Google Maps v3 fitBounds() Zoom too close for single marker

前端 未结 17 2128
别那么骄傲
别那么骄傲 2020-12-12 23:28

Is there a way to set a max zoom level for fitBounds()? My problem is that when the map is only fed one location, it zooms in as far as it can go, which really

17条回答
  •  感动是毒
    2020-12-12 23:47

    I really like mrt's solution and it works perfectly if you've always only have one point to work with. I did however find that if the bounding box was not based on one point, but the points were very close together, this could still cause the map to be zoomed in too far.

    Here's a way to first check if the points are within a defined distance of each other, then if they are smaller than that minimum distance, extend the bounds by that minimum distance:

    var bounds = new google.maps.LatLngBounds();
    // here you extend your bound as you like
    
    // ...
    
    var minDistance = 0.002;
    var sumA = bounds.getNorthEast().lng() - bounds.getSouthWest().lng();
    var sumB = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
    
    if((sumA < minDistance && sumA > -minDistance) 
    && (sumB < minDistance && sumB > -minDistance)){
    var extendPoint1 = new google.maps.LatLng(bounds.getNorthEast().lat() + minDistance, bounds.getNorthEast().lng() + minDistance);
        var extendPoint2 = new google.maps.LatLng(bounds.getNorthEast().lat() - minDistance, bounds.getNorthEast().lng() - minDistance);
        bounds.extend(extendPoint1);
        bounds.extend(extendPoint2);
    }
    

    Hope this helps someone!

提交回复
热议问题