Geolocation problems when switch GPS on and off - javascript

Thanks in advance first.I build a website with an option to lead you to a specific place when you click button "Navigate". Everything works fine on desktop and everything works fine on mobile when GPS of the phone is enabled.
I use the google maps reference and it works just fine:
http://maps.google.com/maps?saddr=myLat,myLng&daddr=targetLat,targetLng
I do this on $('.button').click(). Not on $(window).load or $(document).ready. When you click the button, it calls the geolocation functions:
function getGeolocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
$('.error-message').html('<p>Your browser does not support this function</p>');
}
}
function geoSuccess(position) {
myLat = position.coords.latitude;
myLng = position.coords.longitude;
window.location.href = 'http://maps.google.com/maps?saddr=' + myLat + ',' + myLng + '&daddr=targetLat,targetLng';
}
function geoError(){
switch(error.code) {
alert('example alert - enable GPS');
case error.PERMISSION_DENIED:
$('.error-message').html('<p>User denied the request for Geolocation.</p>');
break;
case error.POSITION_UNAVAILABLE:
$('.error-message').html('<p>Location information is unavailable.</p>');
break;
case error.TIMEOUT:
$('.error-message').html('<p>The request to get user location timed out.</p>');
break;
case error.UNKNOWN_ERROR:
$('.error-message').html('<p>An unknown error occurred.</p>');
break;
}
}
But the problem comes when the GPS is disabled.
First of all, sometimes, it doesn't enter in geoError(). I tried so many times, but the only thing I "found" is that it caches sometimes. Is that possible ?
But the main problem is that, when the GPS is disabled, the "example alert" pops up, then I turn my GPS on and click the button again, it doesn't work again. I have to refresh the page to apply the GPS turn on. I want to avoid that. Does anyone know why is that happening and is there a way to do what I want?
The other problem is when I load my page with GPS turned on. Then I turn it off and click the button. Nothing happens at all. It enter getGeolocation(), gets true and then it stops. It doesn't enter getCurrentPosition(). Any ideas?

I had ever faced the same problem, and final I found the solution. You can change getCurrentPosition to watchPosition, it seems getCurrentPosition cannot recognize when location changes, watch help us do that. Try my solution, hope it helps you :)
P/S you should settime out: 10000 for watchpostion or getcurrentpostion

I've got the same problem on Android 6.0 and Chrome 59.0.3071.125.
In short: When I start a webapp with location Off, I receive a PositionError as expected.
However when I switch location back to On, every subsequent call to navigator.geolocation.getCurrentPosition or navigator.geolocation.watchPosition returns same error.
I've tried the same with maps.google.com and result is exactly the same (they show a snackbar Google Maps could not determine your precise location) so I believe that there is no workaround.
There is a similar post on ionic framework forum - They didn't find a solution either.
To sum up:
Looks like Chrome is checking for location services **on page load and doesn't update the state any more.
So only thing that helps is reloading the webapp which forces chrome to check again if location services are available.
Update:
this is a known bug in Chromium: 672301, 721977.
Workaround is available in Chrome Mobile v59 behind lsd-permission-prompts flag.

In your error function, the argument is missing.
function geoError(error){
//code goes here
}
Source: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_geolocation_error

Related

Not allowed to launch cutom protocol because a user gesture is required

I need to run my custom protocol twice but it doesn't work the second time, I got this error ( Not allowed to launch 'cutomProtocol' because user gesture is required. ) I tried to find a solution but I did not find any!
Same problem with chrome, firefox and edge.
I need to see this popup twice
window.location.href = 'my-protocol://${base64}';
and
customProtocolVerify(
`my-protocol://${base64}`,
() => {
// successCb: Callback function which gets called when custom protocol is found.
console.log('My protocol found and opened the file successfully..');
},
() => {
// failCb: Callback function which gets called when custom protocol not found.
console.log('My protocol not found.');
}
);
I tried with these two and didn't work
Clarification
I have a custom protocol.
My scenario:
check if it's installed successfully (I'm using customProtocolVerify method) and that method makes the launch if the protocol is found
run some APIs
launch the protocol again
My problem:
Step 3 doesn't work, I have the error on the console that says " Not allowed to launch... " and of course I can't see my popup to open my protocol.
I'm asking for help to make step 3 work
The only way to bypass this "bug" is to ask the user twice (or in a loop) by showing a OK alert or some sort of user confirm box.
My solution:
OpenLinkInExternalApp(Link);
alerty.alert('', { title: '', okLabel: 'Open Link' }, function () {
OpenLinkInExternalApp(Link);
});
The above code will open the external app, then a OK alert will pop up, after clicking OK, I call the same code again. Do this in a loop if needed.
TIP:
We guide our users to use split screen at this stage. This is where users can dock your web-app on the left and the external app on the right as an example.
Alert Box:
We user Alerty.js https://github.com/undead25/alerty#readme

Javascript - prompt cause 'document is not focused'

