Angular Google Maps - automatically set 'center' and 'zoom' to fit in all markers

前端 未结 5 1602
暗喜
暗喜 2021-02-19 05:51

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

相关标签:
5条回答
  • 2021-02-19 06:27

    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.

    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.

    0 讨论(0)
  • 2021-02-19 06:27

    angular-google-maps has taken care of this feature. All you need to do is add fit="true" attribute in your markers directive (ui-gmap-markers). Example : <ui-gmap-markers models="map.markers" fit="true" icon="'icon'"> Please refer the document http://angular-ui.github.io/angular-google-maps/#!/api

    0 讨论(0)
  • 2021-02-19 06:29

    The answer has been posted for another problem: https://stackoverflow.com/a/23690559/5095063 After that you have just to add this line:

    $scope.map.control.getGMap().fitBounds(bounds);
    
    0 讨论(0)
  • 2021-02-19 06:37

    Also use timeout to make sure it is digested properly

     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);
              });
    
    0 讨论(0)
  • 2021-02-19 06:45

    Thanks to all the replies, I got this code which is working perfectly for me:

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

    I hope it will help to someone.

    0 讨论(0)
提交回复
热议问题