Center/Set Zoom of Map to cover all visible Markers?

前端 未结 4 1455
孤街浪徒
孤街浪徒 2020-11-28 17:20

I am setting multiple markers on my map and I can set statically the zoom levels and the center but what I want is, to cover all the markers and zoom as much as possible hav

4条回答
  •  误落风尘
    2020-11-28 18:10

    To extend the given answer with few useful tricks:

    var markers = //some array;
    var bounds = new google.maps.LatLngBounds();
    for(i=0;i 15){
      map.setZoom(15);
    }
    
    //Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
    //Note that this will not cover the case if you have 2 markers on the same address.
    if(count(markers) == 1){
        map.setMaxZoom(15);
        map.fitBounds(bounds);
        map.setMaxZoom(Null)
    }
    

    UPDATE:
    Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
    Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

    google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
      this.setZoom(map.getZoom()-1);
    
      if (this.getZoom() > 15) {
        this.setZoom(15);
      }
    });
    map.fitBounds(bounds);
    

提交回复
热议问题