【发布时间】:2018-10-01 00:47:40
【问题描述】:
我正在使用 Leaflet.js 库制作地图。我有一个事件,在右键单击地图上放置一个标记,我想将每个标记的坐标保存到一个数组或对象数组中。然后我想将它们存储在本地存储中。
var customLayer = new L.layerGroup();
myMap.on('contextmenu', function(e) {
var marker = L.marker(e.latlng,
{icon : flagIcon,
draggable: true,
zIndexOffset : 1000}).addTo(customLayer).addTo(myMap);
customLayer.addTo(myMap);
marker.bindPopup("<b>Custom</b>").openPopup();
});
我确实尝试在本地存储中设置值,但它只保存了第一个键:值对。然后我考虑迭代存储 customMarkers 的数组,但我收到一个错误,即 customLayer.forEach 不是函数。
customLayer.forEach(function(marker) {
var customCoords = marker.getLatLng();
console.log(customCoords);
});
在这里,我将非常感谢您的提示。如果有人想要,这里是传单文档:
https://leafletjs.com/reference-1.3.4.html
与我上一个关于 Leaflet 的问题一样,我对 20 个或更多查询进行了广泛研究,但我没有找到任何问题的答案。我承认我可能问错了问题。如果有,请赐教。
编辑 我在我的事件函数中使用了它,但它只保存最后放置的项目的值。
myStorage = window.localStorage;
mystorage.setItem('coords', e.latlng);
编辑 2
我根据其中一个答案尝试了以下方法,但没有任何反应。
var layers = customLayer.getLayers();
var i;
for(i=0; i<layers.length; i++){
layers[i];//it is what a super class for marker.
//store them away
myStorage = window.localStorage;
myStorage.setItem('coords', layers[i].getLatLng());
}
});
编辑 3
function setJSON(customCoords, coordinates) {
customCoords = 'customCoords';
window.localStorage.setItem(customCoords,
JSON.stringify(coordinates));
}
});
我从以下答案之一尝试了上面的代码,而 localStorage 只是输出未定义。我尝试将字符串作为参数传递,但这给了我意想不到的字符串错误。然后我将参数更改为变量并将字符串分配给它,它仍然不起作用。不过,我找到了解决该问题的方法,并将其发布在下面。
【问题讨论】:
-
显示您尝试保存到本地存储的部分..
-
在底部附近为您编辑。
-
那么您正在为在 LayerGroup 上循环而苦苦挣扎,您是否尝试过 customLayer.getLayer().forEach()?
-
尝试使用
eachLayer方法leafletjs.com/reference-1.3.4.html#layergroup-eachlayer -
关于保存多个
coords的问题,这可能会有所帮助:stackoverflow.com/a/49966216/9613505
标签: javascript leaflet