我正在尝试将地理位置API与Directions服务一起使用,但我得到了:
var UserLoc;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat=position.coords.latitude;
var lng=position.coords.longitude;
console.log(lat);
console.log(lng);
UserLoc = new google.maps.LatLng(lat,lng);
var NewMarker = new google.maps.Marker({
position: UserLoc,
draggable: false,
animation: google.maps.Animation.DROP,
map: SEVTmap
});
}
);
}
else {
alert ( "Възникна проблем при намирането на местонахождението ви!" );
}
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(SEVTmap);
var request = {
origin: UserLoc,
destination: Destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
错误:InvalidValueError:在属性origin中:不是字符串;而不是LatLng或LatLngLiteral:不是对象;而不是对象
创建标记;
答案 0 :(得分:1)
地理定位服务是异步的,您必须在其可用的/可用时使用其回调函数中的结果
var UserLoc;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log(lat);
console.log(lng);
UserLoc = new google.maps.LatLng(lat, lng);
var NewMarker = new google.maps.Marker({
position: UserLoc,
draggable: false,
animation: google.maps.Animation.DROP,
map: SEVTmap
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: SEVTmap
});
directionsDisplay.setMap(SEVTmap);
var request = {
origin: UserLoc,
destination: Destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}, function (PositionError) {alert("geolocation error:"+PositionError.code+" msg="+PositionError.message);});
} else {
alert("Възникна проблем при намирането на местонахождението ви!");
}