在我的例子中,我追踪了从我的地理位置到奥马哈海滩博物馆诺曼底法国的路线
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function geolocationSuccess(position) {
var destination="49.366973,-0.882042";
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
direction = new google.maps.DirectionsRenderer({
map : mapObject,
suppressMarkers : true
// panel : panel // Dom element pour afficher les instructions d'itinéraire
});
if(userLatLng && destination){
var request = {
origin : userLatLng,
destination : destination,
travelMode : google.maps.DirectionsTravelMode.DRIVING // Mode de conduite
}
var directionsService = new google.maps.DirectionsService(); // Service de calcul d'itinéraire
directionsService.route(request, function(response, status){ // Envoie de la requête pour calculer le parcours
if(status == google.maps.DirectionsStatus.OK){
direction.setDirections(response); // Trace l'itinéraire sur la carte et les différentes étapes du parcours
}
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
console.log(myRoute.steps[i].instructions+' -> '+myRoute.steps[i].distance.value);
}
console.log(myRoute.steps[0].instructions)
$("#route").html('Dans '+myRoute.steps[0].distance.value+' m '+myRoute.steps[0].instructions);
readbyTTS(myRoute.steps[0].instructions);
var follow = navigator.geolocation.watchPosition(function(position) {
geolocationSuccess(position);
});
});
}
}
function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br />";
}
function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation)
{
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
<style type="text/css">
#map {
width: 800px;
height: 600px;
}
</style>
</head>
<body>
<h1></h1>
<div id="map"></div>
<p><span id="route"></span></p>
<p id="error"></p>
</body>
</html>
感谢您的帮助 KILROY
答案 0 :(得分:1)
您可以尝试使用Google Maps Directions API,它是一种使用HTTP请求计算位置之间路线的服务。
此服务通常用于计算静态(预先知道)地址的方向,以便在地图上放置应用程序内容;此服务不是为了实时响应用户输入而设计的。
查看此SO question以获取更多信息。