Leaflet map United States and fitBounds

十年热恋 提交于 2020-12-15 05:41:09

问题


I've created a function which adds a few layers to my Leaflet map on page load.
Afterwards, I want it to center the view based up on these layers.

let layerGroup = L.featureGroup();
... 
    // add multiple layers
    layerGroup.addLayer(L.geoJson(feature))
...
leafletMap.addLayer(layerGroup);
leafletMap.fitBounds(layerGroup.getBounds());

It currently works as intended, and the map zooms in in order to fit the bounds.

However, when the United States is one of these layers, the map completely zooms out, because of the Near islands.

Is there a way to fix this issue, and thus zoom in on the United States without the map zooming out?

Thanks in advance


回答1:


This is not so easy to fix, I don't know how your data looks like.

A fix would be to check if the lng coord is negative and then add 360 to it:

L.geoJson(feature,{
  coordsToLatLng: function coordsToLatLng(coords) {
    // the coords came into the function as //lng,lat,alt
    if(coords[0] < 0){
      coords[0] = coords[0]+360;
    }
    // the coords goes out as //lat,lng,alt
    return new L.LatLng(coords[1], coords[0], coords[2]);
  }
})



回答2:


I've "fixed" the issue by simply removing the Near islands coordinates from my geoJson file.

The corresponding coordinates in my case were: [[[172.9041,53.0012],[173.3013,52.9256],[173.1886,52.7957],[172.9443,52.7498],[172.6404,52.8688],[172.6604,53.0086],[172.9041,53.0012]]]

If anyone finds a better solution, please let me know.



来源:https://stackoverflow.com/questions/64385946/leaflet-map-united-states-and-fitbounds

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