在Google地图中find多个地点的中心

我刚刚抄录了这个问题的代码,并运用了我的经纬度。 但是,经纬度是dynamic的,地图的center会根据位置的纬度和经度而变化。

以下是来自其他问题的代码

 <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>Google Maps Multiple Markers</title> <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script> </head> <body> <div id="map" style="width: 500px; height: 400px;"></div> <script type="text/javascript"> var locations = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: new google.maps.LatLng(-33.92, 151.25), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } </script> </body> </html> 

所以我的问题是,如何知道有dynamic位置的地图的中心。 我试过把center留空,但地图没加载。

首先,您可以通过包含所有dynamic生成的位置来创build一个LatLngBounds对象。 使用扩展方法来包含点。 然后,您可以使用getCenter方法获取边界的中心。

更新:

码:

 var bound = new google.maps.LatLngBounds(); for (i = 0; i < locations.length; i++) { bound.extend( new google.maps.LatLng(locations[i][2], locations[i][3]) ); // OTHER CODE } console.log( bound.getCenter() ); 

插图:

在这里输入图像描述

我是通过平均纬度和平均经度并以这些平均值为中心来做到这一点的。

例:

 self.adjustPosition = function () { var lat = 0, lng = 0; if (self.nearbyPlaces().length == 0) { return false; } for (var i = 0; i < self.nearbyPlaces().length; i++) { lat += self.nearbyPlaces()[i].latitude; lng += self.nearbyPlaces()[i].longitude; } lat = lat / self.nearbyPlaces().length; lng = lng / self.nearbyPlaces().length; self.map.setCenter(new window.google.maps.LatLng(lat, lng)); }; 

这种方法不起作用,因为它将平均数字,而不是得到数字(拉特/长)的“中间”。 想想这样,你在美国有6分,在加利福尼亚州有一个,在东南沿海有5个分布在南北。 东海岸的5点在地图上向右(东)加权平均值,而你的中心点在格鲁吉亚周围(东到西)。 如果你想避免使用getCenter,你会希望find最高和最低的东方(纬度+/-和长+/-),并find每个方向的中间,一旦你有极端。

 private LatLng computeCentroid(List<LatLng> points) { double latitude = 0; double longitude = 0; int n = points.size(); for (LatLng point : points) { latitude += point.latitude; longitude += point.longitude; } return new LatLng(latitude/n, longitude/n); 

}