如何在Google地图API中沿原点和目的地之间的路线获取地点(例如加油站) [英] How to to Get Places (e.g Gas Stations) along Route Between Origin and Destination in Google Maps API

查看:76
本文介绍了如何在Google地图API中沿原点和目的地之间的路线获取地点(例如加油站)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否让我知道是否有可能在Google地图API中获取所有地点的列表,例如沿着始发地和目的地之间的路线加油站? 此处是我尝试列出所有加油站或休息区(或任何Google Maps API支持的地点类型)的链接,根据方向支持的路线,两点之间。



以及我的代码到目前为止:

  var directionsDisplay; 
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(49.216364,-122.811897);
var oceanBeach = new google.maps.LatLng(50.131446,-119.506838);

函数initialize(){
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
center:haight
}
map = new google .maps.Map(document.getElementById('map-canvas'),mapOptions);
directionsDisplay.setMap(map);

calcRoute();


函数calcRoute(){
var request = {
origin:haight,
destination:oceanBeach,
travelMode:google。 maps.TravelMode.DRIVING
};
directionsService.route(request,function(response,status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
}
});
}

google.maps.event.addDomListener(window,'load',initialize);

编辑部分:

  //请求方向请求
directionService.route(request,function(result,status){
if(status == google.maps.DirectionsStatus.OK){
directionsRenderer.setDirections(result);

//围绕第一条路径的概述路径的框
var path = result.routes [0] .overview_path;
var boxes = (路径,距离);
drawBoxes(boxes);
} else {
alert(Directions queries failed:+ status);
}

for(var i = 0; i< boxes.length; i ++){
var bounds = box [i];
//在这个边界执行搜索
}



});


