How can I calculate the center of a polygon with the Google Maps API [closed]

2

How can I calculate the center of a polygon (Polygon) with the Google Maps API?

    
asked by Luis Miguel Baez 12.05.2018 в 00:48
source

1 answer

3

You can use version 3 of the API of Google Maps, you might want to pass each point of the polygon to an object LatLngBounds through the extend () method, and finally, call the getCenter() method on the LatLngBounds object.

Consider the following example:

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

// El triangulo de las Bermudas
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)
];

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

// El centro del triángulo de las Bermudas - (25.3939245, -72.473816)
console.log(bounds.getCenter());

What you're seeing is an object LatLng .

What you can do is simply invoke the functions lat() and lng() :

var lat = suPoligono.su_getBounds().getCenter().lat();
var lng = suPoligono.su_getBounds().getCenter().lng();

Another method I could use would be an Algorithm:

Run through all the points in the polygon. For all the points you will find:

  • x1 , the x lowest coordinate
  • y1 , the y lowest coordinate
  • x2 , x highest coordinate
  • y2 , y highest coordinate

Now you have the bounding rectangle, and you can solve the center using:

center.x = x1 + ((x2 - x1) / 2);
center.y = y1 + ((y2 - y1) / 2);
  

For more information, consult the SO source: How to get the center of a polygon in google maps v3? from where I have taken this answer.

    
answered by 12.05.2018 / 15:35
source