If I add a prompt to the function it works once, but gives the error:
"Uncaught (in promise) DOMException: Document is not focused" at the second attempt.
This is the code:
function site(str) {
var url = prompt();
var text = 'The URL is ';
(async() => {
await navigator.clipboard.writeText(text + url);
})();
}
<button class="button" onclick='site()'>URL</button>
I've asked my best friend, Google, but I can't find any solutions. What am I doing wrong?
It is probably caused by this bug in chromium (Issue #1085949) which makes your prompt call take focus from the Document and not return it when closed. I was not able to reproduce this issue on Safari and Firefox.
The same bug can be reproduced by doing alert instead of prompt followed by navigator.clipboard.writeText.
Your JS may be running on a child page. The following works for me:
await parent.navigator.clipboard.writeText('text to copy to Clipboard here.);
The same error will occur, if you don't await AND immediately after the command e.g. do an alert for feedback to the user, as the alert will steal the focus. Or if you otherwise navigate away or change the focus as a side effect.
(not the case in the above question, but just in case someone else stumbles across this problem and finds this question, I'll leave it here)

Ionic 3 geolocation not working when GPS is disabled

I have ionic native geolocation plugin installed
"#ionic-native/geolocation": "^4.15.0"
I have also tried "4.6.0" and "4.20.0". It is working absolutely fine when I keep my GPS enabled before going to that page. But when GPS is not enabled, It won't ask me to turn it ON, gives an error on console and carry undefined coordinates with it.
I wrote the method of getCurrentPosition in constructor/ionViewDidLoad. So even user enable it on that page, the method does not invoke and the coordinates remain undefined.
Following is code
this.geolocation
.getCurrentPosition()
.then(resp => {
console.log(resp);
this.longitude = resp.coords.longitude;
this.latitude = resp.coords.latitude;
})
.catch(error => {
console.log("Error getting location", error);
});
I don't know if I'll have to give manual permissions or what?? I did the same before a couple of months before and everything was fine. First time I am facing this kind of issue. Please help me to get out of this.
you should manually ask permission and request the user to enable location. You can do this with the Diagnostic plugin (#ionic-native/diagnostic). You should use the following methods:
diagnostic.isLocationEnabled()
diagnostic.isLocationAvailable()
diagnostic.requestLocationAuthorization()
If you want to update location after permission is granted you you can use this method:
diagnostic.registerLocationStateChangeHandler()
You can pass a callback here check if location is enabled and available de what you need.
Install the Diagnostics plugin from here: https://ionicframework.com/docs/v3/native/diagnostic/, then check if location is enabled with diagnostics.isLocationAvailable(), if not, prompt the user to enable it from the device settings screen using diagnostics.switchToLocationSettings().

Why isn't this HTML5 geolocation code working to get a user's location on iOS only?

I'm testing this simple geolocation code and it's not working on iOS devices for some reason. I've tested on MacOS, Windows, Windows Phone, Android phones, etc and it works as it should on all.
I always receive the "POSITION_UNAVAILABLE" error after granting permission.
navigator.geolocation.getCurrentPosition(
function success(position) {
var primary = getUniqueId();
var url = endpointBaseurl +
'?property_code=' + propertyCode +
'&distribService=' + distribService +
'&lat=' + position.coords.latitude +
'&lon=' + position.coords.longitude +
'&distribTarget=' + primary;
//Update the line below to be one of your links.
addMenuItem('Offers', url);
},
function error(err) {
switch (err.code) {
case 1:
alert("You must allow location in order to receive tobacco offers. Please refresh and try again.")
break;
case 2:
alert('POSITION_UNAVAILABLE');
break;
case 3:
alert('Error 3');
break;
default:
alert("Unable to determine your location. Please refresh and try again.");
}
}, options);
I've tested on physical devices as well as through Browserstack. The site is running on HTTPS.
Any ideas on why should isn't working or how I should go about debugging? I'm pulling my hair out over this one.
Edit:
On this page, it says the following:
The acquisition of the geolocation failed because at least one internal source of position returned an internal error.
Try using PositionError.message (in your case, err.message):
Returns a human-readable DOMString describing the details of the
error. Specifications note that this is primarily intended for
debugging use and not to be shown directly in a user interface.
Make sure you have location services turned on and set to always or while using in the iOS settings.

Google Maps in IE11 gives "Unspecified error"

I'm getting a very strange error when using custom Google Maps in a website of one of our clients. The map has some markers on it, and when you open the marker you can see a dialog with the address of that location. When I close this dialog (obviously by clicking the cross) in IE11, I get an "Unspecified error". For some reason, this error is being thrown from the method "getBoundingClientRect()". No other browser has this issue (not even IE8).
I am using Google Maps API version 3.14.
Does anyone know what this could be? I'm not sure if it's necessary to place any code, but I'm willing to do that if that makes everything more clear.
You can use this fix for IE (place this code on top):
HTMLElement.prototype._getBoundingClientRect=HTMLElement.prototype.getBoundingClientRect;
HTMLElement.prototype.getBoundingClientRect = function() {
try {
return this._getBoundingClientRect();
} catch(e) {
return { top : this.offsetTop, left : this.offsetLeft };
}
}

Categories

Resources