android webview geolocation
android, geolocation
Solution
- 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() );
Problem
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`?