我已经使用Maps API创建了Google Map,现在我想找到最接近给定位置的n
标记。我发现this Fiddle展示了如何找到最接近的单个标记,如何适应它以便找到最接近的n
标记,而不仅仅是单个最接近的标记?
function find_closest_marker(event) {
var distances = [];
var closest = -1;
for (i = 0; i < markers.length; i++) {
var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
distances[i] = d;
if (closest == -1 || d < distances[closest]) {
closest = i;
}
}
console.log('Closest marker is: ' + markers[closest].getTitle());
}
答案 0 :(得分:0)
这不是有史以来最优雅的解决方案,但是假设原始源代码可以完成这项工作。
function find_closest_markers(event, n) {
var markers_distances = [];
for (i = 0; i < markers.length; i++) {
var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
markers_distances[i] = {
distance: d,
marker: markers[i]
}
}
var closest_markers = markers_distances.sort((a, b) => {return a.distance-b.distance}).slice(0,n)
return closest_markers.map((item) => {return item.marker})
}