I'm very new to Javascript and ran into a problem I can't resolve/understand myself.
Let's say that I made "UserMap" class with a "userPosition" property and want to get coordinates using Geolocation API.
navigator.geolocation.getCurrentPosition(this.getCoordinates);
Then in the callback function I get latitude and longitude:
var coords = { "lat" : position.coords.latitude, "lng" : position.coords.longitude };
My question is: how can I make this callback function report back to the UserMap instance, so the userPosition property can be updated? Obviously this.userPosition = coords;
won't work here. Now I feel pretty much helpless dealing with callbacks. I hope I don't have to make a new object every time I get the updated coords from a user.
Here is the wrong code:
function UserMap() {
this.map = L.map('map', {"zoomControl" : false});
this.userPosition = {};
this.boundary = {};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(this.getCoordinates);
}
else{ alert("Geolocation is not supported by your browser.");
return false;
}
this.map.on("click", function(e) {
alert("Lat: " + e.latlng.lat + " Lng: " + e.latlng.lng);
});
this.display();
}
UserMap.prototype.getCoordinates = function(position) {
var coords = { "lat" : position.coords.latitude, "lng" : position.coords.longitude};
this.userPosition = coords; // I understand why this line won't work, but can't find a workaround solution
}
UserMap.prototype.display = function() {
var lat = this.userPosition.lat;
var lng = this.userPosition.lng;
this.map.setView([lat, lng], 18);
var tile = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
minZoom: '16',
}).addTo(this.map);
L.marker([lat, lng]).addTo(this.map)
.bindPopup('You are here!')
.openPopup();
}
In the callback you can use an ajax call, wich will interact with the server in a nonblocking manner.
If you use jquery you can do something like this: