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

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.

3 ways to do this in this answer:
Get a GPS precise location asking the user to allow access to its browser's API
Get an approximate location (country, city, area) using an external GeoIP service
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>

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

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.

Related

Geo location getCurrentPosition() and watchPosition() not work on insecure origins

I need user's Lattitude and longitude using php. try following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of HTML5 Geolocation</title>
<script type="text/javascript">
function showPosition(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
document.getElementById("result").innerHTML = positionInfo;
});
} else{
alert("Sorry, your browser does not support HTML5 geolocation.");
}
}
</script>
</head>
<body>
<div id="result">
<!--Position information will be inserted here-->
</div>
<button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>
but when i run this code in server i found this warning error when i fetch User Lattitude and Longitude.
getCurrentPosition() and watchPosition() no longer work on insecure
origins. To use this feature, you should consider switching your
application to a secure origin, such as HTTPS
while Same code works here..else suggest any other code to get user Latitude and longitude.
thanks.
Geolocation API Removed from Unsecured Origins in Chrome 50.
This change is effective as of Chrome 50 (12PM PST April 20 2016).
Chrome's developer tools console has been providing warnings since version 44 (released July 21 2015).
There have been a number of public announcements that describe the rationale (and discussion) of why we are making this change:
Intent to deprecate set of powerful features over HTTP (Feb 2015)
Intent to deprecate Geolocation API over HTTP (Nov 2015)
Chrome Dev Summit (Nov 2016)
Chrome Beta Channel release blog (March 17, 2016)
Chrome Status website
There have been a number of other sources that have highlighted this: Mobiforge (Jan 26, 2016), Wired (March 17, 2016), VentureBeat (April 13, 2016).
Read More Documentatin here .So thats not possible to use GeoLocation Without HTTPS.

navigator.geolocation.getCurrentPosition/watchPosition is not working in android 6.0

Here is my javascript code :
function getLocation() {
//navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:30000, enableHighAccuracy:true});
var mobile =jQuery.browser.mobile;
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if(mobile){
watchLocation(function(coords) {
var latlon = coords.latitude + ',' + coords.longitude;
//some stuff
}, function() {
alert("error");
});
} else {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("error");
}
}
}
function watchLocation(successCallback, errorCallback) {
successCallback = successCallback || function(){};
errorCallback = errorCallback || function(){};
// Try HTML5-spec geolocation.
var geolocation = navigator.geolocation;
if (geolocation) {
// We have a real geolocation service.
try {
function handleSuccess(position) {
alert("position:"+position.coords);
successCallback(position.coords);
}
geolocation.watchPosition(handleSuccess, errorCallback, {
enableHighAccuracy: true,
maximumAge: 5000 // 5 sec.
});
} catch (err) {
errorCallback();
}
} else {
errorCallback();
}
}
I have tried both getCurrentPosition and watchPosition.
It's reaching errorCalback() method when control comes to geolocation.watchPosition line.
I am testing in Motorola G 2nd Gen with Android 6 and Google chrome browser and opera mini.
Update 1: When I put alert in error call back function I got error:1; message:Only Secure origins are allowed(see:link).
navigator.geolocation.getCurrentPosition(showPosition, function(e)
{ alert(e); //alerts error:1; message:Only Secure origins are allowed(see: )
console.error(e);
})
Update 2: With the help from g4s8 I am able to findout that the error is because of insecure URL. i.e only accessing with http instead of https.But then also I bypassed that in browser by clicking advanced button.But it will prompt for Do you want to allow location, which I don't want..is there any way to access location without prompting it?
Your page should be served over https to access geolocation API.
See Geolocation API Removed from Unsecured Origins
Starting with Chrome 50, Chrome no longer supports obtaining the user's location using the HTML5 Geolocation API from pages delivered by non-secure connections
...
It is an important issue as it will directly impact any site that requires use of the geolocation API and is not served over https
To fix this serve your page over https or on localhost.
Thank you...Is there any way to bypass it??
You can try to use some geolocation services, e.g.
geoip2, Geolocation request
how to use them? can you show an example?? from those two can i access user location without knowing them?
GeoIP2 detect you location by ip address. You can obtain country (geoip2.country()) and city (geoip2.city) with js lib:
<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
Here https://dev.maxmind.com/geoip/geoip2/javascript/ you can find full documentation.
Google maps geolocation is google service, so you need to get api key first. Then you can send POST request with json parameters to https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY and get the response:
{
"location": {
"lat": 51.0,
"lng": -0.1
},
"accuracy": 1200.4
}
where location is the user’s estimated latitude and longitude, in degrees,
and accuracy is the accuracy of the estimated location, in meters.
Full json parameters defenition you can find in "Request body" section here https://developers.google.com/maps/documentation/geolocation/intro#overview
Also you can find useful those answers: getCurrentPosition() and watchPosition() are deprecated on insecure origins
using IP it provides only country and city..??
Yes, only this.
will it provide physical location like how getCurrent Position provides??
No, you can't get physical location, because it can be accessed only via gelocation API, that was restricted in insecure context.
Also you have one more option. You can host only one page (that access geolocation API) on https server, and redirect from this page to your http site with user location in get parameters.
/* https page */
navigator.geolocation.getCurrentPosition(function (result) {
window.location.href = "http://your.site.com/http-page?lat=" + result.latitude + "&long=" + result.longitude;
});

I want to get my accurate latitude longitude of my linux device on command line. Like Geolocation in HTML5. I dont have access to browser

