Created
July 18, 2016 20:15
-
-
Save hay-wire/dce7684fdf2c1a32bc9abed233b17953 to your computer and use it in GitHub Desktop.
Browser based Javascript to get user's location using html5 geolocation API and reverse geocoding service of Google Maps.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getAddr = function(lat, lng) { | |
console.log("getting addr "); | |
var latlng = new google.maps.LatLng(lat, lng); | |
var geocoder = geocoder = new google.maps.Geocoder(); | |
geocoder.geocode({ | |
'latLng': latlng | |
}, function(results, status) { | |
console.log("geocode result: ", results, " and status: ", status); | |
if (status == google.maps.GeocoderStatus.OK) { | |
if (results[0]) { | |
console.log("Location: ", results[0].formatted_address); | |
document.getElementById("faddress").value = results[0].formatted_address; | |
} | |
} | |
}); | |
} | |
var geoSuccess = function(position) { | |
startPos = position; | |
console.log({ | |
lat: startPos.coords.latitude, | |
lng: startPos.coords.longitude | |
}); | |
getAddr(startPos.coords.latitude, startPos.coords.longitude); | |
}; | |
var geoError = function(error) { | |
console.log('Error occurred. Error code: ' + error.code); | |
// error.code can be: | |
// 0: unknown error | |
// 1: permission denied | |
// 2: position unavailable (error response from location provider) | |
// 3: timed out | |
}; | |
var geoOptions = { | |
enableHighAccuracy: true | |
} | |
var getLocation = function() { | |
console.log("starting getting user location"); | |
navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions); | |
} | |
var script = document.createElement("script"); | |
script.type = 'text/javascript'; | |
script.src = "https://maps.googleapis.com/maps/api/js?sensor=true&key=ADD_YOUR_API_KEY_HERE&callback=getLocation"; | |
document.body.appendChild(script); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment