最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - center of a polygon created with mapbox - Stack Overflow

programmeradmin6浏览0评论

I would like to know how to calculate the centre of a polygon created with this code from Mapbox: .js/example/v1.0.0/show-polygon-area/ I would like to place a marker on the centre of the polygon after it's been created. Thanks in advance.

I would like to know how to calculate the centre of a polygon created with this code from Mapbox: https://www.mapbox./mapbox.js/example/v1.0.0/show-polygon-area/ I would like to place a marker on the centre of the polygon after it's been created. Thanks in advance.

Share Improve this question asked Feb 17, 2016 at 22:36 SurfgetSurfget 731 gold badge1 silver badge6 bronze badges 1
  • I have tried to use the following : var center = e.layer.bounds.getCenter(); But it doesn't work. I have found other scripts to calculate the center of a polygon, but I'm not sure where to find the polygon created – Surfget Commented Feb 17, 2016 at 22:54
Add a ment  | 

2 Answers 2

Reset to default 6

To calculate the center of a polygon you first need to get it's bounds, that can be done using the getBounds method of L.Polygon which it enherits from L.Polyline:

Returns the LatLngBounds of the polyline.

http://leafletjs./reference.html#polyline-getbounds

It returns a L.LatLngBounds object which has a getCenter method:

Returns the center point of the bounds

http://leafletjs./reference.html#latlngbounds-getcenter

It returns a L.LatLng object which you can use to create a 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);

Or you can shorthand it:

var polygon = new L.Polygon(coordinates).addTo(map);

var marker = new L.Marker(polygon.getBounds().getCenter()).addTo(map);

Using that in the Mapbox example would look something like this:

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();
}

You can use turf library.turf.center(features) gives you a point feature at the absolute center point of all input features. where features in your case will be the polygon selected which you can get using mapboxDraw.getAll()

发布评论

评论列表(0)

  1. 暂无评论