0

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

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.