How to update the radius of a Google Maps circle correctly?

54 Views Asked by At

I'm trying to set the radius of a Circle component in Google Maps based on a state variable. When this variable updates, the radius of the Circle also increases, but the old circle stays visible. This only happens when I first change the radius. Any help would be much appreciated.

Screenshot of the problem: enter image description here

My Code:

import React from "react";
import { GoogleMap, useJsApiLoader, Marker, Circle, StandaloneSearchBox } from "@react-google-maps/api";

const center = { lat: 40.41620, lng: -4.34140 }

const mapStyle = {
  width: '100%',
  height: '800px'
};

const containerStyle ={
  width:'100%',
  height:'100vh'
}


export default function App() {

  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: import.meta.env.VITE_GOOGLE_MAPS_KEY
  })

  const [map, setMap] = React.useState(null)
  const [radius, setRadius] = React.useState(500)

  const onLoad = React.useCallback(function callBack(map) {
    const bounds = new window.google.maps.LatLngBounds(center);
    map.zoom = 15
    setMap(map)
  })

  const onUnmount = React.useCallback(function callback(map) {
    setMap(null)
  })

  return isLoaded ?
    (
      <div style={containerStyle}>
        <div className="range setter">
          <p>Radius in KM: {radius}</p>
          <input type="range" min={500} max={5000} step={50} value={radius} onChange={(e) => setRadius(parseInt(e.target.value))} />
        </div>
        <GoogleMap mapContainerStyle={mapStyle} center={center} zoom={10} onLoad={onLoad} onUnmount={onUnmount}>
          <Marker position={center} />
          <Circle center={center} radius={radius} />
        </GoogleMap>
      </div>

    ) : <></>
}
1

There are 1 best solutions below

0
Niels On

I realized this was happening due to StrictMode being enabled. Disabling this resolved it.