Sam B.
Sam B.

Reputation: 3043

Getting current location from browser Chrome and Firefox

I'm trying to get the current location using this code it should log something in the console but doesn't, I also don't get my location from google's map's tutorial https://developers.google.com/maps/documentation/javascript/geolocation

Here's the code from jsfiddle

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        console.log("Geolocation is not supported by this browser.");
    }
}
function showPosition(position) {
    console.log(position.coords.latitude);
    console.log(position.coords.longitude); 
}

Update includes logging the result

Upvotes: 0

Views: 9018

Answers (2)

Papan Sarkar
Papan Sarkar

Reputation: 112

Keeping it simple, if someone is looking for only to see the location co-ordinates. Just use this on your browser console.

navigator.geolocation.getCurrentPosition(function(location) {
    console.log(location.coords.latitude);
    console.log(location.coords.longitude);
});

Upvotes: 1

Jarek Kulikowski
Jarek Kulikowski

Reputation: 1389

You are calling it correctly, and if navigator.geolocation.getCurrentPosition returns valid result then it should print. However, if there was an error then I suggest providing an option to catch an error as follows:

 navigator.geolocation.getCurrentPosition(showPosition, showError);

and define another function:

function showError( error ) {
    console.log( 'getCurrentPosition returned error', error);
}

For complete documentation please see Geolocation.getCurrentPosition

Upvotes: 1

Related Questions