I want to send email of current Lat Long from my Linux device. I tried geo location in HTML5 browsers, it works great. But i want it on command line. I tried so many options such as curl, geoip to some websites by IP, but they all show my ISP's position, not mine.
I prefer using it on command line or python etc tools.
I could successfully write a python program which opens a locally saved page of HTML5 geolocation code and shows accurate lat long also. Then automatically python fetches lat long from browser and shows on terminal.
File: test.py
from splinter.browser import Browser
import os.path
import time
browser = Browser()
browser.visit('file://' + os.path.realpath('geo.html'))
time.sleep(5)
elements = browser.find_by_css("#demo")
div = elements[0]
print div.value
browser.quit()
File: geo.html
<html>
<head>
<title>Test</title>
<p id="demo"></p>
<script type="text/javascript">
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} 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>
</head>
<body>
<p>The element below will receive content</p>
<div id="div" />
<script type="text/javascript">getLocation()</script>
</body>
</html>
But a bug is there, that every time python opens the browser, i have to click "Share location: Yes" in browser. Because the page is running on local server, not on any webserver. So this solution was not applicable.
Can anyone suggest me reliable solution to get my current lat long in linux in command line?
On Linux you need to talk to gpsd.
You could talk to libgps: http://manpages.ubuntu.com/manpages/wily/en/man3/libgps.3.html
You could use the DBUS interface.
Or you could use the python interface: how to use/install gps python library

Accessing location using Javascript

I run the code shown below from different places but this results in same latitude and longitude value at different places.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body onload="getLocation()">
<p id="demo"> </p>
<script>
var x= document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML= position.coords.latitude;
x.innerHTML= position.coords.longitude;
var lat=position.coords.latitude;
var lon=position.coords.longitude;
}
</script>
**strong text**</body>
</html>
Any help would be appreciated.
In short, the problem isn't with your code, but most likely with your device. I can tell you're using the demo code from the W3Schools article on the geolocation API. That code seems to work fine for me, at least as much as I would expect.
Geolocation isn't terribly precise in all cases. According to MDN, the method use to determine location will be the most accurate available for your device at that time. If you're testing on a desktop browser, the results might be no more accurate than to the nearest city, and in some cases even more inaccurate than that (My home in Michigan registers as the middle of New York state, for some weird reason). If you test on a 3g or 4g phone, you might get better results, down to the nearest broadcast area. If you test on a phone with GPS, you might get highly accurate data, where you'll notice a difference if you move even a few feet or so. I say 'might' for these cases, because location data is a huge privacy concern area, and there's a lot of things that might interfere with geolocation to protect a user's privacy.
If you're seeing the same result from relativly small moves, this would easily be the cause. If you've travelled a few hundred miles to run your code elsewhere, then I would have to admit that there's something

W3C Geolocation API not working in Chrome

The below code works in Firefox but not in Google Chrome:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script type="text/javascript">
var successCallback = function(data) {
console.log('latitude: ' + data.coords.latitude + ' longitude: ' + data.coords.longitude);
};
var failureCallback = function() {
console.log('location failure :(');
};
var logLocation = function() {
//determine if the handset has client side geo location capabilities
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(successCallback, failureCallback);
}
else{
alert("Functionality not available");
}
};
logLocation();
setTimeout(logLocation, 5000);
</script>
</head>
<body>
<p>Testing</p>
<body>
</html>
What's going on? I thought Google Chrome was supposed to support the W3C Geolocation API.
Works perfectly for me - with both Chrome 11 and Firefox 4.0.1 on Win 7
Make sure you've not disabled location tracking in Chrome: Options > Under the Hood > Content Settings > Location
Because of security restrictions, resources loaded with the file:/// scheme are not allowed access to location. See HTML 5 Geo Location Prompt in Chrome.
If your domain is insecure (e.g. HTTP rather than HTTPS) then you are not allowed access to location in Chrome. This is since Chrome version 50 (12PM PST April 20 2016).
See https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only for details.
in 2017 :
Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.
Geolocation API Removed from Unsecured Origins in Chrome 50
It works fine for me - with both Chrome 11 and Firefox 4.0.1 on Win 7
Make sure you've not disabled location tracking in Chrome: Options > Under the Hood > Content Settings > Location please allow the permission
and after checking the permission please run it
after running either it will be sucesscallback or else it comes to errorcallback
function sucesscallback (position)
{
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: userLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapObject = new google.maps.Map(document.getElementById("googleMap"), myOptions);
var marker = new google.maps.Marker({
map: mapObject,
position: userLatLng
});
}
function failureCallback(error) {
switch (error.code) {
case 1:
alert("User denied the request for Geolocation.");
break;
case 2:
alert("Location information is unavailable. Please ensure Location is On");
break;
case 3:
alert("timeout");
break;
case 4:
alert("An unknown error occurred.");
break;
}
}
<div id='googleMap' style='width:300px;height:300px;'>
</div>
The Geolocation API lets you discover, with the user's consent, the user's location. You can use this functionality for things like guiding a user to their destination and geo-tagging user-created content; for example, marking where a photo was taken.
The Geolocation API also lets you see where the user is and keep tabs on them as they move around, always with the user's consent (and only while the page is open). This creates a lot of interesting use cases, such as integrating with backend systems to prepare an order for collection if the user is close by.
You need to be aware of many things when using the Geolocation API. This guide walks you through the common use cases and solutions.
https://developers.google.com/web/fundamentals/native-hardware/user-location/?hl=en

Categories