Search code examples
geolocationleafletgeocoding

GeoLocation - Center a map


I am creating a map with markers with the leaflet library.

var mymap = L.map('mapid', {
        center: [${mapCenter.lat}, ${mapCenter.lng}],
        zoom: 9
});

I am using this algorithm to calculate the center of the map based in all the markers I have to show

        double minLatitude = Double.MAX_VALUE;
        double maxLatitude = Double.MIN_VALUE;

        double minLongitude = Double.MAX_VALUE;
        double maxLongitude = Double.MIN_VALUE;

        for (ViewMarker marker : markers) {

            if (marker.getLng() > maxLongitude) {
                maxLongitude = marker.getLng();
            }

            if (marker.getLng() < minLongitude) {
                minLongitude = marker.getLng();
            }

            if (marker.getLat() > maxLatitude) {
                maxLatitude = marker.getLat();
            }

            if (marker.getLat() < minLatitude) {
                minLatitude = marker.getLat();
            }                       
        }

        double centerLatitude =     (minLatitude  + maxLatitude ) / 2;
        double centerLongitude =    (minLongitude + maxLongitude) / 2;

But as you see in the image, I wouldn't say that the map is in the center

enter image description here


Solution

  • Instantiate a L.LatLngBounds, insert the markers' LatLngs there, and then do a map.fitBounds().

    Alternatively, use a FeatureGroup to hold all the markers inside, as it provides a getBounds().

    Unless you know the basics of geodesy and map projections, do not use naïve solutions like centerlat = (lat1 + lat2) / 2, which is not true for the default Mercator projection.