我正在使用谷歌地图,我有点卡住了。我想显示我的源点和目的地点的替代路线。目前我正在使用运行良好并显示正确结果的代码,但唯一的问题是该代码仅显示我的起始和目标路径的单一路线。
这是我的JSFIDDLE 工作演示
这是我在 jsfiddle 演示链接中使用的 示例代码:
HTML 代码:
<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代码:
<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>
您可以在演示中看到,当您输入起点和终点时,它会相应地为您提供单条路线,但我还需要在地图中显示替代路线。
有什么方法可以根据“距离”或“交通持续时间”在给定选项之间选择和显示路线?
提前感谢您的帮助,非常感谢