MikeKeepsOnShine
MikeKeepsOnShine

Reputation: 1748

How to pass values from Java to Javascript insiede an Android WebView

I'm building an Android application where i have to use javascript to show a map. I'm using a WebView that loads an HTML file stored in the assets folder.

    wv=(WebView)findViewById(R.id.webView1);
    wvs=wv.getSettings();
    wv.setWebChromeClient(new WebChromeClient());
    wvs.setJavaScriptEnabled(true);
    wv.addJavascriptInterface(new WebAppInterface(this), "Android");
    wv.loadUrl("file:///android_asset/android_index.html");

In this file, the code dislpays a map using a JavaScript method. I have to center the map (and add a pin) to the current device position. The methods that do these things work fine and the i get the current device position correctly. So, i have to pass the coordinates to the JavaScript method called in the HTML file.

Here the script line where i should use the coordinates:

jQuery(function ($) {
        var map;
        ...
        map.setCenter(/*here latitude*/,/*here longtitude*/);
        ..
});

How can i pass from Java to JavaScript the values i get from the device?

Upvotes: 0

Views: 1315

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006574

On Android 4.3 and below, and on Android 4.4+ with android:targetSdkVersion set to 18 or lower, call loadUrl() on the WebView, with a javascript: URL, the same way you set up a bookmarklet on a desktop OS.

On Android 4.4+ with android:targetSdkVersion set to 19 or higher, use the new evaluateJavaScript() method on WebView.

Upvotes: 2

Related Questions