Cómo obtener el centro de un polígono en Google maps v3?


No necesita ser 100% correcto, puede ser el centro del rectángulo delimitador.

Author: Brian Webster, 2010-06-21

5 answers

Algoritmo:

Recorre todos los puntos del polígono. Para todos los puntos buscar;

  • x1, la coordenada x más baja
  • y1, la coordenada y más baja
  • x2, la coordenada x más alta
  • y2, la coordenada y más alta

Ahora tienes el rectángulo delimitador, y puedes calcular el centro usando:

center.x = x1 + ((x2 - x1) / 2);
center.y = y1 + ((y2 - y1) / 2);
 54
Author: Matthew Scharley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-20 21:53:21

La respuesta de Mateo es una buena solución. Sin embargo, al usar la API v3 de Google Maps, es posible que desee pasar cada punto del polígono a un LatLngBounds object through the extend() method, and then finally call the getCenter() method on the LatLngBounds object. Considere el siguiente ejemplo:

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

// 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)
];

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

// The Center of the Bermuda Triangle - (25.3939245, -72.473816)
console.log(bounds.getCenter());
 173
Author: Daniel Vassallo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:30

Puede extender la clase de polígono con su propia versión de la función faltante, llamémosla my_getBounds ():

google.maps.Polygon.prototype.my_getBounds=function(){
    var bounds = new google.maps.LatLngBounds()
    this.getPath().forEach(function(element,index){bounds.extend(element)})
    return bounds
}

Y luego usarlo en código como este :

myPolygon.my_getBounds().getCenter()

... etc, debería ser equivalente al comportamiento v2

 42
Author: furiozo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-07 22:32:48

Respuesta de@Matthew Scharley este es mi algoritmo. Probablemente sea malo. Sé amable. Lo escribí porque la función getCenter () en la api V3 solo funciona para rectángulos y círculos, no para polígonos.

function polygonCenter(poly) {
    var lowx,
        highx,
        lowy,
        highy,
        lats = [],
        lngs = [],
        vertices = poly.getPath();

    for(var i=0; i<vertices.length; i++) {
      lngs.push(vertices.getAt(i).lng());
      lats.push(vertices.getAt(i).lat());
    }

    lats.sort();
    lngs.sort();
    lowx = lats[0];
    highx = lats[vertices.length - 1];
    lowy = lngs[0];
    highy = lngs[vertices.length - 1];
    center_x = lowx + ((highx-lowx) / 2);
    center_y = lowy + ((highy - lowy) / 2);
    return (new google.maps.LatLng(center_x, center_y));
  }
 5
Author: Jared Beach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-20 20:14:04

Tenga en cuenta que en el caso de un polígono cóncavo, el centro del rectángulo delimitador podría estar completamente fuera del polígono. Si sus polígonos pueden estar cóncavos, yo recomendaría usar el centro del círculo inscrito más grande como el "centro" del polígono. Puedes ver un algoritmo bastante simple aquí (p. 4). Si su tarea es colocar una etiqueta en el polígono, esto también dará los resultados más estéticamente agradables (en cuyo caso recomendaría usar este método incluso si sus polígonos podría no ser cóncava).

 1
Author: gkdm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-23 13:24:25