我使用 google map api 3
根据用户输入的地址在 google map
上定位商店。地址到latlong
的转换是使用geocoding
完成的,我的代码工作正常。现在,我的客户希望我绘制搜索区域中的商店以及靠近该区域(近 2 英里)的商店,并计算它们的距离。我想要的一个例子是 this site和 this one 。我的工作 Javascript
如下
var markers = response.d.split('^^');
var latlng = new google.maps.LatLng(51.474634, -0.195791);
var mapOptions1 = {
zoom: 14,
center: latlng
}
var geocoder = new google.maps.Geocoder();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions1);
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].formatted_address
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data);
infoWindow.open(map, marker);
});
})(marker, data);
上面的代码看起来很奇怪,我对 body onload
进行了初始化,并且我的 markers
数组包含所有地址,并且 geocode
将它们转换为 latlong
和 marker
绘制它们。
我希望 api 为我提供从搜索位置到每个商店的更近的地址和距离。我怎样才能得到它?
更新
距离计算可以使用 MrUpsidown 的答案来完成,但我无法到达附近的地方。我去了here并发现 https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=7500&types=library&sensor=false&key=AIzaSyDRn2crkKMALHkQAOyadm-d2u_bIPeBA1o
提供了数据但我不知道如何有效地阅读它,按照建议我尝试使用下面的代码在 jason 中获取它
$.getJSON("https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=7500&types=library&sensor=false&key=AIzaSyDRn2crkKMALHkQAOyadm-d2u_bIPeBA1o", function (data) {
alert(data);
});
但运气不好:(我错过了什么?
最佳答案
你必须自己计算距离。您可以使用 geometry library以及 computeDistanceBetween
方法。
例如:
var latlng = new google.maps.LatLng(51.474634, -0.195791);
然后在地理编码器中:
var distance = google.maps.geometry.spherical.computeDistanceBetween(latlng, results[0].geometry.location);
如果您希望它们以特定顺序显示,您需要将这些标记及其距离存储在一个数组中,并对它们进行排序。
关于javascript - 查找输入位置和附近位置的商店并计算它们与搜索位置的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24673402/