Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP to Location using Javascript

You can submit the IP you receive to an online geolocation service, such as http://www.geoplugin.net/json.gp?ip=<your ip here>&jsoncallback=<suitable javascript function in your source>, then including the source it returns which will run the function you specify in jsoncallback with the geolocation information.

Alternatively, you may want to look into HTML5's geolocation features -- you can see a demo of it in action here. The advantage of this is that you do not need to make requests to foreign servers, but it may not work on browsers that do not support HTML5.


A free open source community run geolocation ip service that runs on the MaxMind database is available here: https://ipstack.com/

Example

https://api.ipstack.com/160.39.144.19

Limitation

10,000 queries per month


It's quite easy with an API that maps IP address to location. Run the snippet to get city & country for the IP in the input box.

$('.send').on('click', function(){

  $.getJSON('https://ipapi.co/'+$('.ip').val()+'/json', function(data){
      $('.city').text(data.city);
      $('.country').text(data.country);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="ip" value="8.8.8.8">
<button class="send">Go</button>
<br><br>
<span class="city"></span>, 
<span class="country"></span>

I wish to point out that if you use http://freegeoip.net/, you don't need to supply to it the IP address of the client's location. Just try these:

1) http://freegeoip.net/xml/

2) http://freegeoip.net/json/

3) http://freegeoip.net/csv/

However, I am unable to retrieve the information with AJAX calls, probably because of some cross-origin policy. Apparently they have not allowed public access to their system.


Just in case you were not able to accomplish the above code, here is a simple way of using it with jquery:

$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",
    function (data) {
        for (var i in data) {
            document.write('data["i"] = ' + i + '<br/>');
        }
    }
);