Javascript Google Maps API v3 设置缩放级别以显示给定半径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5162950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:53:30  来源:igfitidea点击:

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

javascriptgoogle-maps

提问by roflwaffle

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.

编辑:绘制我正在使用的圆圈。理想情况下,地图将放大到半径内的区域。

enter image description here

在此处输入图片说明

采纳答案by Alex

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.

对 fitBounds() 的调用将缩放到完全包含边界的最小缩放级别。如果您再放大 1 个缩放级别,则半径将不会完全包含在地图中。

回答by Martin Zeitler

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.

要显示圆内的区域,需要构建一个矩形,该矩形的角位于圆的周长上,并使地图的视口适合其边界。

E.g. drawing a visible circle and a transparent rectangle with same centerpoint should work as described by the op.

例如,绘制一个可见圆和一个具有相同中心点的透明矩形应该像操作描述的那样工作。

回答by Roberto Júnior

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.

自 2017 年 6 月以来,fitBounds 方法有第二个参数表示填充的大小。对于那些想要删除它的人,您只需要传递 0。

Map.map.fitBounds(bounds, 0);

New method signature:

新方法签名:

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