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

Posted on

How can I get user’s location without asking for the permission or if user permitted once so need not to ask ever again? – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like javascript and php . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about How can I get user’s location without asking for the permission or if user permitted once so need not to ask ever again?.

I am creating a portal using MySQL, JavaScript and Ajax and I want to fetch user’s location in terms of latitude and longitude. if it is not possible to fetch the location without asking then once user grant the permission, I could fetch the location from any page without asking ever again.

Thanks in Advance.

Solution :

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:

<!DOCTYPE html>

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

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

var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
            // Success function
            // Error function
            // 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;  


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."
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."

Displaying the Result in a Map

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

    var img_url = "

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


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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
        <title>Get web visitor's location</title>
        <meta name="robots" value="none" />
    <div id="yourinfo"></div>
    <script type="text/javascript" src="<YOUR_GOOGLE_API_KEY>"></script>
    <script type="text/javascript">
            visitor_lat = google.loader.ClientLocation.latitude;
            visitor_lon = google.loader.ClientLocation.longitude;
            visitor_city =;
            visitor_region = google.loader.ClientLocation.address.region;
            visitor_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>';
            document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';

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 They provide a geolocation service based on IP addresses where you don’t need user permission.

Try this example:

<!DOCTYPE html>
<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=""></script>
    <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>
         .done (function(location) {

It’s possible to guess latitude and longitude based on the origin IP address of a web request. You need access to a database or service which maps IPs to locations, such as MaxMind’s geoip ( There should be JavaScript / PHP wrappers available for services such as these which you can make use of.

GeoIP lookup is not very reliable and can get out of date easily. If you need something more accurate you’ll have to solicit some information from the user, such as a zip code.

Leave a Reply

Your email address will not be published. Required fields are marked *