我想知道如何计算使用来自 Mapbox 的代码创建的多边形的中心:https://www.mapbox.com/mapbox.js/example/v1.0.0/show-polygon-area/ 创建后,我想在多边形的中心放置一个标记。 提前致谢。
最佳答案
要计算多边形的中心,您首先需要获取它的边界,这可以使用 L.Polygon
的 getBounds
方法完成,该方法继承自 L.折线
:
Returns the LatLngBounds of the polyline.
http://leafletjs.com/reference.html#polyline-getbounds
它返回一个 L.LatLngBounds
对象,它有一个 getCenter
方法:
Returns the center point of the bounds
http://leafletjs.com/reference.html#latlngbounds-getcenter
它返回一个 L.LatLng
对象,您可以使用它来创建一个 L.Marker
:
var polygon = new L.Polygon(coordinates).addTo(map);
var bounds = polygon.getBounds();
var center = bounds.getCenter();
var marker = new L.Marker(center).addTo(map);
或者你可以简写:
var polygon = new L.Polygon(coordinates).addTo(map);
var marker = new L.Marker(polygon.getBounds().getCenter()).addTo(map);
在 Mapbox 示例中使用它看起来像这样:
function showPolygonArea(e) {
featureGroup.clearLayers();
featureGroup.addLayer(e.layer);
// Here 'e.layer' holds the L.Polygon instance:
new L.Marker(e.layer.getBounds().getCenter()).addTo(featureGroup);
e.layer.bindPopup((LGeo.area(e.layer) / 1000000).toFixed(2) + ' km<sup>2</sup>');
e.layer.openPopup();
}
关于javascript - 使用 mapbox 创建的多边形的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35469153/