简体   繁体   中英

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>
  );
}

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)
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM