6

I want generate a html file including Leaflet library to show an OpenStreetMap view with a polygon. The polygon on the map should be centered. To do so i followed this discussion, but its still unclear to me, how to center an arbitrary polygon and autozoom it. Autozoom means to me, that the polygon is completly in the visible map excerpt and fills it.

As example this would be the desired result:

enter image description here

This is my code so far:

    var map;
    var ajaxRequest;
    var plotlist;
    var plotlayers=[];

    function initmap() {
        // set up the map
        map = new L.Map('map');

        /* --- Replace for different URL for OSM tiles */
        var url_base ='URL_TO_MY_OPENSTREETMAPS_SERVER';
        var latitude = 50.2222;
        var longtitude = 3.322343;
        var poly = L.polygon([
           [50.2222, 3.322343],
           [50.2322, 3.323353],
           [...]
        ]);


        // create the tile layer with correct attribution
        var osmUrl=url_base+'{z}/{x}/{y}.png';
        var osmAttrib='Map data ɠOpenStreetMap contributors';
        var osm = new L.TileLayer(osmUrl, {minZoom: 4, maxZoom: 20, attribution: osmAttrib});       

        // start the map at specific point
        map.setView(new L.LatLng(latitude, longtitude),15);
        map.addLayer(osm);
        poly.addTo(map);
    }

Especially it would be great, if there are "onboard" methods of Leaflet that i can use. How to calculate the center of a polygon is clear to (e.g. here) but maybe there are already implemnented methods i can use.

Solution:

// start the map at specific point
// map.setView(new L.LatLng(latitude, longtitude),15); <- Remove this line
map.addLayer(osm);
poly.addTo(map);
map.fitBounds(poly.getBounds()); // <- Add this line

2 Answers 2

15

Not exactly centering, but if you want the map to be fitted to the polygon:

map.fitBounds(poly.getBounds());

(doc).

1
  • 1
    I will recommend to include a maxZoom -> map.fitBounds(poly.getBounds(),{maxZoom:12}); fitBounds() is better than map.setView(poly.getBounds().getCenter()) but really wants to zoom :) Mar 27, 2016 at 10:59
2

To center more than one polygon is good to know that .fitBounds also accepts an array as argument, so you could do this:

const poly = [polygonA,polygonB,polygonC]; 

const bounds = poly.map(p=>p.getBounds());

mymap.fitBounds(bounds);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.