I'm new to JavaScript and I'm currently building a simple mapping application using leaflet.
I'm having issues with the application whereby I can't get two functions to call sequentially (Likely due to my lack of JS knowledge).
I have two functions. One will return the current location and the other will take this locations lat, lon as input to create a map:
/* Return a position object*/
function getMyLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
return position;
});
}
else {
alert("Please turn on location services");
}
}
/* Create a map and place a marker at the given lat,lon */
function createMap(lat,lon) {
var mymap = L.map('map', {zoomControl: false}).setView([lat, lon], 17);
L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/outdoors-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiZG9uc2Nvc2hhIi...', {
maxZoom: 20
}).addTo(mymap);
L.marker([lat, lon]).addTo(mymap);
}
The functions are called in the document ready function:
$(document).ready(function () {
var pos = getMyLocation();
createMap(pos.coords.latitude,pos.coords.longitude);
});
The problem is, however, createMap() gets called before the pos variable has been set, meaning it's passed two undefined lat and longs, thus the map doesn't render.
What's the correct way to fix an issue like this in JavaScript? I looked at promises but wasn't sure if I was on the right lines. Alternatively, I could just call createMap() from inside getMyLocation but I presume there's a better solution.