Android WebView 使用 Google Map JavaScript API


在 Android 中,

可以使用 Google Map JavaScript API,

WebView 顯示 Google Map 地圖,

參考範例, 如下 :

 權限
<uses-permission android:name="android.permission.INTERNET" />

 Layout XML
<?xml version="1.0"  encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:id="@+id/main"
    >
    <WebView android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />
</LinearLayout>

 Android 程式碼
public class HelloWorld extends Activity
{
    private static final String MAP_URL = "http://gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html";
    private int      gMapZoom = 8;
    private WebView  gWebView;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        setupWebView();
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    
    private void setupWebView(){
        final String centerURL = "javascript:initialize();"
                               + "centerAt(" + -34.397 + "," + 150.644 + ");"
                               + "map.setZoom(" + gMapZoom + ");";
        
        gWebView = (WebView)findViewById(R.id.webview);
        
        // JavaScript 啟用
        gWebView.getSettings().setJavaScriptEnabled(true);
        
        // 網頁執行完成後, 接著要執行的網頁 (也可是 JavaScript)
        gWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url){
                view.loadUrl(centerURL);
            }
        });
        
        gWebView.loadUrl(MAP_URL);
    }
}

範例 :

Related Posts Plugin for WordPress, Blogger...