在谷歌地图上找到最近的针脚

Ben*_*ter 2 javascript google-maps geocoding google-maps-api-3

我一直在使用javascript Google Maps API来构建以下地图:http://springhillfarm.com.au/locations-map/现在我想在用户搜索搜索栏中的位置时列出最近的5个引脚.

尝试进入像"North Epping"这样的郊区,地图将使用以下功能很好地移动:

$("#searchclick").click(function(){

    var address = document.getElementById('searchbar').value;

    var address = address + " Australia";

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            var latitude2 = results[0].geometry.location.lat();
            var longitude2 = results[0].geometry.location.lng();
            var relocate = new google.maps.LatLng(latitude2, longitude2);
            map.setCenter(relocate);

            map.setZoom(12);

            } //when status is OK

        }); // geocode
    });
Run Code Online (Sandbox Code Playgroud)

但现在我真的希望它返回最近的5个引脚.

怎么可能在javascript中?

sq2*_*sq2 6

我注意到你的生产代码 - 我可能会添加/可能会进行大量优化! - 使用以下内容获得您的位置和一堆标记:

var myLatlng = new google.maps.LatLng(-37.5759571, 143.8064523);
var marker0 = new google.maps.Marker({ position: new google.maps.LatLng(-37.7994512, 144.9643374), map: map, title:"Toothpicks, 720 Swanston Street Carlton 3052 VIC", icon:image });
var marker1 = new google.maps.Marker({ position: new google.maps.LatLng(-31.9097004, 115.8485327), map: map, title:"Good Life Shop, Shop 7 Dog Swamp Shopping Centre, Yokine WA 6060", icon:image });
Run Code Online (Sandbox Code Playgroud)

等等...

如果您在数组中有这些标记,例如:

var markers = [ marker0, marker1, etc... ]
Run Code Online (Sandbox Code Playgroud)

一个简单的方法是使用一点毕达哥拉斯来获得当前位置和所有标记之间的距离.就像是:

// make a new array of markers since you probably don't want to modify the existing array
var markersByDistance = [];
for ( var i = 0; i < markers.length; i++ ) {
    var marker = markers[i];

    // using pythagoras does not take into account curvature, 
    // but will work fine over small distances.
    // you can use more complicated trigonometry to 
    // take curvature into consideration
    var dx = myLatlng.longitude - marker.longitude;
    var dy = myLatlng.latitude - marker.latitude;
    var distance = Math.sqrt( dx * dx + dy * dy );

    markersByDistance[ i ] = marker;
    markersByDistance[ i ].distance = distance;

}

// function to sort your data...
function sorter (a,b) { 
    return a.distance > b.distance ? 1 : -1;
}

// sort the array... now the first 5 elements should be your closest points.
markersByDistance.sort( sorter );
Run Code Online (Sandbox Code Playgroud)

这一切都可能毫无意义,因为Google Maps API可能会为您本地执行此操作.