Check if a latitude and longitude is within a circle google maps

前端 未结 3 2106
灰色年华
灰色年华 2020-12-08 03:26

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

\"enter

<

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 03:53

    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 Pythagorean theorem can be used to get the distance:

    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 have to normalize the longitudes first.

提交回复
热议问题