开发者

Google Maps API v3 set zoom level to show a given radius?

I created a map where a user inputs a zipcode and a radius (miles) and I want the map to center on the point created from the zipcode and only display (roughly) the area that would be within that radius. I am creating a Circle with the radius and trying to get the map to fit to that circle. Right now it centers correctly but the area being shown is way more than the radius given.

me.center_map = function(latlng, r)
{
    // latlng is the point of the zipcode
    var circ = new google.maps.Circle();
    circ.setRadius(r * 1609.0);
    circ.setCenter(latlng);
    map.setCenter(latlng);
    map.fitBounds(circ.getBounds());

    // updates markers
    google.maps.event.trigger(map,'dragend')开发者_如何学Python;
};

EDIT: Drew the circle that I am using. Ideally the map would be zoomed in to the area within the radius.

Google Maps API v3 set zoom level to show a given radius?


The call to fitBounds() will zoom to the smallest zoom level that fully contains the bounds. If you were to zoom in 1 more zoom level the radius would not be fully contained within the map.


map.setZoom(map.getZoom() + 1);

This depends how good the particular radius fit (in case it's not always the same). To display the area within the circle one would need to construct a rectangle that has it's corners on the circle's perimeter and fit the map's viewport to it's bounds. Eg. drawing a visible circle and a transparent rectangle with same center-point should work as described by the op.


Since June 2017, the method fitBounds has a second parameter that represents the size of the padding. For those who want to remove it, you just need to pass 0.

Map.map.fitBounds(bounds, 0);

New method signature:

fitBounds(bounds:LatLngBounds|LatLngBoundsLiteral, padding?:number)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