Android Google Map In Fragment Example | Map Inside Fragment

google map integration in android, android google map in fragment, android current location on google map, android google map custom marker, android google map custom info window

This post is about Android google map in fragment example.

We will implement a google map inside a fragment using supportmapfragment class.

Integration of google map inside fragment is little different than the integration in android activity.

Udemy Course

You can enhance your android skill with below course. You will also find other courses at below link as per your current skills.

Go to Udemy For Course Information 

Look of Google Map In Fragment

Prerequisite

First of all, we need to create a project in the google developer console to have a map in our fragment.

I have written a tutorial on how to integrate google map API in android studio.

First, read and understand this tutorial. After creating this example, you will have one sample app with google map.

You will also have a Google API key, which is required in this project. So go through above link first and then come back with your Google API key.

Step 1. Adding dependencies

We will add google dependencies to use some classes related to google map.

For this, add the below line in your build.gradle(Module: app) file.

 implementation 'com.google.android.gms:play-services:12.0.1'

Step 2. Manifest Changes

Add below source code in AndroidManifest.xml file right after <application> tag.

<meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR API key"/>

In the above code, you need to write your google API key in the second line.

After </application> tag, add below code

 <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

Whole source code for  AndroidManifest.xml file will look like below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.parsaniahardik.google_map_fragment">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR 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>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

</manifest>

Step 3. Image

In this google map, we will add one icon to the marker.

For this icon, add one image in the res->drawable directory.

You can download sample image by clicking the below link.

[sociallocker]Download Spidy Image[/sociallocker]

Step 4. Making Fragments

We will use two fragments in this example. One is for sample and another will contain google map.

Make a new fragment and give it a name “OneFragmnent

Copy and paste the following code in fragment_one.xml file

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".OneFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorAccent"
        android:textColor="#fff"
        android:gravity="center"
        android:textSize="35dp"
        android:text="One Fragment" />

</FrameLayout>

Create another fragment named “MapFragment”

Add the following coding lines in fragment_map.xml file

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".MapFragment">

    <fragment
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/frg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>

I have just added one fragment tag. It is representing the layout of the google map.

Consider below line in <fragment> tag.

 android:name="com.google.android.gms.maps.SupportMapFragment"

Above line will convert the simple fragment into the google map fragment.

Write down the below coding lines in MapFragment.java file

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
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;

public class MapFragment extends Fragment {

    public MapFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_map, container, false);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.frg);  //use SuppoprtMapFragment for using in fragment instead of activity  MapFragment = activity   SupportMapFragment = fragment
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                mMap.clear(); //clear old markers

                CameraPosition googlePlex = CameraPosition.builder()
                        .target(new LatLng(37.4219999,-122.0862462))
                        .zoom(10)
                        .bearing(0)
                        .tilt(45)
                        .build();

                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 10000, null);

                mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.4219999, -122.0862462))
                        .title("Spider Man")
                        .icon(bitmapDescriptorFromVector(getActivity(),R.drawable.spider)));

                mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.4629101,-122.2449094))
                        .title("Iron Man")
                        .snippet("His Talent : Plenty of money"));

                mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.3092293,-122.1136845))
                        .title("Captain America"));
            }
        });


        return rootView;
    }

    private BitmapDescriptor bitmapDescriptorFromVector(Context context, int vectorResId) {
        Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
        vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
        Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.draw(canvas);
        return BitmapDescriptorFactory.fromBitmap(bitmap);
    }

}

Clarification of above code

Read the below line

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.frg);

I have created an object of SupportMapFragment class.

If you are working in activity instead of fragment, you should use the object of the MapFragment class instead of SupportMapFragment class.

Now we will start the map using the object mapFragment.

