Skip to content

Instantly share code, notes, and snippets.

@imlinus
Created January 19, 2018 12:59
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 imlinus/63d306449c0886776c4f1e0d58be7c89 to your computer and use it in GitHub Desktop.
Save imlinus/63d306449c0886776c4f1e0d58be7c89 to your computer and use it in GitHub Desktop.
jQuery GeoLocation wrapper
var GeoLocation = {
cb: '',
lat: '',
lng: '',
getPosition: function() {
var that = this;
if(navigator.geolocation) {
$.when(
this.getCurrentPositionDeferred({
enableHighAccuracy: true
})
).done(function(data) {
that.lat = data.coords.latitude;
that.lng = data.coords.longitude;
that.cb();
});
} else {
$.post('https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCI7FLO-uCXy3pn5NwznlVgBJUT1exSsRg', function(data) {
that.lat = data.location.lat;
that.lng = data.location.lng;
that.cb();
});
}
return this;
},
then(cb) {
this.cb = cb;
return this;
},
getCurrentPositionDeferred: function(options) {
var deferred = $.Deferred();
navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject, options);
return deferred.promise();
}
}
<script>
GeoLocation.getPosition().then(function() {
console.log(GeoLocation.lat);
console.log(GeoLocation.lng);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment