半径

2010-08-19 58 views
29

我需要知道如何检索谷歌地图API V3可视缩放级别的半径。半径

例如,如果我在缩放级别3,并根据用户的屏幕尺寸(让刚刚说400x400的可视区域)?我如何获得可视区域的“半径”圈子。

另外,我目前正在使用map.fitBounds()为所有点添加到地图,所以我真的所有我需要是所有边界的半径。我想要的是类似于“20英里”的东西,我可以将其输入到我的数据库应用程序中。

回答

72

半径将等于一个来自边界的中心的距离边界的角落。从the calculations from this page使用大圆距离公式,我想出了以下内容:

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()将包含完整的地图视后。但是,如果你LatLngBounds被延伸到包括LatLng点,然后你发出一个map.fitBounds(bounds)建成,API增加了地图的视口的一个位,所以bounds“盒子”具有一定的填充。

如果使用地图目前的检视,从中心到视口的拐角半径可能比你想有一个较大的半径。也许从视口中心到最远视口边缘中间的距离。 (如果地图不是完美的正方形)

+1

Awesomesauce,正是我需要的。谢谢! – 2010-08-20 15:54:23

+0

为了得到这个例子的工作,前3行应该是 'var bounds = map.getBounds(); var center = bounds.getCenter(); var ne = bounds.getNorthEast();' – 2015-04-09 14:04:32

21

重构版本Eric's answer以上使用google.maps.geometry.spherical命名空间(请确保您已加载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); 
} 
+1

完美!帮助我很多地方要求低到不要达到配额太快。 – kosemuckel 2016-11-22 18:03:38

2

我也重构了Eric的回答,我的是作为一个独立的功能,和我返回结果以米为单位(如需要时由Places API search

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 
}