最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Google Map circle is loaded twice in my React application using react-google-maps - Stack Overflow

programmeradmin3浏览0评论

I'm using react-google-maps/api to load google maps for my web app. My problem is that two circles are loaded onto the map overtop of each other, when I only want one.

In my main component I'm loading in my google maps component and passing a radius prop to it. When I change the radius, it's evident that there's two circle, as shown here.

This issue is most likely due to React StrictMode, as when I turn it off the problem goes away.

I've tried keeping a reference to the Circle, and then doing circleRef.current.setMap(null);, but this does nothing to solve the problem - two circles still exist on top of one another.

Here's the example code, taken from the react-google-maps/api npm docs

import { useJsApiLoader, GoogleMap, Circle } from "@react-google-maps/api";
import { useState, useCallback, memo } from "react";

const containerStyle = { width: '400px', height: '400px' }
const center = { lat: 48.428420, lng: -123.3656444 };
function GoogleMapComponent({radius}: {radius: number}) {
  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: '...',
  })

  const [map, setMap] = useState<google.maps.Map | null>(null)

  const onLoad = useCallback(function callback(map: google.maps.Map) {
    // This is just an example of getting and using the map instance!!! don't just blindly copy!
    const bounds = new window.google.maps.LatLngBounds(center)
    map.fitBounds(bounds)

    setMap(map)
  }, [])

  const onUnmount = useCallback(function callback(map: google.maps.Map) {
    setMap(null)
  }, [])

  return isLoaded ? (
    <GoogleMap
      mapContainerStyle={containerStyle}
      center={center}
      zoom={12}
      onLoad={onLoad}
      onUnmount={onUnmount}
    >
      <Circle center={center} radius={radius} />
      <></>
    </GoogleMap>
  ) : (
    <></>
  )
}

export default memo(GoogleMapComponent)

Is there a way to fix this so that only one circle appears, without turning off React StrictMode?

发布评论

评论列表(0)

  1. 暂无评论