且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查纬度和经度是否在圆圈Google地图内

更新时间:2023-08-30 14:12:52

对于这样短的距离,当精度不必精确到厘米时,可以将地球表面视为平面。计算中心点纬度处从度数到公里的转换,然后 Pythagoran定理可以用于获取dinstance:

$ p $ 函数arePointsNear(checkPoint,centerPoint,km){
var ky = 40000/360 ;
var kx = Math.cos(Math.PI * centerPoint.lat / 180.0)* ky;
var dx = Math.abs(centerPoint.lng - checkPoint.lng)* kx;
var dy = Math.abs(centerPoint.lat - checkPoint.lat)* ky;
return Math.sqrt(dx * dx + dy * dy)}

演示: http://jsfiddle.net/Guffa/57gQa/



注意:代码不考虑考虑你是否通过0/360经度。如果是这样的话,你首先必须正常化经度。


Below is the desired result, which I'm looking for

What I would like to know is:

I have created the circle using center point lat lang and radius around it. Now I want to know, how to check (calculate) if a latitude and longitude is either inside or outside the area I would appreciate if you can give me code example in Javascript. I'm using Google Maps API V3.

I found this function but not working as expected for me:

function arePointsNear(checkPoint, centerPoint) {
    var sw = new google.maps.LatLng(centerPoint.lat() - 0.005, centerPoint.lng() - 0.005);
    var ne = new google.maps.LatLng(centerPoint.lat() + 0.005, centerPoint.lng() + 0.005);
    var bounds = new google.maps.LatLngBounds(sw, ne);
    if (bounds.contains (checkPoint)){
        return true;
    }
    return false;
}

Any help will be great.. thanks in advance!!

For such short distances, and when the accuracy doesn't have to be exact to the centimeter, you can treat the surface of the earth as flat. Calculate a conversion from degrees to kilometers at the latitude of the center point, then the Pythagoran theorem can be used to get the dinstance:

function arePointsNear(checkPoint, centerPoint, km) {
  var ky = 40000 / 360;
  var kx = Math.cos(Math.PI * centerPoint.lat / 180.0) * ky;
  var dx = Math.abs(centerPoint.lng - checkPoint.lng) * kx;
  var dy = Math.abs(centerPoint.lat - checkPoint.lat) * ky;
  return Math.sqrt(dx * dx + dy * dy) <= km;
}

Demo: http://jsfiddle.net/Guffa/57gQa/

Note: The code doesn't take into consideration if you are passing the 0/360 longitude. If that is the case, you would first have to normalise the longitudes.