Uncaught ReferenceError: lat is not defined

Possible duplicate:
JavaScript scope

I have a problem with my script, I want to get the lat, lng value from the pos function, but when I inspect the item in the console, I get this error:

"Uncaught ReferenceError: lat not defined TEST.html: 30 (anonymous function)"

line 30: var latlng = new google.maps.LatLng (lat, lng); This is my complete code:

<script type="text/javascript">

navigator.geolocation.getCurrentPosition (function (pos){
  lat = pos.coords.latitude;
  lng = pos.coords.longitude;
});

  var directionsDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;
  var latlng = new google.maps.LatLng (lat, lng);
  var oceanBeach = new google.maps.LatLng(-6.2501199999999999,106.75937);

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var mapOptions = {
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: latlng
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    directionsDisplay.setMap(map);
  }

  function calcRoute() {
    var selectedMode = document.getElementById("mode").value;
    var request = {
        origin: latlng,
        destination: oceanBeach,
        // Note that Javascript allows us to access the constant
        // using square brackets and a string value as its
        // "property."
        travelMode: google.maps.TravelMode[selectedMode]
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
</script>

      

+3


source to share


2 answers


You have at least two problems:

  • The scope of your variables (they are defined in a subfunction and are not available in the scope you are trying to use them in)

  • The function getCurrentPosition()

    is asynchronous. This means that it ends some time after it is called, and only completes when it calls the completion callback function. So it is not finished yet at the time you are trying to use the results after the function call.

To handle getCurrentPosition()

as asynchronous, you must do it like this:



navigator.geolocation.getCurrentPosition (function (pos){
    var lat = pos.coords.latitude;
    var lng = pos.coords.longitude;
    var latlng = new google.maps.LatLng (lat, lng);
    var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);      
    // any further code that uses these variables
});

// no code here that uses the results of getCurrentPosition() 
// because it has not completed yet

      

You can see a similar question and answer here: Not being able to handle the asynchronous nature of navigator.geolocation

0


source


Will there be a problem if you write it like this:

navigator.geolocation.getCurrentPosition (function (pos){
     var lat = pos.coords.latitude;
     var lng = pos.coords.longitude;
     var latlng = new google.maps.LatLng (lat, lng);
     var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);
});

      

The reason it screams is because lat is defined in a different scope for latlng and oceanBeach, which is defined outside of the callback function and it doesn't have access to it there

UPDATE

Considering your situation, you can use a callback to solve your problems, that is, do something like create getCurrentPosition in your own function, for example:

 function getCurrentLocation(callback) {
   if(navigator.geolocation) {
     navigator.geolocation.getCurrentPosition(function(pos) {
     var lat = pos.coords.latitude;
     var lng = pos.coords.longitude;
     callback(new google.maps.LatLng(lat,lng), new google.maps.LatLng(-6.2501199999999999,106.75937));
   });
  }
  else {
   throw new Error("Your browser does not support geolocation.");     
  }
} 

      



and calling them separate callbacks for each, i.e. do

   getCurrentLocation(function(latlng,oceanBeach){
  // work with latlng and ocean beach here
  });

      

and now finally a function call from each ie function

<script type="text/javascript">

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

function initialize() {
 getCurrentLocation(function(latlng,oceanBeach){
   directionsDisplay = new google.maps.DirectionsRenderer();
   var mapOptions = {
   zoom: 14,
   mapTypeId: google.maps.MapTypeId.ROADMAP,
   center: latlng
   }
   map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
   directionsDisplay.setMap(map);
 });

}

</script>

      

and using the same method for calcRoute. Note. Instead of keeping directionDisplay and routesService global, you should do all of this in a class to make it cleaner and more object oriented

0


source







All Articles