Saturday, March 30, 2013

Embed Google Map in WebView

Embed Google Map in WebView


To load your custom Map, open it in PC, copy the Short URL in share option. It will be used later.

copy the Short URL in share option


MainActivity.java, load mapPath with the Short URL in share option.
package com.example.androidwebmap;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
 
 WebView myWebView;
 
 String mapPath = "https://maps.google.com/?ll=37.0625,-95.677068&spn=29.301969,56.513672&t=h&z=4";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  myWebView = (WebView)findViewById(R.id.mapview);
  myWebView.getSettings().setJavaScriptEnabled(true);
  myWebView.setWebViewClient(new WebViewClient());
  
  myWebView.loadUrl(mapPath);
 }

}


Modify layout to add a MapView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <WebView
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Notes:
- Permission of "android.permission.INTERNET" is need.
- Not all function can work on WebView! such as user cannot touch the marker on map.

download filesDownload the files.

3 comments:

  1. I tested your example and it works ok, but when i include this code in mine, i recived the next error: Error converting result java.io.IOException: Attempted read on closed stream.
    Do you known what's wrong?
    I have one activity with some layouts, one another. I hidden one as needed. In the layout where i have the webview, i have a fragment too, but in this case i hidden one view, it's depend if my device has OpenGL 2.0 or not. If the device don't has OpenGL 2.0 I use your code...

    ReplyDelete
  2. Awesome tutorial! Helped clear my issue. Thanks!

    ReplyDelete
  3. This code stills work nowadays? when i try to open maps.google in a webview, it doesn't open in the webview but it launchs the google maps app... How can we force use in webview?
    Thanks for your advice

    ReplyDelete