I need to get users latitude and longitude from browser, but on most of browsers are some restrictions that doesn't let to do it. How to tell users that his geolocation is off or it simply doesn't support it?
I tried something like this, but neither ipad or safari on my mac prompt anything.
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(success);
else
alert('not supported');
DEMO: http://jsfiddle.net/7sRdS/
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// ...
}, function(error) {
//error handling
switch(error.code) {
case error.PERMISSION_DENIED:
//User denied the request for Geolocation.
break;
case error.POSITION_UNAVAILABLE:
//Location information is unavailable.
break;
case error.TIMEOUT:
//The request to get user location timed out.
break;
case error.UNKNOWN_ERROR:
//An unknown error occurred.
break;
}
alert("Geolocation error: " + error.code);
},
{
timeout:10000 //10s
});
} else {
alert("Geolocation services are not supported by your browser.");
}
Take a look at modernizr which provides multiple feature detection tests.
Related
I'm trying to use the Google Maps API and get current location.
my page is being served over HTTPS.
I have no problems on Android devices. The browser wants location permission and I can get my location. But ios phone does not want access permission and gives location permission error.
is there anything i can do to ask for access permission for ios phone?
Here is my code
function findMyPlace() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError, { timeout: 20000 });
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
//do something
}
In the documentation for getCurrentPosition over at MDN
you can see that getCurrentPosition() has an error callback. Apply the error callback and see what type of response you get. I've added a code-sample below.
function findMyPlace() {
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition( (position) => {
console.log(position.coords);
}, (e) => {
console.log(e);
});
} else {
console.log("navigator not supported");
}
}
findMyPlace();
I have implemented the devise omniauth setup and when I’m signed in with either Facebook, twitter or google the html5 geolocation returns a position unavailable error. But when I'm logged in as regular devise user it works just fine! How can I allow access to the html5 geolocation on my rails app when logged in with a social media account?
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setGeoCookie,showError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
window.location = window.location;
window.alert("Permission denied");
break;
case error.POSITION_UNAVAILABLE:
window.location = window.location;
window.alert("Location information is unavailable.");
break;
case error.TIMEOUT:
window.location = window.location;
window.alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
window.location = window.location;
window.alert("An unknown error occurred.");
break;
}
location.reload();
}
Update 1
I changed the code to the following and I'm getting the following errors inside the browser console:
Origin does not have permission to use Geolocation service
[blocked] Access to geolocation was blocked over secure connection with mixed content to https://localhost:3000.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
alert("Geolocation is not supported by this browser.");
}
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
Any ideas on how to unblock this?
This is not a rails issue but a Javascript issue. Somewhere in your template, CSS, or Javascript you load something from http instead of https. Use your browser's inspector to find the culprit.
UPDATE: it doesn't work only on safari mobile (chrome for ios works correctly).
I am trying to get user location using google maps API.
It works correctly on desktop FF and Chrome (shows city and country) but it doesn't show anything on iOS safari (iOS 11). Also it seems that it doesn't work properly on some other mobile devices.
Note that I am using HTTPS so there are no problems with security.
Here's javascript code:
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{
document.getElementById("userlocation").innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position){
lat=position.coords.latitude;
lon=position.coords.longitude;
displayLocation(lat,lon);
}
function showError(error){
switch(error.code){
case error.PERMISSION_DENIED:
document.getElementById("userlocation").innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
document.getElementById("userlocation").innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
document.getElementById("userlocation").innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
document.getElementById("userlocation").innerHTML="An unknown error occurred."
break;
}
}
function displayLocation(latitude,longitude){
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
document.getElementById("userlocation").innerHTML = city + ", " + country;
}
else {
document.getElementById("userlocation").innerHTML = "address not found";
}
}
else {
document.getElementById("userlocation").innerHTML = "Geocoder failed due to: " + status;
}
}
);
}
And here's HTML:
<body onload="getLocation()">
<p id="userlocation">Getting your location ...</p>
</body>
Thanks in advance.
In your mobile device, you have to enabled the geolocation for safari in the settings. If the geolocation is disabled, nothing will append.
Try this manipulation:
Go to settings.
Next, go to the confidentiality (with a hand in the left of the scroll menu).
Then, click to the location service bar.
Scroll down and accept the location's service for safari.
Tell me if you have some questions
I would like to hide() or show() a button that allows users to use their current location based on whether or not they are currently allowing location to be used in their browser setting.
the below code only checks if the browser supports geolocation and not whether or not the particular user is allowing it.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML="Geolocation is not supported by this browser.";}
}
Is there a boolean value that I can detect for their browser setting letting me know if location is currently allowed?
thanks for any suggestions.
Have you read http://www.w3schools.com/html/html5_geolocation.asp
What you want to do is check the errors to see if they allowed it or denied the request.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
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;
}
}
The below code will allow you to check the permission status without invoking the navigator.geolocation permission request.
Browsers Supported: Chrome(43+), Firefox(46+), Edge and Opera.
Unsupported: Safari(mac, ios), Internet explorer, Android webview.
navigator.permissions && navigator.permissions.query({name: 'geolocation'})
.then(function(PermissionStatus) {
if (PermissionStatus.state == 'granted') {
//allowed
} else if (PermissionStatus.state == 'prompt') {
// prompt - not yet grated or denied
} else {
//denied
}
})
Here is the Reference Link.
Compatibility on other browsers is unknown. I haven't tested it myself but please feel to test yourself and comment below.
I am trying to set up my code to locate the most accurate position on a android phone or tablet. Since getCurrentPosition doesn't give enough time for the GPS to find a location, I am using the watchPosition. This works great but I need to allow the user to stop this watchPostion so I'm using the clearWatch function. This clearWatch function works on my android phone 2.2.2 version but not on the android tablet 3.2.1 version. My other issue is on my android phone, once I stop/clearwatch and I try locating my position again my phone vibrates and the browser closes. What is the issue here? I've tried this on other phones as well and have the same problem. If anyone has any suggestions I would greatly appreciate it. Below is the code I'm using.
//function to locate using GPS
function ShowMyLocation(){
if (navigator.geolocation) {
ShowProgressIndicator('map');
watchID = navigator.geolocation.watchPosition(function(position){
var mapPoint = esri.geometry.geographicToWebMercator(new esri.geometry.Point(position.coords.longitude, position.coords.latitude, new esri.SpatialReference({
wkid: 4326
})));
var graphicCollection = esri.geometry.geographicToWebMercator(new esri.geometry.Multipoint(new esri.SpatialReference({
wkid: 4326
})));
graphicCollection.addPoint(mapPoint);
geometryService.project([graphicCollection], map.spatialReference, function(newPointCollection){
HideProgressIndicator();
if (!map.getLayer(baseMapLayerCollection[0].Key).fullExtent.contains(mapPoint)) {
alert('Data not available for the specified address.');
return;
}
mapPoint = newPointCollection[0].getPoint(0);
AddServiceRequest(mapPoint);
});
}, function(error){
HideProgressIndicator();
switch (error.code) {
case error.TIMEOUT:
alert('Timeout');
break;
case error.POSITION_UNAVAILABLE:
alert('Position unavailable');
break;
case error.PERMISSION_DENIED:
alert('Permission denied');
break;
case error.UNKNOWN_ERROR:
alert('Unknown error');
break;
}
}, {
timeout: 5000,
maximumAge: 90000,
enableHighAccuracy: true
});
}
}
function clearWatch(){
// Cancel the updates when the user clicks a button.
if (watchID > 0) {
navigator.geolocation.clearWatch();
alert("Stop tracking location");
}
}
Your syntax is incorrect. clearWatch takes an argument of which watch ID to cancel.
In your case, you should have clearWatch(watchID), not clearWatch().