【问题标题】:Clearing map layers with react-leaflet and hooks使用 react-leaflet 和 hooks 清除地图图层
【发布时间】: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


【解决方案1】:

作为 Falke Design 的mentions in a comment above

将圈子添加到特征组,然后每次locationfound 被触发,您调用featuregroup.clearLayers(),然后将新圈子添加到特征组

这解决了问题。

工作代码框是here

【讨论】:

    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 2021-09-13
    相关资源
    最近更新 更多