【发布时间】:2020-07-14 06:43:47
【问题描述】:
我正在为react-leaflet 构建一个自定义插件,以使用传单的locate 方法定位用户。
它基本上可以工作,但是有一个问题是图层在关闭和重新打开位置之间没有清除。每次切换定位按钮时,locate 应该重新开始。
这是问题的codesandbox。当您切换按钮时,圆圈会变得更暗,因为图层会相互堆叠。
这是组件:
import React, { useEffect, useState, useRef } from 'react'
import L from 'leaflet'
import { useLeaflet } from 'react-leaflet'
import LocationSearchingIcon from '@material-ui/icons/LocationSearching';
import MapButton from './MapButton'
function Locate() {
const { map } = useLeaflet();
const [locate, setLocate] = useState(false);
function toggleLocate() {
setLocate(!locate)
}
console.log(locate)
const layerRef = useRef(L.layerGroup());
useEffect(() => {
if (locate) {
map.removeLayer(layerRef.current)
map.locate({ setView: false, watch: true, enableHighAccuracy: true }) /* This will return map so you can do chaining */
.on('locationfound', function (e) {
L.circleMarker([e.latitude, e.longitude], {
radius: 10,
weight: 3,
color: 'white',
fillColor: 'blue',
fillOpacity: 1
}).addTo(layerRef.current);
L.circle([e.latitude, e.longitude], e.accuracy / 2, {
weight: 1,
color: 'blue',
fillColor: 'blue',
fillOpacity: 0.2
}).addTo(layerRef.current);
window.localStorage.setItem('accuracy', e.accuracy)
map.setView([e.latitude, e.longitude], 16)
layerRef.current.addTo(map)
})
.on('locationerror', function (e) {
alert("Location error or access denied.");
})
} if (!locate) {
map.stopLocate();
map.removeLayer(layerRef.current);
}
}, [locate, map]);
return (
<MapButton
title={locate ? 'Click to disable location' : 'Click to locate'}
onClick={toggleLocate}
left
top={102}
>
<LocationSearchingIcon fontSize="small" style={{ color: locate ? 'orange' : '' }} />
</MapButton>
)
}
export default Locate
我将不胜感激任何停止层堆叠的解决方案或提示,并正确清除按钮已切换。谢谢
【问题讨论】:
-
将圈子添加到功能组中,然后每次触发
locationfound,您调用featuregroup.clearLayers(),然后将新的圈子添加到功能组中 -
@FalkeDesign 谢谢,这解决了问题
标签: reactjs leaflet react-hooks react-leaflet