Skip to content

Instantly share code, notes, and snippets.

@czmole
Created September 9, 2017 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save czmole/cd6088dec6bdd5c9ff79c27197f3d96a to your computer and use it in GitHub Desktop.
Save czmole/cd6088dec6bdd5c9ff79c27197f3d96a to your computer and use it in GitHub Desktop.
Sharing location in the browser
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&key=AIzaSyDg4kddVaGQNI5O5Cx5eOpGBO0X8ODTL-U"></script>
</head>
<body>
</body>
</html>
var city, state;
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng);
}
function errorFunction() {
console.log("Geocoder failed");
}
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) {
if (results[1]) {
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
state = results[0].address_components[i];
break;
}
}
}
alert(city.long_name +", "+ state.long_name);
} else {
console.log("City name not available");
}
} else {
console.log("Geocoder failed due to: ", status);
}
});
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
document.addEventListener('DOMContentLoaded', function() {
initialize();
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment