Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 818
Jack Avatar asked Oct 16 '25 00:10

Jack


1 Answers

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

like image 77
fernandosavio Avatar answered Oct 17 '25 13:10

fernandosavio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!