Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if marker is within circle overlay on Google Maps (Javascript API V3)

I have markers dotted around a map, and a radius (circle overlay) on a marker marking your location (which changes every time you move). Is there any way I can check to see if the other markers come inside the circle?

UPDATE

I got around this by looping through each other marker, and using the geometry library calculating the distance between your marker and the other marker and then a simple if statement to see if it's less than 100 meters.

function checkAllChests() {
    var Current = 0;
    $.each(treasureArray, function() {
        //var thisLocation = treasureArray[Current].getPosition();

        var distanceBetween = Math.ceil(google.maps.geometry.spherical.computeDistanceBetween(treasureArray[Current].getPosition(), marker_me.getPosition()));
        if(distanceBetween < 100) {
            alert('CAN OPEN THIS CHEST');
        }
        Current++;
    });
}

I'd like to note that the above code uses jQuery, so if you aren't using jQuery it won't work.

like image 594
Joey Emery Avatar asked Jan 07 '12 00:01

Joey Emery


1 Answers

Here's a way to add a contains method to the google.maps.Circle class. It first uses the bounding box to exclude a point if it's not even in the bounding box. If it is in the bounding box, then it compares the distance from the point to the center with the radius, and returns true only if the distance is shorter than the radius.

Once you add the javascript below, you can call the contains() method on your circle object.

google.maps.Circle.prototype.contains = function(latLng) {
  return this.getBounds().contains(latLng) && google.maps.geometry.spherical.computeDistanceBetween(this.getCenter(), latLng) <= this.getRadius();
}
like image 196
Mark Avatar answered Nov 20 '22 16:11

Mark