I'm trying to take the geolocation of the User and then do a query.
In Mozilla Firefox it works fine also in Safari.... but in Chrome it doesnt work at all.
window.onload = function(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude,
longitude = position.coords.longitude;
console.log(latitude + " " + longitude);
},handleError);
function handleError(error){
//Handle Errors
switch(error.code) {
case error.PERMISSION_DENIED:
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
console.log("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
console.log("An unknown error occurred.");
break;
}
}
}else{
// container.innerHTML = "Geolocation is not Supported for this browser/OS.";
alert("Geolocation is not Supported for this browser/OS");
}
};
And i get the error 1
User denied the request for Geolocation.
But i haven't denied any request, actually the popup window doesnt come up at all.
I've went to Chrome Settings > Show advanced > Privacy > Content Settings > Location allow for all.
Restarted chrome and nothing happened. I'm sure my code is 100% legit so does anyone know how to deal with it?
Thanks!
Ok this was quite easy... Chrome since 20 of April 2016 has disabled the Geolocation API for insecure websites (without https)... link here
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
So dont worry..
The easiest way is to click on the area left to the address bar and change location settings there. It allows to set location options even for file:/// and all other types
If you are using chrome, please have a look at the answer below:
HTML 5 Geo Location Prompt in Chrome
Related
I created a mobile web-app to rate places (such as restaurant, coffee etc) in my city.
So far I use navigator.geolocation.getCurrentPosition() of the geolocation API to get the place's coordinates in the form when users create the "place's post". I try to avoid a maximum in the process to force the user to write an address they most of time don't know by heart..
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
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;
}
}
At that point my main issue is a lot of user have disabled the navigator's location and it's too complicated for them to go back to the settings to do the changes. In the same time they report me that if they would be invited to share a one-time location, they would accept it.
As far as I know it's impossible to do so because the navigator's settings take the lead on all web interactions. So once it's disabled, no turning back.
I was wondering what was the most seamless way for the user to share coordinates without touching to its navigator's settings?
im building an app through phonegap, with a geolocation button.
if a user denies permission for geolocation the first time, how can i ask for permission again when they click the geolocation button again?
my code structure at the moment is:
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, positionError);
} else {
hideLoadingDiv()
showError('Geolocation is not supported by this device')
}
}
function positionError() {
hideLoadingDiv()
showError('Geolocation is not enabled. Please enable to use this feature')
}
You can't.
The only thing you can do is to display the instructions to reactivate the location sharing in his browser's settings (https://support.google.com/chrome/answer/142065?hl=en).
Two ways of doing this:
If you have a version of Chrome bigger than 83.0.4103.97 then use the lock icon in the URL
For older versions of Chrome the bellow code will work fine:
The bellow code only works on Chrome.
Steps:
Open Chrome
Open the console
Copy in the console
var allowGeoRecall = true;
var countLocationAttempts = 0;
Copy in the console the functions
function getLocation() {
console.log('getLocation was called')
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,
positionError);
} else {
hideLoadingDiv()
console.log('Geolocation is not supported by this device')
}
}
function positionError() {
console.log('Geolocation is not enabled. Please enable to use this feature')
if(allowGeoRecall && countLocationAttempts < 5) {
countLocationAttempts += 1;
getLocation();
}
}
function showPosition(){
console.log('posititon accepted')
allowGeoRecall = false;
}
Run the function in the console
getLocation();
After running this you will be asked to allow to share your position. If your response is negative you will be asked again until you agree.
HINT: If your user has a negative response, let him know why you need the coordinates. Is vital for him to understand that this step is vital for the good run of the web app.
This can be reset in Page Info which can be accessed by clicking the lock icon next to the URL and allowing Location
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;
});
im building an app through phonegap, with a geolocation button.
if a user denies permission for geolocation the first time, how can i ask for permission again when they click the geolocation button again?
my code structure at the moment is:
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, positionError);
} else {
hideLoadingDiv()
showError('Geolocation is not supported by this device')
}
}
function positionError() {
hideLoadingDiv()
showError('Geolocation is not enabled. Please enable to use this feature')
}
You can't.
The only thing you can do is to display the instructions to reactivate the location sharing in his browser's settings (https://support.google.com/chrome/answer/142065?hl=en).
Two ways of doing this:
If you have a version of Chrome bigger than 83.0.4103.97 then use the lock icon in the URL
For older versions of Chrome the bellow code will work fine:
The bellow code only works on Chrome.
Steps:
Open Chrome
Open the console
Copy in the console
var allowGeoRecall = true;
var countLocationAttempts = 0;
Copy in the console the functions
function getLocation() {
console.log('getLocation was called')
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,
positionError);
} else {
hideLoadingDiv()
console.log('Geolocation is not supported by this device')
}
}
function positionError() {
console.log('Geolocation is not enabled. Please enable to use this feature')
if(allowGeoRecall && countLocationAttempts < 5) {
countLocationAttempts += 1;
getLocation();
}
}
function showPosition(){
console.log('posititon accepted')
allowGeoRecall = false;
}
Run the function in the console
getLocation();
After running this you will be asked to allow to share your position. If your response is negative you will be asked again until you agree.
HINT: If your user has a negative response, let him know why you need the coordinates. Is vital for him to understand that this step is vital for the good run of the web app.
This can be reset in Page Info which can be accessed by clicking the lock icon next to the URL and allowing Location
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