Open In App

How to Implement Google Map Inside Fragment in Android?

Last Updated : 22 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices improves the user experience and adaptability of the application. Fragments can exist only inside an activity as its lifecycle is dependent on the lifecycle of host activity. For example, if the host activity is paused, then all the methods and operations of the fragment related to that activity will stop functioning, thus the fragment is also termed as sub-activity. Fragments can be added, removed, or replaced dynamically i.e., while activity is running. In this article, we are going to implement Google Map inside Fragment in Android Studio. Using it you will be able to locate any place in the world in your android application.

What we are going to build in this article?

Here is a sample video of what we are going to build in this article. Note that we are going to make this project in Java language.

Step by Step Implementation

Step 1. Key generation

Go to website site https://mapsplatform.google.com. The interface shown below will appear. Click on Create Project.

Give your project a suitable name and also give the name of the organization if you are working for personal projects then let it be as No Organization.

Now select Maps SDK for Android and click on enable.

Go to credentials > Create Credentials and then an API key will be generated successfully.

Step 2. Create a New Project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • Name the application at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?  

Step 3. Adding required dependencies

Navigate to Gradle scripts > build.gradle(module) and use the following dependencies in it-

implementation 'com.google.android.gms:play-services-maps:17.0.0'

Step 4. Working on XML files

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
   <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/frame_layout"/>
  
</androidx.constraintlayout.widget.ConstraintLayout>


Navigate to app > right-click > new > fragment > blank fragment. Name it as MapFragment and use the following code in fragment_map.xml file

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapFragment">
  
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/google_map"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>
  
</RelativeLayout>


Navigate to the AndroidManifest.xml file and use the following code in it-

XML




<?xml version="1.0" encoding="utf-8"?>
    package="com.example.googlemapinsidefragment">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <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/Theme.GoogleMapInsideFragment">
  
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="Key should be copied here which you generated in step 1"/>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
  
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
  
</manifest>


Step 5. Working on Java files

Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding.

Java




package com.example.googlemapinsidefragment;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
  
import android.os.Bundle;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Initialize fragment
        Fragment fragment=new MapFragment();
  
        // Open fragment
        getSupportFragmentManager()
                .beginTransaction().replace(R.id.frame_layout,fragment)
                .commit();
    }
}


Navigate to the MapFragment.java file and use the following code in it. Comments are added to the code to have a better understanding.

Java




package com.example.googlemapinsidefragment;
  
import android.os.Bundle;
  
import androidx.fragment.app.Fragment;
  
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
  
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
  
public class MapFragment extends Fragment {
  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Initialize view
        View view=inflater.inflate(R.layout.fragment_map, container, false);
  
        // Initialize map fragment
        SupportMapFragment supportMapFragment=(SupportMapFragment)
                getChildFragmentManager().findFragmentById(R.id.google_map);
  
        // Async map
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                // When map is loaded
                googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                    @Override
                    public void onMapClick(LatLng latLng) {
                        // When clicked on map
                        // Initialize marker options
                        MarkerOptions markerOptions=new MarkerOptions();
                        // Set position of marker
                        markerOptions.position(latLng);
                        // Set title of marker
                        markerOptions.title(latLng.latitude+" : "+latLng.longitude);
                        // Remove all marker
                        googleMap.clear();
                        // Animating to zoom the marker
                        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));
                        // Add marker on map
                        googleMap.addMarker(markerOptions);
                    }
                });
            }
        });
        // Return view
        return view;
    }
}


Here is the final output of our application.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads