如何使用谷歌地图API显示替代路线 [英] How to display alternative route using google map api

查看:82
本文介绍了如何使用谷歌地图API显示替代路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用谷歌地图,我有点卡住了。我想为我的源和目标点显示替代路线。目前我正在使用完美工作并显示正确结果的代码,但唯一的问题是此代码仅显示我的起始和目标路径的单个路由。



这是我的 JSFIDDLE WORKING DEMO



以下是我在jsfiddle演示链接中使用的示例代码

HTML代码:

 < h1>计算您的路线< / h1> 
< form id =calculate-routename =calculate-routeaction =#method =get>
< label for =from>发件人:< / label>
< input type =textid =fromname =fromrequired =requiredplaceholder =地址size =30/>
< br />

< label for =to>收件人:< / label>
< input type =textid =toname =torequired =requiredplaceholder =Another addresssize =30/>
< a id =to-linkhref =#>取得我的位置< / a>
< br />

< input type =submit/>
< input type =reset/>
< / form>

JS CODE:

 < script> 
函数calculateRoute(from,to){
//中心初始化为意大利那不勒斯
var myOptions = {
zoom:10,
center:new google.maps .LatLng(40.84,14.25),
mapTypeId:google.maps.MapTypeId.ROADMAP
};
//绘制地图
var mapObject = new google.maps.Map(document.getElementById(map),myOptions);

var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin:from,
destination:to,
provideRouteAlternatives:true,
travelMode:google.maps.DirectionsTravelMode.DRIVING,
unitSystem:google.maps.UnitSystem.METRIC
};
directionsService.route(
directionsRequest,
函数(响应,状态)
{
if(status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map:mapObject,
directions:response
});
}
else
$ (#error)。append(无法检索您的路线< br />);
}
);

