Leaflet.js center the map on a group of markers

后端 未结 1 1178
情深已故
情深已故 2021-01-31 07:35

I\'m using Leaflet.js and would like some way to centre the map on the markers I have so that all are within the user\'s view when the page launches. If all the mar

1条回答
  •  北海茫月
    2021-01-31 07:58

    You can use L.LatLngBounds in order to create an area to zoom to.

    First, create a bounds and pass it an array of L.LatLngs:

    var bounds = new L.LatLngBounds(arrayOfLatLngs);
    

    This will create a bounds that will encapsulate every point that is contained in the array. Once you have the bounds, you can fit the bounds of the map to match your created bound:

     map.fitBounds(bounds);
    

    This will zoom the map in as far as it can go, while still containing every point in your array.

    Alternatively, you can also call the fitBounds method by simply calling it and passing in an array of L.LatLng objects. For example:

    map.fitBounds([[1,1],[2,2],[3,3]]);
    

    This would function exactly the same, without the need to create a specific L.LatLngBounds object.

    0 讨论(0)
提交回复
热议问题