简体   繁体   中英

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

EDIT: Drew the circle that I am using. Ideally the map would be zoomed in to the area within the 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 of course 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 centerpoint 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM