Jack
Jack

Reputation: 3680

How to center my current position? (Google Maps)

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?

Upvotes: 4

Views: 6444

Answers (2)

fernandosavio
fernandosavio

Reputation: 10407

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..

Upvotes: 9

Guilherme Reda
Guilherme Reda

Reputation: 115

you are not returning any value from the function centerMe

Upvotes: 2

Related Questions