Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android webview geolocation

I have to retrieve a user's location in a WebView. I do this with the following Javascript:

function getLocation() {    navigator.geolocation.getCurrentPosition(displayLocation, handleError); } 

But the permission request popup never opens.

I've set these settings:

ws.setJavaScriptEnabled(true); ws.setGeolocationEnabled(true); ws.setJavaScriptCanOpenWindowsAutomatically(true); 

What is the correct way to access a user's location from within a WebView?

like image 339
Ste Avatar asked Mar 16 '11 18:03

Ste


People also ask

What is geolocation permission?

Geolocation permissions are applied to an origin, which consists of the host, scheme and port of a URI. In order for web content to use the Geolocation API, permission must be granted for that content's origin. This class stores Geolocation permissions. An origin's permission state can be either allowed or denied.

What is WebChromeClient?

A callback interface used by the host application to notify the current page that its custom view has been dismissed. class. WebChromeClient.FileChooserParams.


1 Answers

  • JavaScript must be enabled in the WebView, using WebSettings.setJavaScriptEnabled(true);
  • The app needs permission ACCESS_FINE_LOCATION
  • The WebView must use a custom WebChromeClient which implements WebChromeClient.onGeolocationPermissionsShowPrompt(). This method is called by the WebView to obtain permission to disclose the user's location to JavaScript. (In the case of the browser, we show a prompt to the user.) The default implementation does nothing, so permission is never obtained and the location is never passed to JavaScript. A simple implementation which always grants permission is ...

    webView.setWebChromeClient(new WebChromeClient() {  public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {     callback.invoke(origin, true, false);  } }); 

Geolocation uses databases to persist cached positions and permissions between sessions. The location of the database is set using WebSettings.setGeolocationDatabasePath(...). If the location of the database is not set, the persistent storage will not be available, but Geolocation will continue to function correctly otherwise. To set the location of the databases, use ...

webView.getSettings().setGeolocationDatabasePath( context.getFilesDir().getPath() ); 
like image 125
Chris Cashwell Avatar answered Oct 10 '22 14:10

Chris Cashwell