This code works when I break any time after pos is defined, then continue. But when I run it normally it doesn’t display anything. What am I doing wrong?
function initialize() {
var pos;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
}, function() {
handleNoGeolocation(true);
});
}
else { // Browser doesn't support geolocation
handleNoGeolocation(false);
}
var myOptions = {
zoom: 7,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
getCurrentPosition(f, ...)is asynchronous, meaning that the callbackfis called later after successful completion of the request. But at this time the local variableposin the functioninitialize()is no longer in scope.You can solve the problem by defining
posin the global window scope. This should work andposwill get assigned by the callback. However, you do not know when this assignment happens. The best way to handle this problem, is to do something withposdirectly in the callback, e.g. write it into a text field or store it in the database, etc.