MacMac MacMac - 1 year ago 100
SQL Question

Radius/nearest results - Google Maps API

First of all I'm using Google Maps API v3. I have one big map that shows all the results pulled from a database, now I like to implement a feature that shows a radius of nearest results within X kilometres from the current location (served by HTML5 geolocation).

As the map contains all the results, I want to be able to add X kilometres, then it will get submitted that results will be returned the nearest results according to the current location of the user. The whole map should then remove all the out-of-radius markers, leaving the markers that are inside a radius of X kilometres.

I'm requesting an effective code, tutorial or an article on how to do this.


Here the JSFiddle Demo:

I suppose this is one way to do it. You can use Google Map V3 API's circle to create the bounds from your center point or current location. You can specify the radius of the circle in meters with setRadius(radius:number). With the created circle you can loop through your markers and see if they are within the circle's bound using Circle's getBounds object which is a LatLngBounds and check if the marker is within bound or not.

I went ahead and created a small demo that has five points on a map, and when you click on the create circle button it'll make the first marker the center point and draws a circle with a radius of 5000 and filters out the markers that are not with in bound using the method described above:

function createRadius(dist) {
    var myCircle = new google.maps.Circle({
        center: markerArray[markerArray.length - 1].getPosition(),
        map: map,
        radius: dist,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35
    var myBounds = myCircle.getBounds();

    //filters markers
    for(var i=markerArray.length;i--;){
    map.setCenter(markerArray[markerArray.length - 1].getPosition());