我在Google地图中有动态生成的标记列表。我希望地图的中心成为所有标记的中心,并缩小到足以让所有标记都在视野中。
在计算地图中心方面,也许这可以通过迭代所有纬度和经度并找到中心点来实现。但是,我无法弄清楚计算缩放应该是什么的最佳方法。
这可能实现吗?
我的地图正在模板中使用,如下所示:
<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实现:
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()')
答案 0 :(得分:17)
在Google Maps API中使用LatLngBounds类,如下所示:
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
它可以很好地缩放和居中地图以适合您的所有标记。
当然,这是纯粹的javascript,而不是角度版本,所以如果您在角度实现它时遇到问题(或者您无法访问从中获取标记的地图实例),那就让我吧知道。
答案 1 :(得分:17)
angular-google-maps已经完成了这项功能。您需要做的就是在markers指令中添加fit =“true”属性(ui-gmap-markers)。
示例:<ui-gmap-markers models="map.markers" fit="true" icon="'icon'">
请参阅文档http://angular-ui.github.io/angular-google-maps/#!/api
答案 2 :(得分:6)
已针对其他问题发布了答案:https://stackoverflow.com/a/23690559/5095063 之后你只需添加这一行:
$scope.map.control.getGMap().fitBounds(bounds);
答案 3 :(得分:4)
感谢所有回复,我得到的代码对我来说非常合适:
var bounds = new google.maps.LatLngBounds();
for (var i = 0, length = $scope.map.markers.length; i < length; i++) {
var marker = $scope.map.markers[i];
bounds.extend(new google.maps.LatLng(marker.latitude, marker.longitude));
}
$scope.map.control.getGMap().fitBounds(bounds);
我希望它会对某人有所帮助。
答案 4 :(得分:0)
还要使用超时来确保它被正确消化
uiGmapIsReady.promise()
.then(function (map_instances) {
var bounds = new google.maps.LatLngBounds();
for (var i in $scope.map.markers) {
var marker = $scope.map.markers[i];
bounds.extend(new google.maps.LatLng(marker.latitude, marker.longitude));
}
$timeout(function() {
map_instances[0].map.fitBounds(bounds);
}, 100);
});