Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent double prompt for geolocation in Phonegap app?

I created a PhoneGap app for iPhone that uses geolocation via JavaScript inside webview.

When I run the app the first time, it'll prompt me to allow geolocation for this app.

When I hit "ok", it'll prompt me again with the same question but this time it states that "index.html" wants permission to use geolocation.

That makes sense because iOS probably wants permission to allow geolocation for the app itself for the first time and the 2nd time the browser wants permission.

However, since doesn't lead to a great user experience:

How can I prevent this double prompt? (I'd be enough if the 2nd prompt could be prevented)

like image 471
Timo Ernst Avatar asked Dec 13 '12 09:12

Timo Ernst


1 Answers

I found the cause for the issue.

The call to navigator.geolocation.getCurrentPosition(onsuccess, onerror) happens before Phonegap was fully loaded.

This means that the geolocation call of webview (and not a native call via PhoneGap) is being triggered which will again ask for permission (which does make sense). Compare it to the normal Safari browser on your Smartphone. It'll ask for geolocation permission for every new website. It's the same when loading index.html via PhoneGap on application startup.

However, the solution is to wait for the deviceready event which gets fired when PhoneGap has fully loaded:

document.addEventListener("deviceready", function(){
     navigator.geolocation.getCurrentPosition(onsuccess, onerror, params);
}, false);

This will make the PhoneGap API available which overwrites the default HTML5 gelocation call of the browser and get the device's geo location via a native call (which you already accepted in the first prompt).

This will work because PhoneGap's API calls are identical to the standard W3C call for HTML5: http://docs.phonegap.com/en/2.2.0/cordova_geolocation_geolocation.md.html#Geolocation

like image 68
Timo Ernst Avatar answered Oct 03 '22 14:10

Timo Ernst