Search code examples
reactjsreact-google-maps

Check if marker is visible on ViewPort google-maps-react


I am Currently working on a website like zillow.com, And I have to show data on the right side of map corresponding to the markers visible on map and whenever the user drags map I have to check for new markers on the map and show on the right panel.

const { isLoaded, loadError } = useJsApiLoader({
      googleMapsApiKey: "APIKEY",
      libraries: libraries
  });
  const mapRef = useRef();
  const onMapLoad = useCallback((map) => {
      mapRef.current = map;
  }, [])
return isLoaded && (
      <>
  <GoogleMap mapContainerStyle={mapContainerStyle}
     center={center}
     zoom={9.1}
     options={options}
     onLoad={onMapLoad}
     onDragEnd={() => console.log("DRAGGED")}
     >
    sellerData.map((element, index) => {
                          return (
                              <>
                                  <Marker
                                      key={index}
                                      position={
                                          {
                                              lat: element.Marker.lat, lng: element.Marker.lng
                                          }}
                                      icon={{
                                          url: icon,
                                          scaledSize: new window.google.maps.Size(40, 40)
                                      }}
                                  />
</GoogleMap>
<>
)```

Solution

  • Map.getBounds().getNorthEast() will get you the top east lat and lng & getBounds().getSouthWest() will get you the bottom left lat and lng. TRY This:

    const OnDragEnd= ()=>{
    let ne = this.map.getBounds().getNorthEast();
    let sw = this.map.getBounds().getSouthWest();
     console.log(ne.lat() + ";" + ne.lng());
     console.log(sw.lat() + ";" + sw.lng());
    }
    

    Thanks me later😀