How can I get user's location without asking for the permission or if user permitted once so need not to ask ever again?

3 ways to do this in this answer:

  1. Get a GPS precise location asking the user to allow access to its browser's API
  2. Get an approximate location (country, city, area) using an external GeoIP service
  3. Get an approximate location (country, city, area) using CDN service

Ask the user to allow access to its browser's API

You can get the location of the client using HTML5 features. This will get you the exact location of the user if it is done from a device which has a GPS, or an approximate location. Once the user approved to share his location, you'll get it without any more approval. This solution uses Geolocation.getCurrentPosition(). It is required for most cases to do this under HTTPS protocol.

If you are in a hurry, here is a CodePen with this solution: https://codepen.io/sebastienfi/pen/pqNxEa

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to get your coordinates:</p>

<button onclick="getLocation()">Try It</button>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            // Success function
            showPosition, 
            // Error function
            null, 
            // Options. See MDN for details.
            {
               enableHighAccuracy: true,
               timeout: 5000,
               maximumAge: 0
            });
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;  
}
</script>

</body>
</html>

Handling Errors and Rejections The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

Displaying the Result in a Map

function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;

    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=
    "+latlon+"&zoom=14&size=400x300&sensor=false";

    document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}

GeoIP

If the solution above doesn't work in your scenario, you can obtain an approximate position using IP's location. You will not necessarily get the exact location of the user, but may end up with the location of the nearest Internet node in the user's connection point area, which may be close enough for 99% of the use cases (country, city, area).

As this is not precise but doesn't require the user's approval, this may also meet your requirements.

Find below 2 ways to do that. I would recommend doing this using the CDN solution because it is faster and yes, speed matters a lot.

Get an approximate location (country, city, area) using an external GeoIP service

Many external services allows you to obtain the GeoIP location. Here is an example with Google.

To get your Google API Key, go here: https://developers.google.com/loader/signup?csw=1

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Get web visitor's location</title>
        <meta name="robots" value="none" />
    </head>
    <body>
    <div id="yourinfo"></div>
    <script type="text/javascript" src="http://www.google.com/jsapi?key=<YOUR_GOOGLE_API_KEY>"></script>
    <script type="text/javascript">
        if(google.loader.ClientLocation)
        {
            visitor_lat = google.loader.ClientLocation.latitude;
            visitor_lon = google.loader.ClientLocation.longitude;
            visitor_city = google.loader.ClientLocation.address.city;
            visitor_region = google.loader.ClientLocation.address.region;
            visitor_country = google.loader.ClientLocation.address.country;
            visitor_countrycode = google.loader.ClientLocation.address.country_code;
            document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
        }
        else
        {
            document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
        }
    </script>
    </body>
</html>

Get an approximate location (country, city, area) using CDN service

An alternative to using external services is provided by most of the CDN. The advantage of this solution is that no extra HTTP request is required, so it is faster. If you already have a CDN, this is the way to go. You can use CloudFlare, CloudFront, etc.

In this scenario, you will most likely end up with the location as a parameter of the HTTP request's header, or even directly in the window object so you can get it with Javascript. Read the CDN's documentation to know more.

Edited on mid December 2018 to add more options.


You can go for an external service like https://www.geolocation-db.com. They provide a geolocation service based on IP addresses where you don't need user permission.

  • JSON: https://geolocation-db.com/json/
  • JSONP: https://geolocation-db.com/jsonp/

Try this example:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Geo City Locator</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body> 
    <div>Country: <span id="country"></span></div>
    <div>State: <span id="state"></span></div>
    <div>City: <span id="city"></span></div>
    <div>Latitude: <span id="latitude"></span></div>
    <div>Longitude: <span id="longitude"></span></div>
    <div>IP: <span id="ip"></span></div>
    <script>
      $.getJSON('https://geolocation-db.com/json/')
         .done (function(location) {
            $('#country').html(location.country_name);
            $('#state').html(location.state);
            $('#city').html(location.city);
            $('#latitude').html(location.latitude);
            $('#longitude').html(location.longitude);
            $('#ip').html(location.IPv4);
         });
    </script>
</body>
</html>