问题
I am trying to use the geolocations API with the Directions service but I get:
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);
}
});
Error : InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object; and not an Object
The marker is created;
回答1:
The geolocation service is asynchronous, you have to use the result in its callback function when/where it is available
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("Възникна проблем при намирането на местонахождението ви!");
}
来源:https://stackoverflow.com/questions/35756481/html-5-geolocation-not-working-with-directions-api