How to get visitor's location (i.e. country) using geolocation? [duplicate]

I'm trying to extend the native geolocation function

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

so that I can use the visitor's country name (perhaps return an informative array).

So far all I've been able to find are functions that display a google maps interface but none actually gave what I want, except for this library which worked well in this example but for some reason didn't work on my computer. I'm not sure why that went wrong there.

Anyways, do you know how I can simply return an array containing information like country, city, etc. from latitude and longitude values?



You don't need to locate the user if you only need their country. You can look their IP address up in any IP-to-location service (like maxmind). This will be accurate most of the time.

If you really need to get their location, you can get their lat/lng with that method, then query Google's or Yahoo's reverse geocoding service.


You can use my service,, for this. It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner. Here's a simple example that logs the city and country:

$.get("", function(response) {
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details:

The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission.


You can use your IP address to get your 'country', 'city', 'isp' etc...
Just use one of the web-services that provide you with a simple api like which provide you a JSON service at Simple send a Ajax (or Xhr) request and then parse the JSON to get whatever data you need.

var requestUrl = "";

  url: requestUrl,
  type: 'GET',
  success: function(json)
    console.log("My country is: " +;
  error: function(err)
    console.log("Request failed, error= " + err);

See a service I built that is fast and has reliable performance thanks to having 10 global endpoints each able to handle >10,000 requests per second!

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.

This snippet will return the details of your current ip. To lookup other ip addresses, simply append the ip to the url eg.

The API also provides an is_eu field indicating whether the user is in an EU country.

$.get("", function (response) {
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");
<script src=""></script>
<pre id="response"></pre>

Here's the fiddle;

I also wrote this detailed analysis of 8 of the best IP Geolocation APIs.


A very easy to use service is provided by Here's an example URL:

And here's some (jQuery) code which I've added to your code:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        $.getJSON('', {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            type: 'JSON'
        }, function(result) {
            alert('Country: ' + result.countryName + '\n' + 'Code: ' + result.countryCode);

Try it on ...


you can't get city location by ip. here you can get country with jquery:

$.get("", function(response) {
console.log(;}, "jsonp");

A free and easy to use service is provided at Webtechriser (click here to read the article) (called wipmania). This one is a JSONP service and requires plain javascript coding with HTML. It can also be used in JQuery. I modified the code a bit to change the output format and this is what I've used and found to be working: (it's the code of my HTML page)

        <p id="loc"></p>

        <script type="text/javascript">
            var a = document.getElementById("loc");

  	            function jsonpCallback(data) { 
	            a.innerHTML = "Latitude: " + data.latitude + 
                              "<br/>Longitude: " + data.longitude + 
                              "<br/>Country: " +; 
        <script src=""


PLEASE NOTE: This service gets the location of the visitor without prompting the visitor to choose whether to share their location, unlike the HTML 5 geolocation API (the code that you've written). Therefore, privacy is compromised. So, you should make judicial use of this service.


For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I'm the author).

Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.

var options = {
    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0,
    desiredAccuracy: 30,
    fallbackToIP: true, // if HTML5 geolocation fails or rejected
    addressLookup: true, // get detailed address information
    timezone: true, 
    map: "my-map" // this will even create a map for you

geolocator.locate(options, function (err, location) {
    console.log(err || location);

It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...


You can use to get visitor's location. It supports IPv6.

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

JavaScript Code:

function getIPDetails() {
    var ipAddress = document.getElementById("txtIP").value;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
    };"GET", "" + ipAddress, true);

<input type="text" id="txtIP" placeholder="Enter the ip address" />
<button onclick="getIPDetails()">Get IP Details</button>

jQuery Code:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            $.getJSON("" + $('#txtIP').val(),
                 function (result) {
                     alert('Country Name: ' + result.country_name)

<script src=""></script>
    <input type="text" id="txtIP" />
    <button id="btnGetIpDetail">Get Location of IP</button>


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.