Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use containsLocation in react-google-maps/api library

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?

like image 315
Tom Avatar asked Oct 14 '25 04:10

Tom


1 Answers

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: ƒ}

like image 97
Tom Avatar answered Oct 16 '25 18:10

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!