使用react传单和钩子清除地图图层



我正在为react-leaflet构建一个自定义插件,以使用传单的定位方法定位用户。

它基本上可以工作,但有一个问题是图层在关闭位置和重新打开位置之间无法清除。每次切换定位按钮时,locate应重新启动。

这是一个问题的代码沙盒。切换按钮时,随着层堆叠在一起,圆圈会变暗。

这是组件:

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

我将感谢任何解决方案或提示,以停止层堆叠,并清除正确的按钮是切换。感谢

正如Falke Design在上面的评论中提到的:

将圆圈添加到featureGroup,然后每次触发locationfound时,调用featuregroup.clearLayers(),然后将新圆圈添加到featureGroup

这解决了问题。

正在工作的代码沙盒在这里

最新更新