I use the react-google-maps/api
for maps in React. I have a polygon on my map and I want to check on each click event if the click happened inside or outside the polygon.
import React from "react";
import { LoadScript, GoogleMap, Polygon } from "@react-google-maps/api";
export default function App() {
const paths = [
{ lat: 52.52549080781086, lng: 13.398118538856465 },
{ lat: 52.48578559055679, lng: 13.36653284549709 },
{ lat: 52.48871246221608, lng: 13.44618372440334 },
{ lat: 52.52549080781086, lng: 13.398118538856465 }
];
const handleClick = (event) => {
console.log(event.latLng);
};
return (
<div className="App">
<LoadScript
id="script-loader"
googleMapsApiKey="MY_API_KEY"
language="en"
region="us"
>
<GoogleMap
mapContainerClassName="App-map"
center={{ lat: 52.52047739093263, lng: 13.36653284549709 }}
zoom={12}
version="weekly"
on
onClick={onClick}
>
<Polygon
paths={paths}
strokeColor={"#FF0000"}
strokeOpacity={0.8}
strokeWeight={2}
fillColor={"#FF0000"}
fillOpacity={0.35}
draggable={true}
/>
</GoogleMap>
</LoadScript>
</div>
);
}
Based on the docs there is a function google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle)
that I can use, so in my case in the handleClick function it would look similar to this: containsLocation(event.latLng, paths)
.
However, I don't know how to call this function, @react-google-maps/api
doesn't export geometry
or poly
. Here is the doc.
How do I use this function?
Thanks to @MrUpsidown !
I added the geometry library to LoadScript, then it's in the window:
<LoadScript
id="script-loader"
googleMapsApiKey="MY_API_KEY"
language="en"
region="us"
libraries={["geometry"]}
>
console.log(window.PolyGeometry);
{containsLocation: ƒ, isLocationOnEdge: ƒ}
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.