Android OS: Add GoogleMap as fragment

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
copyraw
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();
    }
}
  1.  package com.joellipman.mymapapp;  // change to your own package 
  2.   
  3.  import android.os.Bundle; 
  4.  import android.support.v4.app.Fragment; 
  5.  import android.view.LayoutInflater; 
  6.  import android.view.View; 
  7.  import android.view.ViewGroup; 
  8.   
  9.  import com.google.android.gms.maps.CameraUpdateFactory; 
  10.  import com.google.android.gms.maps.GoogleMap; 
  11.  import com.google.android.gms.maps.MapView; 
  12.  import com.google.android.gms.maps.MapsInitializer; 
  13.  import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
  14.  import com.google.android.gms.maps.model.CameraPosition; 
  15.  import com.google.android.gms.maps.model.LatLng; 
  16.  import com.google.android.gms.maps.model.MarkerOptions; 
  17.   
  18.  /** 
  19.   * A fragment that launches other parts of the demo application. 
  20.   */ 
  21.  public class MapFragment extends Fragment { 
  22.   
  23.      MapView mMapView; 
  24.      private GoogleMap googleMap; 
  25.   
  26.      @Override 
  27.      public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  28.                               Bundle savedInstanceState) { 
  29.          // inflate and return the layout 
  30.          View v = inflater.inflate(R.layout.activity_map_fragment, container, 
  31.                  false)
  32.          mMapView = (MapView) v.findViewById(R.id.mapView)
  33.          mMapView.onCreate(savedInstanceState)
  34.   
  35.          mMapView.onResume()// needed to get the map to display immediately 
  36.   
  37.          try { 
  38.              MapsInitializer.initialize(getActivity().getApplicationContext())
  39.          } catch (Exception e) { 
  40.              e.printStackTrace()
  41.          } 
  42.   
  43.          googleMap = mMapView.getMap()
  44.          // latitude and longitude 
  45.          double latitude = 17.385044
  46.          double longitude = 78.486671
  47.   
  48.          // create marker 
  49.          MarkerOptions marker = new MarkerOptions().position( 
  50.                  new LatLng(latitude, longitude)).title("Hello Maps")
  51.   
  52.          // Changing marker icon 
  53.          marker.icon(BitmapDescriptorFactory 
  54.                  .defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
  55.   
  56.          // adding marker 
  57.          googleMap.addMarker(marker)
  58.          CameraPosition cameraPosition = new CameraPosition.Builder() 
  59.                  .target(new LatLng(17.385044, 78.486671)).zoom(12).build()
  60.          googleMap.animateCamera(CameraUpdateFactory 
  61.                  .newCameraPosition(cameraPosition))
  62.   
  63.          // Perform any camera updates here 
  64.          return v; 
  65.      } 
  66.   
  67.      @Override 
  68.      public void onResume() { 
  69.          super.onResume()
  70.          mMapView.onResume()
  71.      } 
  72.   
  73.      @Override 
  74.      public void onPause() { 
  75.          super.onPause()
  76.          mMapView.onPause()
  77.      } 
  78.   
  79.      @Override 
  80.      public void onDestroy() { 
  81.          super.onDestroy()
  82.          mMapView.onDestroy()
  83.      } 
  84.   
  85.      @Override 
  86.      public void onLowMemory() { 
  87.          super.onLowMemory()
  88.          mMapView.onLowMemory()
  89.      } 
  90.  } 


activity_map_fragment.xml
copyraw
<?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>
  1.  <?xml version="1.0" encoding="utf-8"?> 
  2.   
  3.  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  4.      android:orientation="vertical" android:layout_width="match_parent" 
  5.      android:layout_height="match_parent"> 
  6.   
  7.      <com.google.android.gms.maps.MapView 
  8.          android:id="@+id/mapView" 
  9.          android:layout_width="match_parent" 
  10.          android:layout_height="match_parent" 
  11.          class="com.google.android.gms.maps.SupportMapFragment" /> 
  12.  </LinearLayout> 


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


Same file again but on the menu item (or to call it from anywhere): eg. MainActivity.java
copyraw
setContentView(R.layout.activity_map_fragment);
addMapFragment();
  1.  setContentView(R.layout.activity_map_fragment)
  2.  addMapFragment()
Category: AndroidOS :: Article: 597

Credit where Credit is Due:


Feel free to copy, redistribute and share this information. All that we ask is that you attribute credit and possibly even a link back to this website as it really helps in our search engine rankings.

Disclaimer: The information on this website is provided without warranty and any content is merely the opinion of the author. Please try to test in development environments prior to adapting them to your production environments. The articles are written in good faith and, at the time of print, are working examples used in a commercial setting.

Thank you for visiting and, as always, we hope this website was of some use to you!

Kind Regards,

Joel Lipman
www.joellipman.com

Related Articles

Joes Revolver Map

Accreditation

Badge - Certified Zoho Creator Associate
Badge - Certified Zoho Creator Associate

Donate & Support

If you like my content, and would like to support this sharing site, feel free to donate using a method below:

Paypal:
Donate to Joel Lipman via PayPal

Bitcoin:
Donate to Joel Lipman with Bitcoin - Valid till 8 May 2022 3QnhmaBX7LQSRsC9hh6Je9rGQKEGNQNfPb
© 2021 Joel Lipman .com. All Rights Reserved.