How to Implement Google Map Inside Fragment in Android?
Last Updated :
22 Feb, 2022
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:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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: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: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"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
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:
Similar Reads
How to Implement GridView Inside a Fragment in Android?
A GridView is a versatile and efficient widget that allows you to display items in a grid-like fashion, perfect for presenting images, icons, or any structured data. Fragments, on the other hand, are essential components for building flexible and modular user interfaces. They enable the creation of
5 min read
How to Implement onBackPressed() in Fragments in Android?
In Android, the Fragment is the part of the 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. onBac
3 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. Â A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It h
12 min read
How to Implement Google's Places AutocompleteBar in Android?
If you ever used Google Maps on mobile or accessed from a desktop, you must have definitely typed in some location into the search bar and selected one of its results. The result might have had fields such as an address, phone numbers, ratings, timings, etc. Moreover, if you ever searched for a plac
5 min read
How to Implement Current Location Button Feature in Google Maps in Android?
The current location is a feature on Google Maps, that helps us locate the device's position on the Map. Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going t
5 min read
How to Implement findViewById in Fragments in Android?
Fragments represent a part of the app's UI which is reusable. Fragments are having its own layout, and lifecycle but must be hosted inside an activity to be visible. The activity becomes easier to modify if it consists of many fragments. A fragment can have multiple instances inside an activity. fin
3 min read
How to Implement Stepper Functionality in Android?
A Stepper widget allows you to organize content in a sequence of steps, and the user can navigate between them. In this article we are going to implement a Stepper-like functionality in an Android app here we take the help of Tablayout to achieve this. A Sample video is attached below to get an idea
4 min read
How to Implement Item Click Interface in Android?
When we click on an item in an application either it gives some information or it redirects the user to any other page. In this article, we will learn that how we can implement Item Click Interface in an android application. What we are going to build in this article?In this article, we will be usin
5 min read
How to Draw Polyline in Google Maps in Android?
Google Maps is used in many Android applications. While using Google Maps there are many modifications which you will get to see while using Maps in this apps. When we have used Google Maps in different apps such as OLA and Uber we will get to see lines and routes drawn on our Maps. In this article,
4 min read
How to Implement TNImage Library in Android?
Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android O
3 min read