Google Maps API: Calculate Center/Zoom of Polyline

僤鯓⒐⒋嵵緔 提交于 2019-12-03 05:39:45

问题


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 coordinates from the overlay, but that really does not represent the center of the overlay. Therefore when I load the map, it is not centered on the overlay.

Does anyone have a good method for centering the map on the overlay, by calculating the center, not hard coding it?

var latlng = new google.maps.LatLng(38.269239, -122.276010);
    var myOptions = {
        zoom: 15,//Calculate this somehow?
        center: latlng,// Calculate value from array of coordinates?
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/3320925/google-maps-api-calculate-center-zoom-of-polyline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!