javascriptreactjsgoogle-maps-api-3containsmarker

React Google Maps API - containsLocation "b.get is not a function"


I am creating a marker where the map is clicked and I want to know if this marker is inside or outside the polygon. I use the containsLocation function for this, but I keep getting the following error "TypeError: b.get is not a function". Thank you in advance for your answers.

function App() {
  const refPoly = useRef(null);
  const [position, setPosition] = useState(null);

  const center = {
    lat: 25.774,
    lng: -80.19,
  };
  
  const containerStyle = {
    position: "absolute",
    width: "70%",
    height: "70%",
  };

  const bermudaTriangle = [
    { lat: 25.774, lng: -80.19 },
    { lat: 18.466, lng: -66.118 },
    { lat: 32.321, lng: -64.757 },
  ];
  const google = window.google;
  const onHandleClickMap = (event) => {
    setPosition({ lat: event.latLng.lat(), lng: event.latLng.lng() });
    console.log(
      google.maps.geometry.poly.containsLocation(event.latLng, bermudaTriangle)
    );
  };

  return (
    <div className="App">
      <LoadScript
        googleMapsApiKey={GOOGLE_MAPS_API_KEY}
        id="script-loader"
        libraries={["geometry"]}
      >
        <GoogleMap
          mapContainerStyle={containerStyle}
          center={center}
          zoom={18}
          onClick={onHandleClickMap}
        >
          <Polygon
            ref={refPoly}
            paths={bermudaTriangle}
            strokeColor="#0000FF"
            strokeOpacity={0.8}
            strokeWeight={2}
            fillColor="#0000FF"
            fillOpacity={0.35}
          />
          {position && <Marker position={position} />}
        </GoogleMap>
      </LoadScript>
    </div>
  );
}

Solution

  • I had the same issue; I solved it like this:

    Instead of:

    const bermudaTriangle = [
        { lat: 25.774, lng: -80.19 },
        { lat: 18.466, lng: -66.118 },
        { lat: 32.321, lng: -64.757 },
      ];
    

    ...I wrote the bermudaTriangle like this:

     const bermudaTriangle = new window.google.maps.Polygon({
                paths: polygons[0].paths,
              });
    
    
            console.log(window.google.maps.geometry.poly.containsLocation(
                { lat: event.latLng.lat(), lng: event.latLng.lng() },
                bermudaTriangle)
            );