HTML5 Geolocation with IpForensics fallback
An example of how you would use the ipdata API as a fallback for when HTML5 Geolocation fails or if the user blocks geolocation requests from your website
const geoFindMe = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, geoOptions);
} else {
console.log("Geolocation services are not supported by your web browser.");
}
}
const success = (position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const altitude = position.coords.altitude;
const accuracy = position.coords.accuracy;
console.log(`lat: ${latitude} long: ${longitude}`);
}
const error = (error) => {
var request = new XMLHttpRequest();
request.open('GET', 'https://ipforensics.net/api/v1/origin?apikey=APIKEY');
request.setRequestHeader('Accept', 'application/json');
request.onreadystatechange = function () {
if (this.readyState === 4) {
data = JSON.parse(this.responseText)
console.log(`lat: ${data.meta_data.geolocation.latitude} long: ${data.meta_data.geolocation.}`);
}
};
request.send();
}
const geoOptions = {
enableHighAccuracy: true,
maximumAge: 30000,
timeout: 27000
};
// call the function
geoFindMe()Last updated