Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Last active June 28, 2017 02:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyecatchup/221c4e802fe9ed677b3e741c387cffff to your computer and use it in GitHub Desktop.
Save eyecatchup/221c4e802fe9ed677b3e741c387cffff to your computer and use it in GitHub Desktop.
Better getCurrentPosition() - Based on https://ipinfo.io/developers/replacing-getcurrentposition
/* Helper function, required if jQuery is not available */
var ajax = function ajax(method, url, callback) {
var xhr = !!window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function() {4 == this.readyState && callback(xhr)};
xhr.open(method, url, true);
xhr.send();
};
function do_something(coords) {
// Do something with the coords here
console.log(coords);
}
if (navigator.userAgent.match(/bot|spider/i)) {
// It is a bot. We might want to set some defaults here, or do nothing.
} else {
// It's not a bot! Hit the API
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords);
},
function(failure) {
/* If jQuery is available */
/*
$.get('https://ipinfo.io/json', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
do_something(coords);
});
*/
/* If jQuery is not available */
ajax("GET", "https://ipinfo.io/json", function(response) {
if (response.status == 200) {
var data = JSON.parse(response.responseText),
loc = data.loc.split(','),
coords = {
latitude: loc[0],
longitude: loc[1]
};
do_something(coords);
}
});
}
);
}
<pre id="out"></pre>
<script>
var ajax = function ajax(method, url, callback) {
var xhr = !!window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function() {4 == this.readyState && callback(xhr)};
xhr.open(method, url, true);
xhr.send();
};
function do_something(coords) {
// Do something with the coords here
document.querySelector('#out').textContent = JSON.stringify(coords, null, 4);
}
if (navigator.userAgent.match(/bot|spider/i)) {
// It is a bot. We might want to set some defaults here, or do nothing.
} else {
// It's not a bot! Hit the API
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords);
},
function(failure) {
ajax("GET", "https://ipinfo.io/json", function(response) {
if (response.status == 200) {
var data = JSON.parse(response.responseText),
loc = data.loc.split(','),
coords = {
latitude: loc[0],
longitude: loc[1]
};
do_something(coords);
}
});
}
);
}
</script>
@eyecatchup
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment