简体   繁体   中英

Get center of geojson Continent/Country/State with leaflet

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

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):

http://postgis.net/docs/images/st_centroid03.png

(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».

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM