4

I'm trying to center my current location in Google Maps. This will center a location with a specific latitude- and longitude-variable.

var coords = new google.maps.LatLng(62.39081100, 17.30692700);

But I tried to grab the users location with this function:

function grabMyPosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(centerMe);
    } else {
        alert("You don't support this");
    }
}
function centerMe(center) {
    var me_location = {
        lat: position.coords.latitude,
        lon: position.coords.longitude
    };
}

And then do this:

var coords = new google.maps.LatLng(me_location.lat, me_location.lon);

But then I get this:

Uncaught TypeError: Cannot read property 'lat' of undefined 

That's because I'm storing and filling this "me_location" variable inside a function. How can I make it "global" so it could be used outside my function?

4
  • 1
    me_location is not accessible from outside CenterMe function.. Apr 8, 2013 at 18:17
  • I thought so, but how "bypass" this problem?
    – Jack
    Apr 8, 2013 at 18:18
  • You return the object at the end of the function, and call navigator.geolocation.getCurrentPosition(centerMe()); instead. Apr 8, 2013 at 18:19
  • Why don't you work async? navigator.geolocation.getCurrentPosition receive a callback function as argument.. so center the map inside callback.. Apr 8, 2013 at 18:21

2 Answers 2

9
function grabMyPosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(centerMe);
    } else {
        alert("You don't support this");
    }
}
function centerMe(position) {
    var coords = new google.maps.LatLng(
        position.coords.latitude,
        position.coords.longitude
    );

    map.setCenter(coords);
    // or
    map.panTo(coords);
}

Supposing your map variable is global..

0
2

you are not returning any value from the function centerMe

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.