It's quite simple, there are several sites that provide this type of service via API, one of them is ipstack that I found and is free (max of 10,000 requests per month).
The advantage of ipstack is that it provides several additional information, such as the country flag, DDI, continent code and others.
All you have to do is register and you will receive an API key, the usage is very simple:
http://api.ipstack.com/<ip>?access_key=<chave de api>
How do I create an account I already have an API key (no problem post it here)
http://api.ipstack.com/191.19.145.134?access_key=dd66d448ad3762f3480cbd96faddb276
The answer is:
{
"ip":"191.19.145.134",
"type":"ipv4",
"continent_code":"SA",
"continent_name":"South America",
"country_code":"BR",
"country_name":"Brazil",
"region_code":"SP",
"region_name":"Sao Paulo",
"city":"S\u00e3o Paulo",
"zip":"01323",
"latitude":-23.5733,
"longitude":-46.6417,
"location":{
"geoname_id":3448439,
"capital":"Bras\u00edlia",
"languages":[
{
"code":"pt",
"name":"Portuguese",
"native":"Portugu\u00eas"
}
],
"country_flag":"http:\/\/assets.ipstack.com\/flags\/br.svg",
"country_flag_emoji":"\ud83c\udde7\ud83c\uddf7",
"country_flag_emoji_unicode":"U+1F1E7 U+1F1F7",
"calling_code":"55",
"is_eu":false
}
}
Here's a practical example, remembering that it will not work on HTTPS requests (so it will not work for Stackoverflow).
var api_key = "dd66d448ad3762f3480cbd96faddb276";
function LocalizaIP(ip) {
console.log("http://api.ipstack.com/"+ip+"?access_key="+api_key);
$.ajax({
method: "GET",
url: "http://api.ipstack.com/"+ip+"?access_key="+api_key,
}).done(function (obj) {
console.log(obj);
});
};
LocalizaIP("191.19.145.134");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>