开发者

How to check if a given marker is inside a area

Hello everybody o/ I know that this is more a math question than gmap, but I suppose that someone already pass through this =)

In my map, I have cir开发者_如何学JAVAcle (actually I have several of them, but this not change the question), like this: http://code.google.com/intl/pt-BR/apis/maps/articles/mvcfun/step6.html

How do I know if a marker (with latitude X and longitude Y) is inside this circle?

Sorry for the bad english, I'm brazillian =p


In Google Maps JavaScript API v3 you can use geometry library. To enable it you have to slightly change the script URL:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>

The library contains utility functions for the computation of geometric data on sphere. You can utilize it to compute the distance of two points given by their latLngs this way:

var distanceInMetres = google.maps.geometry.spherical.computeDistanceBetween(latLngCircleCenter, latLngPoint);

Now you can easily check if the point is inside the circle (suppose R is in metres):

if(distanceInMetres < R)
   alert("in the circle");


If (lat1, lon1) and (lat2, lon2) are your two points and R is the radius of the circle around your first point, then the distance between the points is given by the haversine formula (or the Great-circle distance). But I believe that for your problem, the angles are small enough to use this approximation:

How to check if a given marker is inside a area

and then check whether d^2 is less than the radius R^2.

But if your latitude and longitude differences are larger than a few degrees, you'll want to use the full haversine formula.


I Recommend you read http://www.movable-type.co.uk/scripts/latlong.html. It provides a number of algorithms for computations of this kind. It includes JavaScript code for the computations.


Basically if you have the coords of circle center (cX,cY) and radius R, and some marker at X,Y you can do the following calculations:

var distanceQuad = (X-cX)*(X-cX)+(Y-cY)*(Y-cY)
if (distanceQuad<=(R*R))
{
 alert("Marker inside circle!");
}

This is from trigonometry. You calculate distance as sqrt(sqr(deltaX)+sqr(deltaY)) and compare it with circle Radius. Given code is a bit optimized to get rid of calculating square root.


It's much easier than you'd expect. Read this answer including a working jsFiddle example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