getting location in WebView via js
I am not sure why, but now it works. There is code for simply app with webView which use gps location.
MainActivity:
package com.qiteq.gpswebview;
import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView wv = new WebView(this);
wv.loadUrl("http://qiteq.pl/stack/index.html");
setContentView(wv);
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
}, 0);
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(new WebChromeClient() {
@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
});
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qiteq.gpswebview">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And index.html:
<script>
function getLocationConstant()
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError);
} else {
alert("No GPS support");
}
}
function onGeoSuccess(event)
{
document.getElementById("location").value = event.coords.latitude+", "+event.coords.longitude;
alert("Success: "+event.coords.latitude+", "+event.coords.longitude);
}
function onGeoError(event)
{
alert("Error code " + event.code + ". " + event.message);
}
</script>
<input type="text" name="location" id="location" style="width:278px;">
<button onclick="getLocationConstant()" >Click</button>