Golan_trevize
Golan_trevize

Reputation: 2433

How to save a variable value outside of a function in javascript

I am newbie to JavaScript, I was trying to make a simple GoogleMaps which is centered in my current position and I am finding problems saving my latitude and longitude to center the map.

Here is my code which i have adopted:

function initialize() {
 var latitudeCenter;
 var longitudeCenter;
 navigator.geolocation.getCurrentPosition(onSuccess, onError);
 function onSuccess(position){
 console.log(position.coords.latitude, position.coords.longitude);
 latitudeCenter = position.coords.latitude;
 longitudeCenter = position.coords.longitude;
 }
 function onError(error){
 alert('Error en GPS: ' + error);
 }
var mapOptions = {
 zoom: 8,
 center: new google.maps.LatLng(latitudeCenter, longitudeCenter)
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
console.log('latitud: ' + latitudeCenter + ' longitud: ' + longitudeCenter);
}

In the first console log I can read my current position and latitude, so that method works fine, but when I try to save it in centerLatitude and centerLongitude it does not work, it displays undefined.

Thanks for the help

Upvotes: 0

Views: 557

Answers (1)

Callum Linington
Callum Linington

Reputation: 14417

So, the functions onSuccess and onError are asynchronous, so you won't get back an answer straight away. So therefore you put your actual map initialisation code inside that onSuccess

function initialize() {
    var latitudeCenter;
    var longitudeCenter;
    navigator.geolocation.getCurrentPosition(onSuccess, onError);

    function onSuccess(position){
        console.log(position.coords.latitude, position.coords.longitude);
        latitudeCenter = position.coords.latitude;
        longitudeCenter = position.coords.longitude;

        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(latitudeCenter, longitudeCenter)
        };

        map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
    }

    function onError(error){
        alert('Error en GPS: ' + error);
    }


    console.log('latitud: ' + latitudeCenter + ' longitud: ' + longitudeCenter);
}

Upvotes: 1

Related Questions