Google Maps JavaScript API v3: how to get the center lat & lon of a polygon


How to get the center lat & lon of a polygon?

We can do it just by calling polygon.getBounds().getCenter()

// The Bermuda Triangle
var polygonCoords = [
  new google.maps.LatLng(25.774252, -80.190262),
  new google.maps.LatLng(18.466465, -66.118292),
  new google.maps.LatLng(32.321384, -64.757370),
  new google.maps.LatLng(25.774252, -80.190262)
];

var triangle = new google.maps.Polygon({
                 paths: polygonCoords,
                 strokeColor: "#0000FF",
                 strokeOpacity: 0.8,
                 strokeWeight: 2,
                 fillColor: "#FF0000",
                 fillOpacity: 0.35
     });

alert(triangle.getBounds().getCenter());

Note: in Google Maps JavaScript API v2, Polygon had a getBounds() method, but that doesn’t exist for v3 Polygon. You can find that method in this article.

Leave a Reply