能否从leaflet导出geojson以保存地图状态?
我希望将标记、缩放和地图中心存储起来以便以后加载。
有许多种方法可以在leaflet上加载geojson,但我找不到任何选项将地图导出为geojson...
能否从leaflet导出geojson以保存地图状态?
我希望将标记、缩放和地图中心存储起来以便以后加载。
有许多种方法可以在leaflet上加载geojson,但我找不到任何选项将地图导出为geojson...
目前没有“开箱即用”的选项可以将地图上所有的标记导出为GeoJSON,但你可以很容易地自己完成。Leaflet的L.Marker
有一个toGeoJSON
方法:
返回标记的GeoJSON表示形式(GeoJSON点要素)。
http://leafletjs.com/reference.html#marker-togeojson
例如:
// Create a marker
var marker = new L.Marker([0, 0]);
// Get the GeoJSON object
var geojson = marker.toGeoJSON();
// Log to console
console.log(geojson);
将会输出到你的控制台:
{
"type":"Feature",
"properties":{},
"geometry":{
"type":"Point",
"coordinates":[0,0]
}
}
如果您想将添加到地图中的所有标记存储在GeoJSON集合中,可以执行以下操作:
// Adding some markers to the map
var markerA = new L.Marker([0, 0]).addTo(map),
markerB = new L.Marker([1, 1]).addTo(map),
markerC = new L.Marker([2, 2]).addTo(map),
markerD = new L.Marker([3, 3]).addTo(map);
// Create an empty GeoJSON collection
var collection = {
"type": "FeatureCollection",
"features": []
};
// Iterate the layers of the map
map.eachLayer(function (layer) {
// Check if layer is a marker
if (layer instanceof L.Marker) {
// Create GeoJSON object from marker
var geojson = layer.toGeoJSON();
// Push GeoJSON object to collection
collection.features.push(geojson);
}
});
// Log GeoJSON collection to console
console.log(collection);
将输出到你的控制台:
{
"type":"FeatureCollection",
"features":[{
"type":"Feature",
"properties":{},
"geometry":{
"type":"Point",
"coordinates":[0,0]
}
},{
"type":"Feature",
"properties":{},
"geometry":{
"type":"Point",
"coordinates":[1,1]
}
},{
"type":"Feature",
"properties":{},
"geometry":{
"type":"Point",
"coordinates":[2,2]
}
},{
"type":"Feature",
"properties":{},
"geometry":{
"type":"Point",
"coordinates":[3,3]
}
}]
}
编辑: 但是,正如QP发现的那样,如果您能够将标记放入L.LayerGroup
、L.FeatureGroup
或L.GeoJSON
图层中,您可以使用它的toGeoJSON
方法来返回一个 GeoJSON 要素集合:
返回图层组的 GeoJSON 表示形式(GeoJSON FeatureCollection)。
http://leafletjs.com/reference.html#layergroup-togeojson
如果您想存储地图的当前范围(中心和缩放),您可以通过执行以下操作将其简单添加到集合中:
var bounds = map.getBounds();
var collection = {
"type": "FeatureCollection",
"bbox": [[
bounds.getSouthWest().lng,
bounds.getSouthWest().lat
], [
bounds.getNorthEast().lng,
bounds.getNorthEast().lat
]],
"features": []
};
您可以使用成员和L.Map
的setBounds
方法来恢复它。就是这样。您可以将其发送到服务器或通过dataurl下载,任何您喜欢的方式都可以。希望这有所帮助,祝好运。
FeatureGroup
图层并将其添加到地图中:var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var marker = new L.marker([lat, lon]).addTo(drawnItems);
var collection = drawnItems.toGeoJSON();
var bounds = map.getBounds();
collection.bbox = [[
bounds.getSouthWest().lng,
bounds.getSouthWest().lat,
bounds.getNorthEast().lng,
bounds.getNorthEast().lat
]];
// Do what you want with this:
console.log(collection);
L.FeatureLayer
的toGeoJSON
方法,因为您说您无法在任何地方找到解决方案(我认为在文档中已经明确说明),并且需要一个L.Map
的解决方案。我将在我的答案中添加它,以便其他用户可以完整地了解并避免混淆。 - iH8