Get the location from an IP Address in Javascript
How to get the location from an IP Address in Javascript and JQuery.
One of ipdata's most useful features is that if you use it client-side with Javascript you don't have to pass in the user's IP address. We will automatically get the user's IP Address, geolocate it and return the geolocation data to you client-side.
An example request in JQuery
$.get("https://api.ipdata.co?api-key=<<apiKey>>", function(response) {
console.log(response.country_name);
}, "jsonp");
A simple call like above without passing in any parameters other than the API key will give you the location of the user currently on the page with the above code embedded.
Pure Javascript
var request = new XMLHttpRequest();
request.open('GET', 'https://api.ipdata.co/?api-key=<<apiKey>>');
request.setRequestHeader('Accept', 'application/json');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
};
request.send();
Updated over 2 years ago