0

i want to alert the curlat variable in a other function so i can use it in the google maps feature. But i cant get it to work.

var getLocation = {
    init: function () {
        var curlat = "";

        function onSuccess(position) {
            curLat = position.coords.latitude;
        };   

        function onError(error) {
            alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
        }
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    }
}

var map = {
    init: function () {
        alert(curLat); // alert the cordinate here

        //Google maps API initialisation
        var element = document.getElementById("map");

        //Define the properties of the OSM map to be displayed 
        var map = new google.maps.Map(element, {
            center: new google.maps.LatLng(57, 21),
            zoom: 11,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            mapTypeControl: false,
            streetViewControl: false
        });
        //Define OSM map type pointing at the OpenStreetMap tile server         
        map.mapTypes.set("OSM", new google.maps.ImageMapType({
            getTileUrl: function (coord, zoom) {
                return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
            },
            tileSize: new google.maps.Size(256, 256),
            name: "OpenStreetMap",
            maxZoom: 18
        }));
    }

}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 3
    You need to edit that code and format it properly. it's utterly unreadable right now. – Marc B May 26 '14 at 20:42
  • 2
    You probably will have to read this: [Why is my variable undefined after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function-asynchron) – Felix Kling May 26 '14 at 20:49

1 Answers1

1

First, javascript is case sensitive, so curlat should be curLat.

Second, bring the variable outside the function:

var curLat = "" ;

var getLocation = {       ...

Also, as pointed out correctly by others. You should delay initialization of map until curLat is set. Maybe you can call .map.init from the success handler.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 1
    I'm not sure that would help a lot. `getCurrentPosition` is asynchronous, so it depends on when `map.init()` is called. – Felix Kling May 26 '14 at 20:49
  • Good point. Missed that in the overview on mobile. Updated answer a little. Will check again when on desktop again. – Patrick Hofman May 26 '14 at 21:09