Weblurk
Weblurk

Reputation: 6802

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

Let's say I have an array of polygons, which contains a bunch of lat/long coordinates used to draw these areas on a 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},
    ],
];

When initializing the map, How do I set the initial viewport of the map to be centered around all polygons?

Here is an image illustrating what I mean:

How I want the map to behave

Upvotes: 4

Views: 1849

Answers (2)

duncan
duncan

Reputation: 31912

You could construct a LatLngBounds object. For each point in your polygons, extend that Bounds object to include that point. Then update the map to fit those bounds.

Something like this:

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());

One issue you might have is I'm not sure if the bounds.extend will work with the {lat: 1, lng: 2} format for your points. You may have to construct LatLng objects instead.

In which case it would be:

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

Upvotes: 4

agentpx
agentpx

Reputation: 1081

Just a snippet from my old project

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`

Take a look at center property within the code above

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

Upvotes: -1

Related Questions