Pergunta

Hi i'm wanting to create a map that, when a function is called, generates directions to a point based on the users current geolocation. I have tried to do this and so far my attepts have been fruitless, here is my current JS code:

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = latlon;
var end = "Darwin, NSW, Australia";
var request = 
{
   origin:start,
   destination:end,
   travelMode: google.maps.DirectionsTravelMode.DRIVIN
};

function initialize() 
{
   if (navigator.geolocation)
   {
     navigator.geolocation.getCurrentPosition(showPosition);
   }

   function showPosition(position)
   {

     directionsDisplay = new google.maps.DirectionsRenderer();
     var latlon = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
     var mapOptions = 
      {
        zoom:15,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: latlon
      }
      map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
      directionsDisplay.setMap(map);
   } 
 }

 function getdirections() 
 {
    directionsService.route(request, function(response, status) 
    {
      if (status == google.maps.DirectionsStatus.OK) 
      {
        directionsDisplay.setDirections(response);
      }
    });

 }

Any Help would be greatly appreciated, but keep in mind it must use the google maps api, v3. Thank you :)

Foi útil?

Solução

Please checkout this jsfiddle,

Here i have hard-coded the starting position and end position is the users current position.

Is this what you are looking for ?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top