$ b $(document).ready(function(){
//如果浏览器支持Geolocation API
if(typeof navigator.geolocation == (您的浏览器不支持Geolocation API);
return;
}

(#error)。 $(#from-link,#to-link)。click(function(event){
event.preventDefault();
var addressId = this.id.substring(0,this.id .indexOf( - ));

navigator.geolocation.getCurrentPosition(function(position){
var geocoder = new google.maps.Geocoder();
geocoder。 geocode({
location:new google.maps.LatLng(position.coords.latitude,position.coords.longitude)
},
function(results,status){$ b $ (状态== google.maps.GeocoderStatus.OK)
$(#+ addressId).val(results [0] .formatted_address);
else
$(#错误)。append(无法检索您的地址&
);
});
},
函数(positionError){
$(#error)。append(Error:+ positionError.message +< br />);
},
{
enableHighAccuracy:true,
timeout:10 * 1000 // 10 seconds
});
});

$(#calculate-route)。submit(function(event){
event.preventDefault();
calculateRoute($(#from).val (),$(#to)。val());
});
});
< / script>

您可以在演示中看到当您输入出发点和目的地点时,它会为您提供单一路线但我还需要在地图中显示替代路线



非常感谢您的帮助,并深表感谢!

解决方案

你需要做的是在接收响应对象响应的回调函数中检查directionsService.route函数调用返回的路由数。路由将是一个数组,因此循环遍历它并使用循环计数器来设置DirectionsRenderer使用的routeIndex。当然,在我看来,这样的结果并不是我们所希望的,因为替代路线的各个部分经常会重叠,所以用户不会总是在视觉上明显地看到其他多余的线路正在发生什么。以及如果您实际显示文本方向,将需要不同的DOM元素来显示每组方向,然后它也令人困惑,哪一组是为了什么。我宁愿建议仅显示主要(第一)路线并且具有按钮以显示可供选择的选择,点击时将仅显示那些路线&方向。这就是说,这里是你的问题的修复:

  directionsService.route(
directionsRequest,
function (response,status){
if(status == google.maps.DirectionsStatus.OK){
for(var i = 0,len = response.routes.length; i< len; i ++) {
google.maps.DirectionsRenderer({
map:mapObject,
directions:response,
routeIndex:i
});
}
$ else {
$(#error)。append(Unable to retrieve your route< br />);
}
}
);


I am using google map and i am bit of stuck at one point. i want to display alternative route for my source and destination point. currently i am using the code which is working perfectly and displaying correct result but the only the problem is that this code displaying only single route for my starting and destination path.

Here is my JSFIDDLE WORKING DEMO

Here is sample code which i am using in jsfiddle demo link:

HTML CODE:

<h1>Calculate your route</h1>
<form id="calculate-route" name="calculate-route" action="#" method="get">
  <label for="from">From:</label>
  <input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
  <a id="from-link" href="#">Get my position</a>
  <br />

  <label for="to">To:</label>
  <input type="text" id="to" name="to" required="required" placeholder="Another address" size="30" />
  <a id="to-link" href="#">Get my position</a>
  <br />

  <input type="submit" />
  <input type="reset" />
</form>  

JS CODE:

<script>
  function calculateRoute(from, to) {
    // Center initialized to Naples, Italy
    var myOptions = {
      zoom: 10,
      center: new google.maps.LatLng(40.84, 14.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // Draw the map
    var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

    var directionsService = new google.maps.DirectionsService();
    var directionsRequest = {
      origin: from,
      destination: to,
      provideRouteAlternatives: true,
      travelMode: google.maps.DirectionsTravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC
    };
    directionsService.route(
      directionsRequest,
      function(response, status)
      {
        if (status == google.maps.DirectionsStatus.OK)
        {
          new google.maps.DirectionsRenderer({
            map: mapObject,
            directions: response
          });
        }
        else
          $("#error").append("Unable to retrieve your route<br />");
      }
    );
  }

  $(document).ready(function() {
    // If the browser supports the Geolocation API
    if (typeof navigator.geolocation == "undefined") {
      $("#error").text("Your browser doesn't support the Geolocation API");
      return;
    }

    $("#from-link, #to-link").click(function(event) {
      event.preventDefault();
      var addressId = this.id.substring(0, this.id.indexOf("-"));

      navigator.geolocation.getCurrentPosition(function(position) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
        },
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK)
            $("#" + addressId).val(results[0].formatted_address);
          else
            $("#error").append("Unable to retrieve your address<br />");
        });
      },
      function(positionError){
        $("#error").append("Error: " + positionError.message + "<br />");
      },
      {
        enableHighAccuracy: true,
        timeout: 10 * 1000 // 10 seconds
      });
    });

    $("#calculate-route").submit(function(event) {
      event.preventDefault();
      calculateRoute($("#from").val(), $("#to").val());
    });
  });
</script>

you can see in the demo when you enter starting point and destination point it will give you single route accordingly but i need to display alternative route as well in the map.

Thanks in advance for your help and much appreciated

解决方案

What you need to do is check how many routes are returned by the directionsService.route function call, within the callback function which receives the response object response.routes will be an array, so loop through it and use the loop counter to set the routeIndex for the DirectionsRenderer to use. Of course this resulting output is not at all in my opinion desirable, as very often segments of alternative routes will overlap so it won't always be visually obvious to a user whats going on with the other extra lines. As well as if you actually display the text directions, will need different DOM element for display of each set of directions, and then it's confusing too which set is for what. I would rather advise showing the main (first) route only and having buttons to display alternatives which upon clicking would show only those routes & directions. That said, here is the fix for your question:

directionsService.route(
    directionsRequest,
    function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            for (var i = 0, len = response.routes.length; i < len; i++) {
                new google.maps.DirectionsRenderer({
                    map: mapObject,
                    directions: response,
                    routeIndex: i
                });
            }
        } else {
            $("#error").append("Unable to retrieve your route<br />");
        }
    }
);

这篇关于如何使用谷歌地图API显示替代路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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