我正在使用Leaflet制作地图,并使用GeoJSON文件中的数据填充地图。我想使用distanceTo函数,但它需要一个latLng对象。有没有办法将GeoJSON的properties.geometry.coordinates'转换'为latLng?
我有一个31个坐标的数组,使用onEachLayer上的push()方法:
var coords = [];
onEachFeature : function(feature,layer) {
coords.push(feature.geometry.coordinates)
//console.log(coords)...
运行之后,coords数组将填充每个坐标的数组。有没有办法将这个数组数组“转换”为latLng对象,以便可以使用ditanceTo?
最终目标是使用distanceTo通过循环运行latLng对象,以便每个弹出窗口显示距中心点的距离。
var low = L.geoJson(hosp, {
pointToLayer: function(feature,latlng) {
return L.circleMarker(latlng, {
color: 'yellow',
weight: 2,
fillColor: 'green',
fillOpacity: .7,
radius:9
});
},
filter: function (feature, layer) {
if(feature.properties.DAILY_PAT <= '600'){
return feature;}
},
onEachFeature : function(feature,layer) {
coords.push(feature.geometry.coordinates)
//console.log(coords)
layer.on('click',function(){
layer.bindPopup("<b>Low Enrollement </b><br>"+"<b>School Name: </b>"
+ feature.properties.FACILITY_N+"<br><b># of Students: </b>"
+ feature.properties.DAILY_PAT).openPopup()
})
;
}
}).addTo(map);
为什么不用Leaflet的LatLng
对象创建坐标数组?
var coords = [];
onEachFeature : function(feature,layer) {
var coordinates = feature.geometry.coordinates;
coords.push(L.LatLng(coordinates[1], coordinates[0])); // paramter's depending on your object
}
然后,使用有点像:
// suppose, centerCoordinates is LatLng object as well
centerCoordinates.distanceTo(coords[0]);
链接到Leaflet上的LngLat
对象:https://leafletjs.com/reference-1.4.0.html#latlng
链接到distanceTo
上的LngLat
方法:https://leafletjs.com/reference-1.4.0.html#latlng
由于你正在产生L.CircleMarker
s和L.CircleMarker
s have a getLatLng()
method,你可以放弃自己处理坐标。在计算距离时,只需参考CircleMarker
实例,例如:
onEachFeature : function(feature,layer) {
var distance = layer.getLatLng().distanceTo(centerPoint);
layer.on('click',function(){
layer.bindPopup("Distance to center: " + distance);
});
}
请注意,在这种情况下,distance
变量存在于每个要素的唯一范围内,因此不需要closures。对onEachFeature()
回调的调用在此处作为闭包。