1

I am trying to set up a map that provides directions to Las Vegas from wherever the browser is located. Here is my code sample:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3 Directions Example</title>
<script type="text/javascript"
       src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 600px;">
 <div id="map" style="width: 280px; height: 400px; float: left;"></div>
 <div id="panel" style="width: 300px; float: right;"></div>
</div>

<script type="text/javascript">


navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
var mylat = location.coords.latitude;
var mylong = location.coords.longitude;
}


 var directionsService = new google.maps.DirectionsService();
 var directionsDisplay = new google.maps.DirectionsRenderer();

 var map = new google.maps.Map(document.getElementById('map'), {
   zoom:7,
   mapTypeId: google.maps.MapTypeId.ROADMAP
 });

 directionsDisplay.setMap(map);
 directionsDisplay.setPanel(document.getElementById('panel'));

 var request = {
    origin: 'mylat,mylong',
destination: '35.580789,-105.210571',
   travelMode: google.maps.DirectionsTravelMode.DRIVING
 };

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

</script>
</body>
</html>

If I hard code in the mylat and mylong then the page will load just fine. I have also used the following to verify that these values are properly populated when location is shared:

function GetLocation(location) {
var mylat = location.coords.latitude;
var mylong = location.coords.longitude;
document.write(mylat);
document.write(mylong);
}

I also have tried to write these variables outside of the function and see that they are suddenly null. What can I try to retain the mylat and mylong variables and reuse in the origin: 'mylat,mylong', call?

2
  • These are private variables in the function scope. Make them global or return by the function. Commented Jan 11, 2014 at 22:03
  • This doesn't do anything, also, alerting mylat and mylong doesn't work: jsfiddle.net/t7txk Commented Jan 11, 2014 at 22:07

4 Answers 4

2

There are really two issues that are being confused here. First, variables in JavaScript are scoped to the function in which they are declared, which is why mylat and myLong are only visible inside GetLocation.

Second, the GetLocation function is a callback function that is executed asynchronously. That is, the code that appears below it in the literal source will actually run before that function's body is executed. This is fine -- and it's not necessary to move the variable declarations outside of the function -- as long as you perform all of the operations that rely on these values inside the GetLocation callback itself (on in some other functions that it calls). Like this:

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
    var mylat= location.coords.latitude;
    var mylong = location.coords.longitude;
    var request = {
        origin: mylat + ',' + mylong,
        destination: '35.580789,-105.210571',
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('panel'));
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

Simply moving the declarations outside of GetLocation is not sufficient and everybody telling you that is missing this second point.

See a working example on JSFIDDLE.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this in depth review.
1

this works for me: - setting directions after coordinates returned

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3 Directions Example</title>
<script type="text/javascript"
       src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 600px;">
 <div id="map" style="width: 280px; height: 400px; float: left;"></div>
 <div id="panel" style="width: 300px; float: right;"></div>
</div>

<script type="text/javascript">

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

var map = new google.maps.Map(document.getElementById('map'), {
   zoom:7,
   mapTypeId: google.maps.MapTypeId.ROADMAP
 });

navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
var mylat,mylong,request;
mylat= location.coords.latitude;
mylong = location.coords.longitude;
request = {
    origin: mylat+','+mylong,
destination: '35.580789,-105.210571',
   travelMode: google.maps.DirectionsTravelMode.DRIVING
 };

 directionsDisplay.setMap(map);
 directionsDisplay.setPanel(document.getElementById('panel'));
 directionsService.route(request, function(response, status) {
   if (status == google.maps.DirectionsStatus.OK) {
     directionsDisplay.setDirections(response);
   }
 });
}

</script>
</body>
</html>

3 Comments

This does work, but it has nothing to do with moving the variable declarations to a higher scope and everything to do with the fact that you're doing everything inside the callback. Your advice confuses the two.
Lots of great answers. I tried yours out and it works for my needs. Thanks.
@lwburk thanks for pointing this out. as explained in more detail by you below the problem is the ayscn call. I've edited the answer and upvoted your solution.
0

Move them one level up, outside the function.

Read about variable scopes in javascript:

http://www.mredkj.com/tutorials/reference_js_intro_ex.html

You can also return them with your function, retrieve when you call it.

1 Comment

This does not solve the problem, because GetLocation is still executed asynchronously.
0

You define mylat, mylong variables inside of function scope. So they can be accessible only inside this function.

You should define variables outside function, for example:

var mylat,
    mylong;

function GetLocation(location) {
    mylat = location.coords.latitude;
    mylong = location.coords.longitude;
}

navigator.geolocation.getCurrentPosition(GetLocation);

More information about variable scope - http://msdn.microsoft.com/en-us/library/bzt2dkta(v=vs.94).aspx

1 Comment

This does not solve the problem, because GetLocation is still executed asynchronously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.