Been trying for 1.5 hours. Can someone please help me out? "your post appears to contain code that is not properly formatted as code" issue. Please can someone help me format this code? It works now in this post, but not when making a new one... Now I cannot make a new post for a day... What the...
FIXED: It appears that the browser output had to be in code layout.
This was my original question:
TITLE: Working with geolocation API - scope question
Hi all
I am working with Mapbox and am trying to update the vars lngreal and latreal (from default Greenwhich coordinates). The function initializeMap() is called during setup, and the idea is that it updates it with user's longlat coordinates if possible. When I run the code below...
function initializeMap() {
mapboxgl.accessToken = 'HIDDEN FOR THIS POST';
var lngreal = 0.0098;
var latreal = 51.4934;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocationInfo);
}
function displayLocationInfo(position) {
//Why does this not work to update the map zoom?
lngreal = position.coords.longitude;
latreal = position.coords.latitude;
console.log(lngreal);
console.log(latreal);
}
console.log(lngreal);
console.log(latreal);
// This adds the map to your page
var map = new mapboxgl.Map({
// container id specified in the HTML
container: 'map',
// style URL
style: 'mapbox://styles/mapbox/light-v10',
// initial position in [lon, lat] format
center: [lngreal, latreal],
// initial zoom
zoom: 14
});
// More code after this but not related
}
It shows the following in html inspector console:
play-mapboxscripts.js:21 0.0098
play-mapboxscripts.js:22 51.4934
play-mapboxscripts.js:17 4.9212796
play-mapboxscripts.js:18 52.333704999999995
Why does it first show the last console.log lines, instead of the console.log lines in the displayLocationInfo function? Isn't that function called in the navigator.geolocation function, which comes before that?
I cannot get the lngreal and latreal variables updated correctly to match the user's location. They will default back to 0.0098 and 51.4934, and the loaded map (var map) will show the default Greenwhich location. Does this have to do with variable scope of the displayLocationInfo function?