Android MapView Example Tutorial

In this tutorial, we are going to learn how to use android MapView in android application development. Android MapView is a View widget in android and it’s sole usage is to display map.

It can come in handy when you want to display a map with other View controls around it. In this android example tutorial, we are going to create a Contact Us page using the MapView and WebView.

The MapView will hold the map address of our contact through a marker overlay while the WebView will hold formatted html text of the address.

You can go further and customize the app to fit your project requirement.

Using the android MapView is not the only way to display map in your android application. You can as well use Google Android Map API. I wrote a tutorial on Google Android Map API using Android Google Map Version 2 using Google Play Services.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android contact us

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidMapView

Package: com.inducesmile.androidmapview

Select Blank Activity

Name your activity : MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

 

Google Map API Key

Next, we are going to obtain the Google Map API key for this application. The follow steps are needed to obtain the Api key

Get information about your app’s certificate.

Register a project in the Google Developers Console if you don’t already have one, add the Google Maps Android API as a service for the project, and create an API key.

Add the key to your app by adding an element to your app manifest.

For a detailed steps, follow the step listed in Google API key documentation.

Once the key is obtained, we are going to add it to the strings.xml resource file as shown below.

<string name="google_android_map_api_key"> Map API key </string>
<string name="google_android_map_api_key"> Map API key </string>


Manifest.xml

There are few user permission we need to add in the Manifest.xml file for the Map. On android 6 and above, we will go further to request this permission during run-time. The modified version of the Manifest.xml file is as shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.androidmapview">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <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">
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_android_map_api_key" />
        <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>

 

Build.gradle

In the app build.gradle file, we will add the Google Play Google Play for Map dependency library. The modified version of the file is as shown.

apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "com.inducesmile.androidmapview"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.google.firebase:firebase-ads:9.0.1'
    compile 'com.google.android.gms:play-services-maps:9.0.1'
}

 

Strings.xml

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<resources>
    <string name="app_name">Android MapView</string>
    <string name="hello_blank_fragment">Hello blank fragment</string>
    <string name="contact_us">Contact Us</string>
    <string name="google_android_map_api_key">Map API key</string>
</resources>

 

Colors.xml

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

 

activity_main.xml

Open the default layout file created for us by Android Studio when the project was create. We are going to implement the android MapView in a Fragment and subsequently add the Fragment to the MainActivity class.

It contains only a RelativeLayout ViewGoup which will act as a wrapper to the Fragment class we will add to the Activity class.

Add the code below to activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container_wrapper"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.inducesmile.androidmapview.MainActivity">
</RelativeLayout>

 

MainActivity.java

The MainActivity class is very simple. Its main function is to add the Fragment class to the Activity class.

Copy the code below to your Activity class.

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_wrapper, new ContactFragment());
        fragmentTransaction.commit();
    }
}

 

fragment_contact.xml

This layout file will holder all the View controls that will appear in our Contact page. We will add a MapView and below it a WebView controls.

Add the code below to the layout file.

<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:orientation="vertical"
    tools:context="com.inducesmile.androidmapview.ContactFragment">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textColor="@color/colorPrimaryDark"
            android:text="@string/contact_us"
            android:paddingTop="8dp"
            android:paddingLeft="16dp"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4"
        android:orientation="vertical">
        <com.google.android.gms.maps.MapView
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        android:orientation="vertical">
        <WebView
            android:id="@+id/contact_us"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none">
        </WebView>
    </LinearLayout>
</LinearLayout>

 

ContactFragment.java

In ContactFragment class, we are going to get the instances of the View controls in onCreateView() method of the Fragment class.

For the text address that will be added to the WebView, we will create an assets folder in the app folder root directory and add a .html file named contact.html.

Open ContactFragment.java and add the code below to the file.

package com.inducesmile.androidmapview;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
public class ContactFragment extends Fragment {
    MapView mapView;
    GoogleMap googleMap;
    private WebView contactWebView;
    public ContactFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact, container, false);
        getActivity().setTitle("Contact Us");
        contactWebView = (WebView)view.findViewById(R.id.contact_us);
        contactWebView.setBackgroundColor(0);
        if(Build.VERSION.SDK_INT >= 11){
            contactWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        }
        contactWebView.getSettings().setBuiltInZoomControls(true);
        AssetManager mgr = getContext().getAssets();
        String filename = null;
        try {
            filename = "contact.html";
            System.out.println("filename : " + filename);
            InputStream in = mgr.open(filename, AssetManager.ACCESS_BUFFER);
            String sHTML = StreamToString(in);
            in.close();
            contactWebView.loadDataWithBaseURL(null, sHTML, "text/html", "utf-8", null);
            //singleContent.setText(Html.fromHtml(sHTML));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mapView = (MapView) view.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        if (mapView != null) {
            googleMap = mapView.getMap();
            googleMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_flag))
                    .anchor(0.0f, 1.0f)
                    .position(new LatLng(55.854049, 13.661331)));
            googleMap.getUiSettings().setMyLocationButtonEnabled(false);
            if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return view;
            }
            googleMap.setMyLocationEnabled(true);
            googleMap.getUiSettings().setZoomControlsEnabled(true);
            MapsInitializer.initialize(this.getActivity());
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(new LatLng(55.854049, 13.661331));
            LatLngBounds bounds = builder.build();
            int padding = 0;
            // Updates the location and zoom of the MapView
            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
            googleMap.moveCamera(cameraUpdate);
        }
        return view;
    }
    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
    public static String StreamToString(InputStream in) throws IOException {
        if(in == null) {
            return "";
        }
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
        }
        return writer.toString();
    }
}

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new android blog post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it

OTHER INTERESTING POSTS:

3 Comments

Add a Comment