我想在Google地图中显示从当前位置到已知位置的方向。我的代码如下所示:
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var bne = new google.maps.LatLng(-27.572832, 153.065247);
var mapOptions = {
zoom:7,
center: bne
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
navigator.geolocation.getCurrentPosition(
function (pos) {
var start = new google.maps.LatLng(pos.coords.latitiude,
pos.coords.longitude);
var end = 'sunnybank,brisbane';
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
},
function (err) {
alert('ERROR(' + err.code + '): ' + err.message);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
似乎navigator.geolocation.getCurrentPosition()对我没有用,还有其他方法可以检索当前位置并将其传递给启动变量吗?
答案 0 :(得分:1)
根据documentation,getCurrentPosition函数将Position object传递给它的回调函数(它是异步的,因此无法返回任何内容),这不是google.maps.LatLng对象(但包含创建一个所需的信息。
function calcRoute() {
navigator.geolocation.getCurrentPosition(function(pos) {
var start = new google.maps.LatLng(pos.coords.latitiude,
pos.coords.longitude);
var end = 'sunnybank,brisbane';
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert("Directions request failed: "+status);
});
}, function(err) {
alert('ERROR(' + err.code + '): ' + err.message);
});
}
答案 1 :(得分:0)
可能有三个原因: