简体   繁体   中英

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--;){
         if(!myBounds.contains(markerArray[i].getPosition()))
             markerArray[i].setMap(null);
    }
    map.setCenter(markerArray[markerArray.length - 1].getPosition());
    map.setZoom(map.getZoom()+1);
}

This solution just has one major flaw - it fetches data in a rectangle, not in a circle.

If you don't want to query any more data than required - use the haversine formula in SQL:

SELECT
    id,
    (3959 *
        acos(
            cos(radians(37)) *
            cos(radians(lat)) *
            cos(radians(lng) - radians(-122)) +
            sin(radians(37)) *
            sin(radians(lat))
        )
    ) AS distance
FROM markers
HAVING distance < 25
ORDER BY distance
LIMIT 0 , 20;

Also checkout Creating a Store Locator with PHP, MySQL & Google Maps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM