问题描述
我的 Google 地图中有一个动态生成的标记列表.我希望地图的中心是所有标记的中心,并缩小到足以让所有标记都在视野中.
I have a dynamically generated list of markers within my Google Map. I want the map's center to be the center of all the markers and zoomed out just enough so that all markers are in view.
在计算地图中心方面,也许可以通过遍历所有经纬度并找到中心点来实现.但是,我无法找出计算缩放比例的最佳方法.
In terms of calculating the map center, perhaps this could be possible by iterating through all the latitudes and longitudes and finding the central point. However, I cannot figure out the best way to calculate what the zoom should be.
这有可能实现吗?
模板中正在使用我的地图,如下所示:
My map is being used in the template like this:
<ui-gmap-google-map events="map.events" center="map.center" zoom="map.zoom" draggable="true" options="options">
<ui-gmap-marker ng-repeat="home in filteredHomes = (resCtrl.filteredHomes | orderBy : $storage.params.orderby : $storage.params.reverseOrder)" coords="{latitude: home.location.latitude, longitude: home.location.longitude}" idkey="home.homeId">
</ui-gmap-marker>
</ui-gmap-google-map>
更新
根据@Tiborg 的建议尝试实现 Angular:
Attempted Angular implementation from advice from @Tiborg:
uiGmapGoogleMapApi.then(function(maps) {
$scope.map = {
center: $scope.$storage.params.views.map.location,
zoom: $scope.$storage.params.views.map.zoom,
events: {
click: function() {
var bounds = new google.maps.LatLngBounds();
for (var i in $scope.filteredHomes) {
bounds.extend($scope.filteredHomes[i].location);
}
$scope.map.fitBounds(bounds);
}
}
};
});
这会产生控制台错误:TypeError: undefined is not a function (evaluating 'a.lat()')
推荐答案
在 Google Maps API 中使用 LatLngBounds 类,如下所示:
Use the LatLngBounds class in Google Maps API, like this:
var bounds = new google.maps.LatLngBounds();
for (var i in markers) // your marker list here
bounds.extend(markers[i].position) // your marker position, must be a LatLng instance
map.fitBounds(bounds); // map should be your map class
它可以很好地缩放地图并使其居中以适合您的所有标记.
It will nicely zoom and center the map to fit all your markers.
当然,这是纯 javascript,而不是 angular 版本,因此如果您在以 angular 实现它时遇到问题(或者您无法从获得标记的位置访问地图实例),请告诉我.
Of course, this is the pure javascript, not the angular version, so if you have problems implementing it in angular (or you don't have access to the map instance from where you get the markers), let me know.
这篇关于Angular Google Maps - 自动设置“中心"和“缩放"以适应所有标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!