Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet OSM: Center mapview on polygon

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
like image 245
alex Avatar asked Jan 06 '14 10:01

alex


2 Answers

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

map.fitBounds(poly.getBounds());

(doc).

like image 50
robertklep Avatar answered Nov 17 '22 20:11

robertklep


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);
like image 1
Emeeus Avatar answered Nov 17 '22 19:11

Emeeus