如何在react-map-gl中为GeolocateControl创建自定义按钮

问题描述 投票:0回答:1

我正在使用

react-map-gl
显示我的地图组件,我想要一个自定义按钮来定位用户的位置;我正在使用
GeolocateControl
组件,但是我将
display: 'none'
设置为其默认按钮,对于另一个按钮的
onClick
事件,我将其称为
geoControlRef.current.trigger()
;我第一次调用时,它正确显示了用户位置,但下次单击时,它显示了不是我当前位置的错误位置。有什么问题吗?

const onCurrentLocationClick = () => {
    geoControlRef?.current?.trigger()
  }
<GeolocateControl
              ref={geoControlRef}
              fitBoundsOptions={{
                zoom: 16,
              }}
              showAccuracyCircle={false}
              style={{ display: 'none' }}
              showUserHeading
            />
            <div className="absolute bottom-4 right-4 z-ultra">
              <CircularButton mode="primary" size="medium" onClick={onCurrentLocationClick} icon={locationButtonIcon} />
            </div>
          </>

reactjs mapbox react-map-gl
1个回答
0
投票

发生的事情是

geoControlRef?.current?.trigger()
多次调用,但
<GeolocateControl/>
组件仅在第一次渲染。要解决此问题,您需要使用
useEffect
钩子来触发
<GeolocateControl/>
组件。

useEffect(() => {
  if (!geolocation) {
    geoControlRef.current?.trigger();
  }
}, [geolocation]);
© www.soinside.com 2019 - 2024. All rights reserved.