我需要知道如何获取Google地图API V3中可视化缩放级别的半径。
例如,如果我处于缩放级别3,并且根据用户屏幕尺寸(假设为400x400可视区域),那么我如何获取可视区域的“半径”圆形范围。
或者,我目前正在使用map.fitBounds()方法对我添加到地图上的所有点进行调整,所以我只需要获取所有边界的半径。我的需求是想要类似于“20英里”的内容,可以输入到我的数据库应用程序中。
我需要知道如何获取Google地图API V3中可视化缩放级别的半径。
例如,如果我处于缩放级别3,并且根据用户屏幕尺寸(假设为400x400可视区域),那么我如何获取可视区域的“半径”圆形范围。
或者,我目前正在使用map.fitBounds()方法对我添加到地图上的所有点进行调整,所以我只需要获取所有边界的半径。我的需求是想要类似于“20英里”的内容,可以输入到我的数据库应用程序中。
半径等于从边界中心到边界角落的距离。使用此页面的计算中的大圆距离公式,我得出了以下结果:
var bounds = map.getBounds();
var center = bounds.getCenter();
var ne = bounds.getNorthEast();
// r = radius of the earth in statute miles
var r = 3963.0;
// Convert lat or lng from decimal degrees into radians (divide by 57.2958)
var lat1 = center.lat() / 57.2958;
var lon1 = center.lng() / 57.2958;
var lat2 = ne.lat() / 57.2958;
var lon2 = ne.lng() / 57.2958;
// distance = circle radius from center to Northeast corner of bounds
var dis = r * Math.acos(Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1));
在进一步研究后,我发现 map.getBounds()
将包含完整的地图视口。但是如果您通过扩展以包括 LatLng
点构建了一个LatLngBounds
,然后发出 map.fitBounds(bounds)
命令,API 会略微增加地图的视口,以使 bounds
"盒子" 具有一些内边距。
如果使用地图的当前视口,则从中心到视口角落的半径可能比您想要的半径更长。这可能是从视口中心到最远视口边缘中点的距离。(如果地图不是完美的正方形)
使用 google.maps.geometry.spherical 命名空间重新编写了上面的Eric's answer 的版本(确保您加载了Geometry library 以使其正常工作)。
var bounds = map.getBounds();
var center = map.getCenter();
if (bounds && center) {
var ne = bounds.getNorthEast();
// Calculate radius (in meters).
var radius = google.maps.geometry.spherical.computeDistanceBetween(center, ne);
}
我也重构了Eric的答案,我的代码是一个独立的函数,并且以米为单位返回结果(正如Places API搜索所需)。
function getBoundsRadius(bounds){
// r = radius of the earth in km
var r = 6378.8
// degrees to radians (divide by 57.2958)
var ne_lat = bounds.getNorthEast().lat() / 57.2958
var ne_lng = bounds.getNorthEast().lng() / 57.2958
var c_lat = bounds.getCenter().lat() / 57.2958
var c_lng = bounds.getCenter().lng() / 57.2958
// distance = circle radius from center to Northeast corner of bounds
var r_km = r * Math.acos(
Math.sin(c_lat) * Math.sin(ne_lat) +
Math.cos(c_lat) * Math.cos(ne_lat) * Math.cos(ne_lng - c_lng)
)
return r_km *1000 // radius in meters
}
var bounds = map.getBounds(); var center = bounds.getCenter(); var ne = bounds.getNorthEast();
- Electric Sheep