You need a database that contains IP address and location mapping. Or you can use a lot of online tools to achieve this, for example: http://www.ipligence.com/geolocation
Google returs lots of result under keywords: "IP location"
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>
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.
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
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