How to calculate the center of multiple polygons in the Javascript Google Maps API?

Let's say I have an array of polygons that contains a bunch of lat / long coordinates used to draw these areas on the map:

// These polygons are just an example to illustrate structure, they are not my actual polygons

var polygons = [ 
    [
       {lat: 1, lng: 2},
       {lat: 3, lng: 4},
       {lat: 5, lng: 6},
       {lat: 1, lng: 2},
    ],
    [
       {lat: 7, lng: 8},
       {lat: 9, lng: 10},
       {lat: 11, lng: 12},
       {lat: 7, lng: 8},
    ],
];

During map initialization How to set the initial map viewport to the center around all polygons?

Here is an image illustrating what I mean:

How do I want the map to behave

+4
source share
2 answers

You can create a LatLngBounds object . For each point in your polygons, expand the Bounds object to include that point. Then update the map to fit these boundaries.

Something like that:

var bounds = new google.maps.LatLngBounds();

for (var i = 0; i < polygons.length; i++) {
    for (var j = 0; j < polygons[i].length; j++) {
        bounds.extend(polygons[i][j]);
    }
}

map.fitBounds(bounds);
map.setCenter(bounds.getCenter());

, : , bounds.extend {lat: 1, lng: 2} . , LatLng.

:

bounds.extend(new google.maps.LatLng(polygons[i][j].lat, polygons[i][j].lng));
+4

var styledMap = new google.maps.StyledMapType(styles);

var mapOptions = {
    //backgroundColor: '#000',
    //draggable:false,
    scrollwheel: false,
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    draggable: false,
    disableDoubleClickZoom: true,
    overviewMapControl: false,
    panControl: false,
    rotateControl: false,
    streetViewControl: false,
    zoomControl:false,
    noClear: true,
    zoom: 6,
    center: new google.maps.LatLng(12.1, 122), //<----- set the center here
    mapTypeId: google.maps.MapTypeId.SATELLITE
};

var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

map.mapTypes.set('map_style', styledMap);`enter code here`

center: new google.maps.LatLng(12.1, 122), //<----- set the center here
-1

Source: https://habr.com/ru/post/1612542/


All Articles