Leaflet geosearch - 将结果标记绑定到现有标记

Leaflet geosearch - binding results marker to an existing one

我有一个带有标记的传单地图和一个带有显示其坐标的文本字段的表单。可以移动或拖动标记以更新相应的表单字段。

使用 Leaflet.GeoSearch,当进行搜索(单击自动完成选项)时,将创建标记的新实例,我想做的是更新现有标记的位置和相应的 lat/long 字段(而不是创建新标记)。 根据 this post 可以通过 marker: myCustomMarker 选项指定自定义标记,但它似乎在我的代码中不起作用。

提前致谢

代码如下:

var tileLayer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> Contributors'
});
var latlng = L.latLng(50.5, 30.5);

var map = new L.Map('map', {
'center': latlng,
'zoom': 12,
'layers': [tileLayer]
});

var marker = L.marker(latlng,{
    draggable: true,
    autoPan: true
}).addTo(map);

marker.on('dragend', function (e) {
updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});

map.on('click', function (e) {
marker.setLatLng(e.latlng);
updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});

function updateLatLng(lat,lng) {
document.getElementById('latitude').value = marker.getLatLng().lat;
document.getElementById('longitude').value = marker.getLatLng().lng;
}
const searchControl  = new GeoSearch.GeoSearchControl({
  style: 'bar',
  provider: new GeoSearch.OpenStreetMapProvider ({
  showMarker: true,
  marker: marker, // use custom marker, not working?
}),

});
map.addControl(searchControl);

JSFiddle:

https://jsfiddle.net/rtjLm6uq/

我快速浏览了他们的 source code , 属性 只是用来提取它的值,它实际上不会使用传入的实例,因此永远不会用作你期待。

您的代码还有其他问题。它是:

const searchControl  = new GeoSearch.GeoSearchControl({
  style: 'bar',
  provider: new GeoSearch.OpenStreetMapProvider ({
  showMarker: true,
  marker: marker, // use custom marker, not working?
}),
});

但应该是:

const searchControl  = new GeoSearch.GeoSearchControl({
  style: 'bar',
  provider: new GeoSearch.OpenStreetMapProvider (),
  showMarker: true,
  marker: marker, // use custom marker, not working?
});

最后,为了解决您的问题,您可以改为监听 GeoSearch 事件,更准确地说,监听从结果列表中选择位置时触发的 showlocation 事件,以清理以前的标记,因为该包将始终添加自己的标记(如果启用)。

也就是说,将以下代码添加到您的文件中应该可以解决问题。

map.on('geosearch/showlocation', () => {
  if (marker) {
    map.removeControl(marker);
  }
});

根据您的评论更新

如果您想在使用 GeoSearch 库时保留初始标记属性,您必须自己应用它。这是一个例子:

map.on('geosearch/showlocation', () => {
  if (marker) {
    map.removeControl(marker);
  }
  // The marker class extends the layer class,
  // so you can search for it among the layers
  map.eachLayer(item => {
    if (item instanceof L.Marker) {
      // Once you found it, set the properties
      item.options.draggable = true;
      item.options.autoPan = true;
      // Then enable the dragging. Without this, it wont work
      item.dragging.enable();
    }
  });
});

Demo