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

4

29

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.

Semibreve answered 14/10, 2014 at 6:59 Comment(0)
R
64

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.

Reeher answered 14/10, 2014 at 7:20 Comment(3)
Pretty sure the Google API no longer returns those object properties any more. At least in my testing it did on on 14/2/2019.Algeciras
@MattTheNinja That's true! Google API is now a paid service and this option must be activated from your options... that's after you input your Credit Card info :*/Polarimeter
@MattTheNinja Best way to do that is still to let the CDN provide you with the info...Polarimeter
M
34

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.

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>
Maxinemaxiskirt answered 8/4, 2016 at 7:46 Comment(5)
This provide unlimited requests or any restriction for requests?Groggery
No restrictions, unlimited requests are allowed.Maxinemaxiskirt
Best alternate solution to get the longitude and latitudeSalutation
what's the catch with this website, unlimited free? they don't list any paid add-ons eitherPals
Although it is unlimited, the location responses where no were near to exact location :(Couperin
W
0

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 (https://www.maxmind.com/en/geoip-demo). 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.

Weighted answered 14/10, 2014 at 7:8 Comment(1)
IPs to location is not so accurate... if person is using smart phone...then its good but if person is using web and the provider's location is somewhere else then it will give you that location.. so that would be wrong information.Semibreve
T
0

Call below API to fetch location details using ip address

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

Limit: 45 requests per minute from an IP address

Documentation : https://ip-api.com/docs/api:json

Tripper answered 15/12, 2022 at 6:56 Comment(3)
This service returned me a result 563km away from where I am. I expected something approximative, but not that much.Perreault
@SimonArnold Please try with this ip-api.com/json and check if region is set correct in device or emulator you are usingTripper
It was about 150km out for me too, but maybe a decent solution if you only need an approximate location.Broach

© 2022 - 2024 — McMap. All rights reserved.