Google Maps API: Calculate Center/Zoom of Polyline

前端 未结 2 1541
梦毁少年i
梦毁少年i 2021-02-01 16:57

I have an overlay that is dynamically generated from user data, so I need to know how to find the center of that overlay.

Currently, I am just using the first coordinate

相关标签:
2条回答
  • 2021-02-01 17:15

    If you have a list of coordinates, you can loop over them and add them to a LatLngBounds object. Here is a example for the V3 API, but the concept in V2 is similar:

    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < coordinates.length; i++) {
      bounds.extend(coordinates[i]);
    }
    

    After that, you can get the center with:

    bounds.getCenter();
    

    Or alternatively, you can call map.fitBounds() directly, which will center the map around the center of the bounds and adjust the zoom, so that the whole bounds will fit exactly into the view port.

    map.fitBounds(bounds);
    
    0 讨论(0)
  • 2021-02-01 17:19

    Based on @tux21b,

          var bounds = new google.maps.LatLngBounds();
          polyline.getPath().forEach(function(e){//can't do polyline.getPath()[i] because it's a MVCArray
              bounds.extend(e);
          })         
          _map.fitBounds(bounds);
    
    0 讨论(0)
提交回复
热议问题