Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 circle (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

like image 679
Lucas Pelegrino Avatar asked Feb 17 '11 09:02

Lucas Pelegrino


2 Answers

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");
like image 123
Tomik Avatar answered Oct 25 '22 03:10

Tomik


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:

Approximate Haversine formula

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.

like image 27
marshall.ward Avatar answered Oct 25 '22 02:10

marshall.ward