Below source code will create the map and it’s markers.

 mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                mMap.clear(); //clear old markers

                CameraPosition googlePlex = CameraPosition.builder()
                        .target(new LatLng(37.4219999,-122.0862462))
                        .zoom(10)
                        .bearing(0)
                        .tilt(45)
                        .build();

                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 10000, null);

                mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.4219999, -122.0862462))
                        .title("Spider Man")
                        .icon(bitmapDescriptorFromVector(getActivity(),R.drawable.spider)));

                mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.4629101,-122.2449094))
                        .title("Iron Man")
                        .snippet("His Talent : Plenty of money"));

                mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.3092293,-122.1136845))
                        .title("Captain America"));
            }
        });

Consider the following lines

 mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
 mMap.clear(); //clear old markers

First line will set the type of the map.

Second will clear all the previous markers and will clean the map.

Following code will set the camera position.

CameraPosition googlePlex = CameraPosition.builder()
                        .target(new LatLng(37.4219999,-122.0862462))
                        .zoom(10)
                        .bearing(0)
                        .tilt(45)
                        .build();

You can set the various properties like target. You need to pass latitude and longitude of the place to set the target.

Then set the zoom, bearing, tilt etc. build() method will finally set up the map.

We are setting different markers with following code

  mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.4219999, -122.0862462))
                        .title("Spider Man")
                        .icon(bitmapDescriptorFromVector(getActivity(),R.drawable.spider)));

                mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.4629101,-122.2449094))
                        .title("Iron Man")
                        .snippet("His Talent : Plenty of money"));

                mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(37.3092293,-122.1136845))
                        .title("Captain America"));

.position property defines the place of the marker using the latitude and longitude.

.title property defines the title of the marker.

.icon property will set the custom image as an icon of the marker.

.snippet property contain some additional information about the marker.

In .icon property, I have used bitmapDescriptorFromVector() method.

Source code for bitmapDescriptorFromVector() method is as below

 private BitmapDescriptor bitmapDescriptorFromVector(Context context, int vectorResId) {
        Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
        vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
        Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.draw(canvas);
        return BitmapDescriptorFactory.fromBitmap(bitmap);
    }

This method creates a bitmap descriptor from the given image.

Step 5. Final Codes

Last but not least, add some codes in activity_main.xml and MainActivity.java file

Write the below code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/btn1"
            android:layout_height="wrap_content"
            android:text="Fragment 1 " />
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/btn2"
            android:layout_height="wrap_content"
            android:text="Map Fragment" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container_frame_back"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">


    </LinearLayout>

</LinearLayout>

I have taken two buttons and one linearlayout which will be our frame layout.

LinearLayout whose id is container_frame_back is our frame and we will load our both fragments in this frame.

Now code for MainActivity.java is as follwing

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button btn1, btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new OneFragment(), false, "one");
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new MapFragment(), false, "one");
            }
        });

    }

    public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.container_frame_back, fragment, tag);
        ft.commitAllowingStateLoss();
    }
}

Describing above snippet

Button click methods are as below

 btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new OneFragment(), false, "one");
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new MapFragment(), false, "one");
            }
        });

When the user clicks the first button, OneFragment will be loaded in the frame.

Second button will open the Map Fragment.

addFragment() method’s code is as below

 public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.container_frame_back, fragment, tag);
        ft.commitAllowingStateLoss();
    }

This fragment will open the new fragment which it receives via it’s first parameter.

Second parameter will decide whether to add a fragment in back stack or not.

For more information about back stack, read fragment backstack management tutorial.

So it was all the word regarding android google map in fragment example.

Do not hesitate to use comment section for any query or for your valuable reviews!

Thanks and good luck!

Udemy Course

You can enhance your android skill with below course. You will also find other courses at below link as per your current skills.

Go to Udemy For Course Information 

Familiar Examples

Visit tutorials on Google Map

Android Show Current Location Marker On Google Map

Custom Marker Google Map In Android Studio

Custom Info Window Click Google Map Android

Download Source Code For Android Google Map In Fragment

[sociallocker]Download Source Code For Google_Map_Fragment[/sociallocker]