Obtendo a localização atual com Javascript

Originalmente, pensei que seria difícil obter a localização atual de um usuário, mas na verdade é muito simples.

Há uma maneira rápida no w3schools que nos mostra como usar a API HTML5 Geolocation:
http://www.w3schools.com/html/html5_geolocation.asp

Você também deve incluir a API do Google Maps:
http://maps.googleapis.com/maps/api/js?sensor=false

Em seguida, você escreve sua função para obter a localização atual:




function getLocation() {
if(navigator.geolocation {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
</code>
</pre>

You'll also need to write your success function:


function geoSuccess(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert("lat:" + lat + " lng:" + lng);
}
</code>
</pre>

And then an error function:


function geoError() {
alert("Geocoder failed.");
}
</code>
</pre>

You can stop here if you just want the lat and lng coordinates.
But if you want to convert these coordinates to a full address, you can call another function that passes your lat and lng:

Add a function in your success function:


function geoSuccess(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert("lat:" + lat + " lng:" + lng);
codeLatLng(lat, lng);
}
</code>
</pre>

And here's the code for that function:


var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
}

function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
console.log(results)
if(results[1]) {
//formatted address
var address = results[0].formatted_address;
alert("address = " + address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</code>
</pre>

Answer found from:
http://stackoverflow.com/questions/6797569/html5-geolocation-easiest-way-to-get-city-name