Applies to:

  • Android Studio (Beta) 0.8.9
  • Android Google Maps v2

What?
A sequel to my article "Basic Android App using Google Maps and Current Location", this article suggests how to add Map as a sub activity. Note that this article is based on a new blank project which does not include code from the previous example but you can still build this over the previous example (as I did).

Why?
The previous article meant that the Google map was your main activity and any other activity would be a sub-activity; returning to the map activity would restart the app as a menu item, it would need to launch a new intent... I wanted to change my previous example so that the homepage of the app (the starting page) will simply display a button to the map (in case of offline mode or incompatibility with the device).

How?
In this example, I'm going to add the map as a fragment. This is the most rudimentary example (display map, move camera and display marker) and can be run from any other activity:

MapFragment.java
package com.joellipman.mymapapp;  // change to your own package

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * A fragment that launches other parts of the demo application.
 */
public class MapFragment extends Fragment {

    MapView mMapView;
    private GoogleMap googleMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflate and return the layout
        View v = inflater.inflate(R.layout.activity_map_fragment, container,
                false);
        mMapView = (MapView) v.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume();// needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        googleMap = mMapView.getMap();
        // latitude and longitude
        double latitude = 17.385044;
        double longitude = 78.486671;

        // create marker
        MarkerOptions marker = new MarkerOptions().position(
                new LatLng(latitude, longitude)).title("Hello Maps");

        // Changing marker icon
        marker.icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

        // adding marker
        googleMap.addMarker(marker);
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
        googleMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));

        // Perform any camera updates here
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}


activity_map_fragment.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>


From your main activity java: eg. MainActivity.java
private void addMapFragment() {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        MapFragment fragment = new MapFragment();
        transaction.add(R.id.mapView, fragment);
        transaction.commit();
}


Same file again but on the menu item (or to call it from anywhere): eg. MainActivity.java
setContentView(R.layout.activity_map_fragment);
addMapFragment();

Add comment


Send

Comments   

0 Chandra Monday, 18th April 2016, 7:57 am
thanks dude.. you saved my life
+2 lovableRogue Friday, 15th January 2016, 12:15 pm
Anyone else had this error:

call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with `checkPermissio n`) or explicitly handle a potential `SecurityException`

on line: Location myLocation = locationManager .getLastKnownLo cation(provider );?
+1 Robert Thursday, 14th January 2016, 3:12 pm
This works very nice !

I would have 1 simple question ... when pressing the back button, I would like to return MainActivity ( I am running "addMapFragment " by pressing a button ).

Currently when pressing the Back button on the phone the application just closes and stays at the background ... so far I have tried for example to add the fragment to the stack and use the popBackStack method ... but no luck so far.

Thank you!
Robert
+1 Kemo Saturday, 26th December 2015, 4:55 pm
It was my mistake, this example works fine, I just added tabLayout and viewPager to the wrong xml file - I posted it in app_bar_main.xm l instead of posting it inside of content_main.xm l.
+1 Kemo Friday, 25th December 2015, 6:39 pm
This works, but I have a problem with map navigation - I cannot swipe up and down on the map, zoom in or out, and left-right swiping drags - it is very slow. Does anyone else have this problem?
+1 CM Saturday, 24th October 2015, 5:26 pm
Extremely nice, simple, helpful example. There's not many that share the knowledge in such a concise, easy to understand & implement way. Please keep doing it.. Thanks for getting me (like Andrew) on track after much searching,
+5 Andrew F Wednesday, 8th July 2015, 1:15 pm
For 3 days straight I have tried to get this working and you have lit up the darkness!
From the bottom of my heart, thank you.
Andrew