Get center of geojson Continent/Country/State with leaflet

故事扮演 提交于 2019-12-02 07:27:26

问题


Is there a way of finding a center for countries/continents which consist of more than one polygon object(ex. USA, Canada, which have an islands besides main land part)? I was trying to use leaflet's Layer.getCenter() or even Layer.getBounds().getCenter(), but those methods certainly don't work for this type of countries and return a "no-go" results.

Example can be seen by the following link (leaflet playground). Just scroll and click on US or Canada and see where circleMarker will appear. Then try clicking on smaller entities, like some islands on south of US, they shall place this marker precisely on center of'em:

http://playground-leaflet.rhcloud.com/voyi/1/edit?html,output


回答1:


Leaflet can only calculate the center of the bounding box of a feature. With a bit of help from other libraries (such as Turf.js) you can calculate the centroid of the polygon or (multipolygon).

In any case, you are getting confused because sometimes the centroid is not within the polygon (or multipolygon):


(source: postgis.net)

(Figure 1. Centroid of a polygon as per PostGIS's ST_Centroid documentation)

So I guess that what you really wanted to ask is:

Given a polygon or multipolygon, how can I calculate a center (or center-like point) which is guaranteed to be within the polygon and looks visually in the center of it, in order to add symbolizers to that point with Leaflet?

And for that, the answer is "pole of inaccessibility" as implemented by polylabel: «the most distant internal point from the polygon outline».



来源:https://stackoverflow.com/questions/42108975/get-center-of-geojson-continent-country-state-with-leaflet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!