通过javascript循环计算用户位置和许多目的地之间的驾驶距离

时间:2015-06-19 00:38:39

标签: javascript json google-maps-api-3

我有一个包含许多位置的json Feed:

  

http://hcafeeds.medcity.net/rss/er/ntx_rss_feed.xml

我计划通过html5地理位置获取用户的位置。此时,我想循环浏览json Feed并输出Feed中的项目以及它们与用户位置的距离。

我已经尝试了使用google maps 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);
  });

我创造了一个小提琴: https://jsfiddle.net/potd25yy/3/

1 个答案:

答案 0 :(得分:1)

您应使用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。到每家医院的距离。希望这有帮助。如果您有其他问题,请告诉我。

https://jsfiddle.net/jqw3g914/1/