解决方案


  1. 使用 RouteBoxer 获取一组google.maps。包含路线的LatLngBounds对象。

    $使用Places库搜索地点。 b $ b

    请注意,对位置请求存在查询限制和配额,因此对于较长的路线,这可能不实际。

    示例



    (但是,看看结果如何分组,它看起来像地方服务是围绕边界的中心,而不是在边界,但它可能已经足够满足您的需求)。



    代码片段:
    $ b

    var boxpolys = null; var directions = null; var routeBoxer = null; var distance = null; // kmvar service = null; var gmarkers = []; var boxes = null; var infowindow = new google.maps.InfoWindow(); function initialize(){//默认地图视图为大陆US var mapOptions = {center :new google.maps.LatLng(40,-80.5),mapTypeId:google.maps.MapTypeId.ROADMAP,zoom:8}; map = new google.maps.Map(document.getElementById(map),mapOptions); service = new google.maps.places.PlacesService(map); routeBoxer = new RouteBoxer(); directionService = new google.maps.DirectionsService(); directionsRenderer = new google.maps.DirectionsRenderer({map:map}); //如果URL末尾有任何参数,它们将位于location.search //看起来像?marker = 3//跳过第一个字符,我们对?不感兴趣var query = location.search.substring(1); //在每个&分隔其余部分字符给出argname = value对的列表var pairs = query.split(&); for(var i = 0; i< pairs.length; i ++){//在第一个=处分割每一对以获得argname和值var pos = pairs [i] .indexOf(=); var argname = pairs [i] .substring(0,pos).toLowerCase(); var value = pairs [i] .substring(pos + 1).toLowerCase(); //处理每个可能的argname - 使用unescape()if theres any spaces of spaces if(argname ==to){document.getElementById('to')。value = unescape(value); } if(argname ==from){document.getElementById('from')。value = unescape(value); } if(argname ==dist){document.getElementById('distance')。value = parseFloat(value); } if(argname ==type){document.getElementById('type')。value = unescape(value); } if(argname ==keyword){document.getElementById('keyword')。value = unescape(value);} } if(argname ==name){document.getElementById('name')。value = unescape(value); } if(argname ==submit){route(); }}} function route(){//清除地图中以前的任何路线框clearBoxes(); //将距离转换为从英里到公里的距离,将距离转换为距离= parseFloat(document.getElementById(distance).value)* 1.609344; var request = {origin:document.getElementById(from)。value,destination:document.getElementById(to)。value,travelMode:google.maps.DirectionsTravelMode.DRIVING} //发出方向请求directionService.route(请求,函数(结果,状态){if(status == google.maps.DirectionsStatus.OK){directionsRenderer.setDirections(result); //围绕第一条路径的概述路径框var path = result.routes [0] .overview_path; boxes = routeBoxer.box(path,distance); // alert(boxes.length); drawBoxes(); findPlaces(0);} else {alert(Directions queries failed:+ status);}}) ;} //将map数组绘制为mapfunction中的多段线drawBoxes(){boxpolys = new Array(boxes.length); for(var i = 0; i< boxes.length; i ++){boxpolys [i] = new google.maps.Rectangle({bounds:boxes [i],fillOpacity:0,strokeOpacity:1.0,strokeColor:'#000000 ',strokeWeight:1,map:map}); }} function findPlaces(searchIndex){var type = document.getElementById('type')。value; var keyword = document.getElementById('keyword').value; var name = document.getElementById('name').value; var request = {bounds:boxes [searchIndex],};如果(!! type&&(type!=)){if(type.indexOf(',')> 0)request.types = type.split(','); else request.types = [type]; } if(!! keyword&&(keyword!=))request.keyword = keyword; if(!! name&&(name!=))request.name = name; service.radarSearch(request,function(results,status){if(status == google.maps.places.PlacesServiceStatus.OK){document.getElementById('side_bar')。innerHTML + =bounds [+ searchIndex +] (var i = 0,result; result = results [i]; i ++){var marker = createMarker(result);}} else {document.getElementById('side_bar()}返回+ results.length +results< br> ').innerHTML + =bounds [+ searchIndex +]返回0个结果< br>& nbsp; status =+ status +< br>;} if(status!= google.maps.places。如果(searchIndex< boxes.length)findPlaces(searchIndex);} else {//延迟1秒并再次尝试setTimeout(findPlaces(+ searchIndex +),1000);}} ); //清除当前在map函数上的盒子clearBoxes(){if(boxpolys!= null){for(var i = 0; i< boxpolys.length; i ++){boxpolys [i] .setMap(null); }} boxpolys = null;} function createMarker(place){var placeLoc = place.geometry.location; if(place.icon){var image = new google.maps.MarkerImage(place.icon,new google.maps.Size(71,71),new google.maps.Point(0,0),new google.maps。 Point(17,34),new google.maps.Size(25,25)); } else var image = {url:https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png,size:new google.maps.Size(7,7),anchor:new google .maps.Point(3.5,3.5)}; var marker = new google.maps.Marker({map:map,icon:image,position:place.geometry.location}); var request = {reference:place.reference}; google.maps.event.addListener(marker,'click',function(){service.getDetails(request,function(place,status){if(status == google.maps.places.PlacesServiceStatus.OK){var contentStr = '< h5>'+ place.name +'< / h5>< p>'+ place.formatted_address; if(!! place.formatted_phone_number)contentStr + ='< br>'+ place.formatted_phone_number; if (!! place.website)contentStr + ='< br>< a target =_ blankhref ='+ place.website +'>'+ place.website +'< / a>'; contentStr + ='< br>'+ place.types +'< / p>'; infowindow.setContent(contentStr); infowindow.open(map,marker);} else {var contentStr =< h5>否结果,status =+ status +< / h5>; infowindow.setContent(contentStr); infowindow.open(map,marker);}});}); gmarkers.push(标记); if(!place.name)place.name =result+ gmarkers.length; var side_bar_html =< a href ='javascript:google.maps.event.trigger(gmarkers [+ parseInt(gmarkers.length - 1)+],\click \);'> + place.name +< / a>< br>; document.getElementById('side_bar')。innerHTML + = side_bar_html;} google.maps.event.addDomListener(window,'load',initialize);

      html,body,#map_canvas {margin:0;填充:0; height:100%;}  

    < script src = https://maps.googleapis.com/maps/api/js?libraries=places\"></script><script src =https://cdn.rawgit.com/googlemaps/v3-utility-library /master/routeboxer/src/RouteBoxer.jstype =text / javascript>< / script>< table border =1> < TR> < td valign =top> < div id =mapstyle =width:600px; height:500px;>< / div> < / TD> < TD> < div id =side_barstyle =width:200px; height:600px; overflow:auto>< / div> < / TD>至少< input type =textid =distancevalue =3size =2>从< input type =text开始的路线里程< / tr>< id =fromvalue =denver/> to< input type =textid =tovalue =oklahoma city,OK/>< input type =submitonclick =route )/>< br>< label>< />< / label>< input type =textid =typevalue =gas_station/>< label> keyword< / label>< input type =textid =keywordvalue =/>< label> name< / label>< input type =textid =namevalue =/>< div id =towns>< / div>

    Can you please let me know if it is possible to get list of all places for example Gas Stations along Route Between Origin and Destination in Google Maps API? Here is a link that I am trying to list all Gas Stations or Rest areas ( or any of Google Maps API Supported Place Types)between two points ans based on a Direction supported route.

    and this my code so far:

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    var haight = new google.maps.LatLng(49.216364,-122.811897);
    var oceanBeach = new google.maps.LatLng(50.131446,-119.506838);
    
    function initialize() {
      directionsDisplay = new google.maps.DirectionsRenderer();
      var mapOptions = {
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: haight
    }
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      directionsDisplay.setMap(map);
    
        calcRoute();
     }
    
    function calcRoute() {
      var request = {
      origin: haight,
      destination: oceanBeach,
      travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
       if (status == google.maps.DirectionsStatus.OK) {
           directionsDisplay.setDirections(response);
          }
     });
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    

    Edited Part:

    // Make the directions request
      directionService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsRenderer.setDirections(result);
    
          // Box around the overview path of the first route
          var path = result.routes[0].overview_path;
          var boxes = routeBoxer.box(path, distance);
          drawBoxes(boxes);
        } else {
          alert("Directions query failed: " + status);
        }
    
          for (var i = 0; i < boxes.length; i++) {
      var bounds = box[i];
      // Perform search over this bounds 
    }
    
    
    
      });
    }
    

    解决方案

    1. Use the RouteBoxer to get an array of google.maps.LatLngBounds objects that cover the route.
    2. for each of those bounds use the Places library to search for the places.

    Note that there are query limits and quotas on the places requests, so for long routes this may not be practical.

    example

    (however, looking at how the results are grouped, it looks like the places service is searching around the center of the bounds, rather than in the bounds, but it might be good enough for your needs).

    code snippet:

    var map = null;
    var boxpolys = null;
    var directions = null;
    var routeBoxer = null;
    var distance = null; // km
    var service = null;
    var gmarkers = [];
    var boxes = null;
    var infowindow = new google.maps.InfoWindow();
    
    function initialize() {
      // Default the map view to the continental U.S.
      var mapOptions = {
        center: new google.maps.LatLng(40, -80.5),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 8
      };
    
      map = new google.maps.Map(document.getElementById("map"), mapOptions);
      service = new google.maps.places.PlacesService(map);
    
      routeBoxer = new RouteBoxer();
    
      directionService = new google.maps.DirectionsService();
      directionsRenderer = new google.maps.DirectionsRenderer({
        map: map
      });
    
      // If there are any parameters at eh end of the URL, they will be in  location.search
      // looking something like  "?marker=3"
    
      // skip the first character, we are not interested in the "?"
      var query = location.search.substring(1);
    
      // split the rest at each "&" character to give a list of  "argname=value"  pairs
      var pairs = query.split("&");
      for (var i = 0; i < pairs.length; i++) {
        // break each pair at the first "=" to obtain the argname and value
        var pos = pairs[i].indexOf("=");
        var argname = pairs[i].substring(0, pos).toLowerCase();
        var value = pairs[i].substring(pos + 1).toLowerCase();
    
        // process each possible argname  -  use unescape() if theres any chance of spaces
        if (argname == "to") {
          document.getElementById('to').value = unescape(value);
        }
        if (argname == "from") {
          document.getElementById('from').value = unescape(value);
        }
        if (argname == "dist") {
          document.getElementById('distance').value = parseFloat(value);
        }
        if (argname == "type") {
          document.getElementById('type').value = unescape(value);
        }
        if (argname == "keyword") {
          document.getElementById('keyword').value = unescape(value);
        }
        if (argname == "name") {
          document.getElementById('name').value = unescape(value);
        }
        if (argname == "submit") {
          route();
        }
      }
    
    }
    
    function route() {
      // Clear any previous route boxes from the map
      clearBoxes();
    
      // Convert the distance to box around the route from miles to km
      distance = parseFloat(document.getElementById("distance").value) * 1.609344;
    
      var request = {
        origin: document.getElementById("from").value,
        destination: document.getElementById("to").value,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      }
    
      // Make the directions request
      directionService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsRenderer.setDirections(result);
    
          // Box around the overview path of the first route
          var path = result.routes[0].overview_path;
          boxes = routeBoxer.box(path, distance);
          // alert(boxes.length);
          drawBoxes();
          findPlaces(0);
        } else {
          alert("Directions query failed: " + status);
        }
      });
    }
    
    // Draw the array of boxes as polylines on the map
    function drawBoxes() {
      boxpolys = new Array(boxes.length);
      for (var i = 0; i < boxes.length; i++) {
        boxpolys[i] = new google.maps.Rectangle({
          bounds: boxes[i],
          fillOpacity: 0,
          strokeOpacity: 1.0,
          strokeColor: '#000000',
          strokeWeight: 1,
          map: map
        });
      }
    }
    
    
    function findPlaces(searchIndex) {
      var type = document.getElementById('type').value;
      var keyword = document.getElementById('keyword').value;
      var name = document.getElementById('name').value;
      var request = {
        bounds: boxes[searchIndex],
      };
      if (!!type && (type != "")) {
        if (type.indexOf(',') > 0)
          request.types = type.split(',');
        else
          request.types = [type];
      }
      if (!!keyword && (keyword != "")) request.keyword = keyword;
      if (!!name && (name != "")) request.name = name;
      service.radarSearch(request, function(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"
          for (var i = 0, result; result = results[i]; i++) {
            var marker = createMarker(result);
          }
        } else {
          document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns 0 results<br>&nbsp;status=" + status + "<br>";
        }
        if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
          searchIndex++;
          if (searchIndex < boxes.length)
            findPlaces(searchIndex);
        } else { // delay 1 second and try again
          setTimeout("findPlaces(" + searchIndex + ")", 1000);
        }
    
      });
    }
    
    // Clear boxes currently on the map
    function clearBoxes() {
      if (boxpolys != null) {
        for (var i = 0; i < boxpolys.length; i++) {
          boxpolys[i].setMap(null);
        }
      }
      boxpolys = null;
    }
    
    function createMarker(place) {
      var placeLoc = place.geometry.location;
      if (place.icon) {
        var image = new google.maps.MarkerImage(
          place.icon, new google.maps.Size(71, 71),
          new google.maps.Point(0, 0), new google.maps.Point(17, 34),
          new google.maps.Size(25, 25));
      } else var image = {
        url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
        size: new google.maps.Size(7, 7),
        anchor: new google.maps.Point(3.5, 3.5)
      };
    
      var marker = new google.maps.Marker({
        map: map,
        icon: image,
        position: place.geometry.location
      });
      var request = {
        reference: place.reference
      };
      google.maps.event.addListener(marker, 'click', function() {
        service.getDetails(request, function(place, status) {
          if (status == google.maps.places.PlacesServiceStatus.OK) {
            var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
            if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
            if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
            contentStr += '<br>' + place.types + '</p>';
            infowindow.setContent(contentStr);
            infowindow.open(map, marker);
          } else {
            var contentStr = "<h5>No Result, status=" + status + "</h5>";
            infowindow.setContent(contentStr);
            infowindow.open(map, marker);
          }
        });
    
      });
      gmarkers.push(marker);
      if (!place.name) place.name = "result " + gmarkers.length;
      var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
      document.getElementById('side_bar').innerHTML += side_bar_html;
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);

    html,
    body,
    #map_canvas {
      margin: 0;
      padding: 0;
      height: 100%;
    }

    <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
    <script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/routeboxer/src/RouteBoxer.js" type="text/javascript"></script>
    <table border="1">
      <tr>
        <td valign="top">
          <div id="map" style="width: 600px; height: 500px;"></div>
        </td>
        <td>
          <div id="side_bar" style="width:200px; height: 600px; overflow: auto"></div>
        </td>
      </tr>
    </table>
    Box within at least
    <input type="text" id="distance" value="3" size="2">miles of the route from
    <input type="text" id="from" value="denver" />to
    <input type="text" id="to" value="oklahoma city, OK" />
    <input type="submit" onclick="route()" />
    <br>
    <label>type</label>
    <input type="text" id="type" value="gas_station" />
    <label>keyword</label>
    <input type="text" id="keyword" value="" />
    <label>name</label>
    <input type="text" id="name" value="" />
    <div id="towns"></div>

    这篇关于如何在Google地图API中沿原点和目的地之间的路线获取地点(例如加油站)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