Last Updated: September 29, 2021
·
105.9K
· andydlin

Getting Current Location with Javascript

I originally thought grabbing a user's current location was going to be difficult, but it's actually very simple.

There's quick way on w3schools that shows us how to use HTML5 Geolocation API:
http://www.w3schools.com/html/html5_geolocation.asp

You also have to include the Google Maps API:
http://maps.googleapis.com/maps/api/js?sensor=false

Then you write your function to grab the current location:


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

4 Responses
Add your response

Nice, but it would work only in Chrome

over 1 year ago ·

Oh really? Hmm I just tested this on Safari and Firefox and they both work. Are there certain versions that this won't work on?

over 1 year ago ·

Need to close that if condition ")"

over 1 year ago ·