HTML 5 Geolocation not working with Directions API

北战南征 提交于 2020-01-26 04:34:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!