我有一个包含多个位置的 json feed:
我计划通过 html5 地理定位获取用户的位置。此时,我想循环遍历 json feed 并输出 feed 中的项目及其与用户位置的距离。
我已经尝试了使用谷歌地图 API 的所有方法,但我似乎总是在使用该方法的一个小时内遇到障碍。
有人做过类似的事情吗?
更新:这是我现有的代码
会很好地输出医院...只是不知道如何获得距离:
var hcafeed = 'http://hcafeeds.medcity.net/rss/er/ntx_rss_feed.xml';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from rss where url="' + hcafeed + '"') + '&format=json&diagnostics=true&callback=?';
$.getJSON(yql,function(data){
if(data.query.count > 0) {
// Run through hospitals and set html
var hospitals = [];
$.each( data.query.results.item, function( key, val ) {
var hospitalAddress = val.address;
var wait = $.trim(val.description.replace("Mins",""));
var units = (wait == 1) ? " Min" : " Mins";
hospitals.push({
'name' : "<div class='name'>"+val.comments.replace(" ER Wait Time","")+"</div>",
'addy' : "<div class='addy'>"+val.address+"</div>",
'phone' : "<div class='phone'>"+val.phone+"</div>",
'waitOutput' : "<div class='wait'>"+wait+units+"</div>",
'wait' : wait,
'distanceOutput' : "<div class='distance'></div>",
});
});
// Sort array by wait time (default)
hospitals.sort(function(a, b){
return a.wait-b.wait;
});
// Prepare array for output (wrapper)
var output = [];
$.each( hospitals, function( key, val ) {
output.push("<div data-key='"+key+"' data-wait='"+val.wait+"' class='hospital'>"+val.name+val.addy+val.phone+val.waitOutput+val.distanceOutput+"</div>");
});
}
// Print array
$("#hospitals").html( output );
}).fail(function (j, t, e) {
console.error(e);
});
我创建了一个 fiddle : https://jsfiddle.net/potd25yy/3/
最佳答案
您应该使用 Directions Service in Google Maps JavaScript API 而不是距离矩阵计算用户位置和医院之间的路径。
功能:
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
返回一个响应,具有多个路由。第一条路线的距离为:
response.routes[0].legs[0].distance.text
这样就可以将其显示到相应的条目中。
我创建了一个快速演示来计算从 Google, Inc. 到每家医院的距离。希望这有帮助。如果您还有其他问题,请告诉我。
关于javascript - 通过 javascript 循环计算用户位置和许多目的地之间的驾驶距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30928149/