如何解决创建新搜索时如何删除当前的传单标记?
我创建了这个组件,用于在搜索城市时显示标记,但是当我创建新搜索时,会添加一个新标记,但未删除前一个标记。您有解决此问题的想法吗?
import { useState,useEffect } from "react";
import { useMap } from "react-leaflet";
import "leaflet-control-geocoder/dist/Control.Geocoder.js";
import L from "leaflet";
import icon from "./../constants/homeIcon";
import { PrintAddress } from "../components/Map/styles";
const SearchBar = () => {
const map = useMap();
let [printInfo,setPrintinfo] = useState("");
useEffect(() => {
let geocoder = L.Control.Geocoder.nominatim({
geocodingQueryParams: {
limit: 3,addressdetails: 1,namedetails: 1,countrycodes: "fr",},});
L.Control.geocoder({
query: "",placeholder: "Search your address",defaultMarkGeocode: false,geocoder,})
.on("markgeocode",function (e) {
let latlng = e.geocode.center;
L.marker(latlng,{ icon })
.bindPopup(e.geocode.name)
.openPopup()
.addTo(map);
map.panTo(latlng);
L.circle(latlng,{
color: "#000",fillColor: "#7AEDAD",radius: 10000,}).addTo(map);
setPrintinfo(e.geocode.name);
})
.addTo(map);
},[map]);
return <PrintAddress className="printInfo">{printInfo}</PrintAddress>;
};
export default SearchBar;
解决方法
使用组件外部的 layerGroup 来存储圆圈和标记,每次添加新标记时,清除图层组并添加新的图层组,以便下次添加另一个标记时能够将其删除。
const layerGroup = L.layerGroup(); // init the empty layerGroup
const SearchBar = () => {
const map = useMap();
...
L.Control.geocoder({
query: '',placeholder: 'Search your address',defaultMarkGeocode: false,geocoder
})
.on('markgeocode',function (e) {
layerGroup.clearLayers(); // lear the layerGroup from previous stored circle and marker
let latlng = e.geocode.center;
L.marker(latlng,{ icon })
.bindPopup(e.geocode.name)
.openPopup()
.addTo(layerGroup); // add the marker to the layerGroup
map.panTo(latlng);
L.circle(latlng,{
color: '#000',fillColor: '#7AEDAD',radius: 10000
}).addTo(layerGroup); // add the circle to th elayerGroup
setPrintinfo(e.geocode.name);
map.addLayer(layerGroup); // here add the layerGroup to th emap
})
.addTo(map);
},[map]);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。