1

I am trying to pass the lat and lon of a user location to a global variable within JavaScript.

The variable is instantiated at the top of the script and given value within the location function.

//lat long variables of user
var lon, lat;

//User location
var Position,
  Accuracy,
  test = null;
function onLocationFound(e) {
  if (Position) {
    pub_map.removeLayer(Position);
    pub_map.removeLayer(Accuracy);
  }
  test = e.latlng;
  console.log("user lat long in script is: " + test);
  lon = test.lng;
  lat = test.lat;
  var radius = e.accuracy / 2;
  //pop up stating the users position
  Position = L.marker(e.latlng)
    .addTo(pub_map)
    .bindPopup(
      "<h4>You are here</h4><p>You are  within " +
        radius +
        " metres from here</p>"
    )
    .openPopup();
  Accuracy = L.circle(e.latlng, radius).addTo(pub_map);
  return lon;
  return lat;
}

//error message if user location cannot be found
function onLocationError(e) {
  alert(e.message);
}
//display the layers to the map
pub_map.on("locationfound", onLocationFound);
pub_map.on("locationerror", onLocationError);

//locate function
pub_map.locate({ setView: true, maxZoom: 16 });

console.log("user lat is: " + lat);
console.log("user lon is: " + lon);

However when trying to call the value outside the script the value is undefined. I know the variable is global and should be accessible by all aspects of the script but for some reason when logging the data outside it still says undefined.

I have tried wrapping the whole script within a function (a bodge if I do say so) and this did not work. I have tried calling it as a reference but this too did not work.

Any ideas or reasons to why this is and how to fix it?

The image below show the logs as you can see inside the function the value is obtained but it is not passed outside of the function.

ChromeLogger showing variable values in console

9
  • 2
    Oh gosh, classical race condition. See stackoverflow.com/questions/14220321/… – IvanSanchez Apr 4 at 16:27
  • 1
    As @IvanSanchez suggested, your console.log statement should be within onLocationFound event processing function. And by the way: what are two return statement trying to achieve at the end of the function? Only the first one is executed anyway. – TomazicM Apr 4 at 17:30
  • @TomazicM Apologies if it was confusing I am just trying to pass these values outside of the function and I used the console.log as to check weather they were actually being put into the variables outside of the function which they were not. I tried many things and returning them was one of those to try an pass it back however this did not work – WMTS Apr 4 at 17:52
  • 1
    But do you understand now what was wrong in your approach? – TomazicM Apr 4 at 18:54
  • 2
    The values are being stored in variables in the global context; just not when you think they are being stored. – IvanSanchez Apr 4 at 21:59
0

The answer was as hinted at within the comments, I was just unable to imagine this in a written example and thus confused me.

The logs themselves were being executed before the value of the global variable had changed and was thus passing it correctly but not logging it. I solved this through assigning the variables within the function themselves and then calling it out to the php script.

Fixed code below:

//Map instantiation and layer calls
pub_map = L.map('mapspce');
pub_map.setView([54.00, -2.54],5.5);
pub_map.addLayer(basetiles);

//User location
var Position, Accuracy,test = null;
function onLocationFound(e) {
    if(Position){
        pub_map.removeLayer(Position);
        pub_map.removeLayer(Accuracy);
    }
test = e.latlng;
console.log("user lat long in script is: " + test);
lon = test.lng;
lat = test.lat;
lat = lat.toString();
lon = lon.toString();
kLOC = lon + " " + lat;
var radius = e.accuracy / 2;
//pop up stating the users position
Position = L.marker(e.latlng).addTo(pub_map).bindPopup("<h4>You are here</h4><p>You are  within " + radius + " metres from here</p>").openPopup();
Accuracy = L.circle(e.latlng, radius).addTo(pub_map);

/* var lat, lon;
lat = parseFloat(Position.coords.latitude);
lon = parseFloat(Position.coords.longitude);

console.log("user lat is: " +lat);
console.log("user lat is: "+lon); */
//return lon;
//return lat;
return test;
}

//error message if user location cannot be found
 function onLocationError(e) {
    alert(e.message);
}
//display the layers to the map
pub_map.on('locationfound', onLocationFound);
pub_map.on('locationerror', onLocationError);

//locate function
pub_map.locate({setView: true, maxZoom:16});



//knn feature

var kTable = 'geoupload.pubs';
var kColumn =["id", "p_name", "address1", "postcode", "local_authority"];
var kGeom = "geom";
var kLOC;
//"51.59977 -3.325952";
//"307998 189349";

//var klocy = "User location is " + test;

//passing variable to the console to show values are being picked up 
console.log(kLOC);
console.log("user lat long is: " + test);
console.log("user lat is: " + lat);
console.log("user lon is: " + lon);

$(document).ready(function(){
    $.ajax({
        url: "knn.php",
        data:{ktable: kTable, kinclu: kColumn, kgeomy: kGeom, Loc: kLOC}
    })
    .done(function(data){
        knnPubsLay = L.geoJSON(JSON.parse(data),{
            pointToLayer: function (feature, latlng){
                return L.circleMarker(latlng,nearStyle);
        }});
        console.log("after " + kLOC);
        pub_map.addLayer(knnPubsLay);
        knnPubsLay.bringToFront();
    })
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.