54
<script type="application/javascript">
    function getip(json){
      alert(json.ip); // alerts the ip address
    }
</script>

<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>

I can get User IP by this code...

I want to find location of this IP. How can I?

SOF User
  • 7,590
  • 22
  • 75
  • 121
  • 2
    What do you mean by the "location?" Latitude/longitude? – Matt Ball Feb 08 '11 at 19:43
  • 4
    be aware the Lat/Long you get is probably not very accurate. My IP address at home shows up about 30 miles away from where I'm actually located; it shows where my ISP is. This could be "good enough" depending on what you're doing, but you should understand the limitations. – Stephen P Feb 08 '11 at 20:06
  • the question is not about programming as is, but how to get "location" from an "IP" – serge Nov 04 '22 at 21:21

12 Answers12

60

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.

  • 2
    how can I call this api in my javascript without running into cors issues? – mishap Feb 06 '15 at 20:57
  • For a list of all free IP lookup services, you can refer to my answer for http://stackoverflow.com/questions/391979/get-client-ip-using-just-javascript – thdoan Feb 01 '16 at 04:56
  • 2
    Also now (2021), this Service needs paid subscription to be able to use `https` instead of `http`. Using `http` in API inside a `https` hosted site will be blocked by the browser. – Anubhab Maji Sep 17 '21 at 05:51
32

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

Alex Czarto
  • 3,151
  • 4
  • 28
  • 28
  • 4
    Although freegeoip.net uses MaxMind database, the service has absolutely no relation with the company. It is an open source and free software supported by the community and maintained by myself, without the consent of MaxMind. – fiorix May 23 '14 at 17:31
  • 4
    It has been moved to https://ipstack.com and they offer paid services now. However, the 10,000 queries limit for free license should be sufficient. Just note, that it's not per hour anymore, it's per month. – jjj Jul 17 '18 at 02:56
  • 2
    They dont support api calls over https for free plan – hardik chugh Sep 18 '21 at 15:52
19

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>
Ken
  • 785
  • 6
  • 11
  • Now (2021), This code snippet, on running inside SO, throws CORS error, their tech support says that there is some issue with CORS when API returns an error response. In my research, it throws a 404 error. I don't know why it throws that error. Same CORS error when running in localhost on some port, they reported that they have some issue with port. Even after hosting on CloudFront, it's the same CORS error, cannot figure out anything else. – Anubhab Maji Sep 17 '21 at 05:58
8

A better way is to skip the "middle man" (ip)

jQuery.get("http://ipinfo.io", function(response) {
    console.log(response.city);
}, "jsonp");

This gives you the IP, the city, the country, etc

Claudiu
  • 3,700
  • 1
  • 38
  • 35
6

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/>');
        }
    }
);
Tushar Shukla
  • 5,666
  • 2
  • 27
  • 41
talsibony
  • 8,448
  • 6
  • 47
  • 46
  • The new url is http://www.geoplugin.net/json.gp, the IP is not necessary but it is less precise (the lat-long) than freegeoip – Nico May 27 '16 at 02:34
  • 1
    This service does not have SSL - so is blocked by Chrome, etc.... – Apps-n-Add-Ons Aug 26 '20 at 18:37
  • 1
    @CFPSupport yep these days http requests are being block so we might, they have https support but it will cost https://www.geoplugin.com/premium#ssl_access_per_year – talsibony Aug 27 '20 at 08:22
3

A rather inexpensive option would be to use the ipdata.co API, it's free upto 1500 requests a day.

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#city").html(response.city + ", " + response.region);
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>

<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

View the Fiddle at https://jsfiddle.net/ipdata/6wtf0q4g/922/

Jonathan
  • 10,792
  • 5
  • 65
  • 85
3

You can use ipgeolocation which is a free IP API that provides country, city, state, province, latitude, longitude and etc.

 let apiKey = "your_api_key_here"; 

  async function getLocation (ip) {
  let url = `https://api.ipgeolocation.io/ipgeo?apiKey=${apiKey}&ip=${ip}`;

  await fetch(url).then((response) =>
    response.json().then((json) => {
      const output = `
          ---------------------
          Country: ${json.country_name}
          State: ${json.state_prov}
          City: ${json.city}
          District: ${json.district}
          Lat / Long: (${json.latitude}, ${json.longitude})
          ---------------------
          `;
      console.log(output);
    })
  );
};

 getLocation('154.28.188.208') // prints the location 

enter image description here

norbekoff
  • 1,719
  • 1
  • 10
  • 21
2
    $.getJSON('//freegeoip.net/json/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Sean Keane
  • 411
  • 1
  • 6
  • 19
2

You can use this google service free IP geolocation webservice

update

the link is broken, I put here other link that include @NickSweeting in the comments:

ip-api.com

and you can get the data in json format:

http://ip-api.com/docs/api:json

andres descalzo
  • 14,887
  • 13
  • 64
  • 115
  • You should delete your comment that says the same. – Matt Ball Feb 08 '11 at 19:53
  • 1
    @10basetom Geoip services regularly go down since they are expensive to operate and tend to get a lot of free traffic. Here are some alternatives that work as of 2015/01: http://ip-api.com/json http://freegeoip.net/json/8.8.8.8 – Nick Sweeting Jan 29 '16 at 20:19
2

Either one of the following links should take care of this:

http://ipinfodb.com/ip_location_api_json.php

http://www.adam-mcfarland.net/2009/11/19/simple-ip-geolocation-using-javascript-and-the-google-ajax-search-api/

Those links have tutorials for getting a users location through Javascript. However, they do so through an API to an external data service. If you have an extremely high traffic site, you might want to hosting the data yourself (or getting a premium api service). To host everything yourself, you will have to host a database with IP Geolocation and use ajax to feed the users location into Javascript. If this is the approach you want to take, you can get a free database of IP information below:

http://www.ipinfodb.com/ip_database.php

Please note that this method entails having to periodically update the database to stay accurate in tracing ips to locations.

user396404
  • 2,759
  • 7
  • 31
  • 42
1

you can use ipinfodb after getting your api key you can query for a location against a specific ip like this http://api.ipinfodb.com/v2/ip_query.php?key=" + apiKey + "&ip=" + ip + "&output=xml you can then then extract the location from the xml response

Rafay
  • 30,950
  • 5
  • 68
  • 101
-1

Try TUQ GEO IP API it's free and really neat and sweet with jsonp support

http://tuq.in/tools/geo

http://tuq.in/tools/geo+stats

Vikrant Mahajan
  • 545
  • 3
  • 8