Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Map API
3.
Example Application
3.1.
Starting a Project
3.2.
Generating the API key
3.3.
Permissions
3.4.
Designing the Map Fragment
3.5.
Designing the UI 
4.
Frequently Asked Questions
5.
Conclusion  
Last Updated: Mar 27, 2024
Easy

Google Maps APIs in Android

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In this blog, we will look into the Google Map API of Android. We will follow the step-by-step procedure of how to set up the project, generate an API key to use in our app, add the required dependency, give several permissions to our app, etc. 

API stands for Application Programming Interface, gives us a special feature to use some functionality/data from the third party, to know about API read this article.

In this article we will first discuss the Google Map API, the types of data it returns, the methods that it offers to its user to interact with the map, and last we discuss a simple example to demonstrate the use of Google API. We will be designing an app having two screens, on the first screen a small description of Tamil Nadu is given, and on pressing the navigate button its map will be shown to you. 

Map API

Google Map API provides us unique feature to integrate google maps into our application to show maps, routes, etc., to enrich the user experience. 

The Google Maps Android API offers five types of maps:

  1. Normal: Typical road map. It shows roads, some features built by humans, and significant natural features such as rivers.
  2. Hybrid: Satellite photographs, roads, and human-built features are visible.
  3. Satellite: Only Satellite photographs data are visible.
  4. Terrain: Topographic data including colors, contour lines and labels, perspective shading, and some roads.
  5. None: Displays empty grid.

Some methods help the user interact with the map more efficiently.

Methods Description
addCircle(CircleOptions options) Add circle on the map
addPolygon(PolygonOptions options) Add polygon on the map
addTileOverlay(TileOverlayOptions options) Add tile overlay on the map 
animateCamera(CameraUpdate update) This shows the update in location with animation
clear() Clears the map
getMyLocation() Returns current location of user
moveCamera(CameraUpdate update) Reposition the camera as per the update instructions
setTrafficEnabled(boolean enabled) Set the traffic layer on or off
snapshot(GoogleMap.SnapshotReadyCallback callback) Snapshots the map
stopAnimation() Stops the camera animation if there is any progress

You can also read about, android operating system

Let us head over to an example to get the more clear idea. In the example below, we have discussed the step-by-step procedure of building a basic app that shows the map according to the given latitude and longitude and how to generate an API key through google console.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example Application

Starting a Project

Firstly, we will open the android studio. If in case you don’t have an android studio setup, consider reading this article. Start a new project and select the Google Maps Activity.

After the project has been built, completely open the file google_map_api.xml. In this file, we must set the API key of our map API then only our map API will work. It is an effortless procedure to generate the API key. There is a link given in this file (on the 7th line), press Ctrl and hover over the link and then click (you can also copy-paste the link in your browser).

Generating the API key

Google Cloud Platform will open where you need to create a new project, enable the API, and create a new API key.

Give a project name and location.

Click enable API button.

Click on create new API key button to generate the API key.

 

 

Copy the generated API key and paste it on the google_maps_api.xml file in place of 

YOUR_API_KEY.

Permissions

Copy these lines of code to your AndroidManifest.xml file in order to get all the required permissions for the app . 

   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission
 android:name="android.permission.ACCESS_COARSE_LOCATION" />

You also need to add one dependency in the build.gradle file in the dependencies section and click on the sync button.

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

Designing the Map Fragment

Content of activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:map="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:id="@+id/frag_map"
   android:layout_height="match_parent"
   tools:context=".MapsActivity"
  android:name="com.google.android.gms.maps.SupportMapFragment"/>

In MapsActivity.java write these lines of code 

package com.example.googlemapapi_dem
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import com.example.googlemapapi_demo.databinding.ActivityMapsBinding;
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 MapsActivity extends FragmentActivity implements OnMapReadyCallback {

   privae GoogleMap myMap;
   private ActivityMapsBinding ourbinding;
   double lon = 78.38, lat = 11.05;

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

       ourbinding = ActivityMapsBinding.inflate(getLayoutInflater());
       setContentView(ourbinding.getRoot());

       // Get the SupportMapFragment and notified when the map is ready to be used.
       SupportMapFragment myMapFragment = (SupportMapFragment) getSupportFragmentManager()
               .findFragmentById(R.id.frag_map);
       myMapFragment.getMapAsync(this);
   }
   @Override
   public void onMapReady(GoogleMap googleMap) {
       myMap = googleMap;
       // Add a marker in place and move the camera
       LatLng place = new LatLng(lat, lon);
       myMap.addMarker(new MarkerOptions().position(place).title("Marker in Place"));
       myMap.moveCamera(CameraUpdateFactory.newLatLng(place));

  

Designing the UI 

Add a new empty activity to the app from the procedure shown in the picture below. Add it as launcher activity. Add this picture to your drawable folder with the name tamil_nadu.jpg


Now simply, we will design the XML file of the newly added activity (activity_main.xml) and code its .java/.kt file accordingly.

activity_main.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">

   <TextView
       android:id="@+id/tv_head"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Google Map Demo"
       android:textSize="40dp"
       android:textStyle="bold"
       android:textColor="@color/black"
       app:layout_constraintTop_toTopOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       android:layout_marginTop="30dp"/>

   <TextView
       android:id="@+id/tv_enter"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Tamil Nadu"
       android:textSize="30dp"
       android:textColor="@color/black"
       app:layout_constraintTop_toBottomOf="@id/tv_head"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       android:layout_marginTop="50dp"/>
   <ImageView
       android:id="@+id/iv_tamil"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:src="@drawable/tamil_nadu"
       app:layout_constraintTop_toBottomOf="@id/tv_enter"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       android:layout_marginLeft="30dp"
       android:layout_marginRight="30dp"/>

   <Button
       android:id="@+id/bt"
       android:layout_width="match_parent"
       android:layout_height="50dp"
       android:text="Navigate"
       app:layout_constraintTop_toBottomOf="@id/iv_tamil"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       android:layout_marginLeft="30dp"
       android:layout_marginRight="30dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.googlemapapi_demo;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       Button bt = findViewById(R.id.bt);
       bt.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent intent = new Intent(MainActivity.this,MapsActivity.class);
               startActivity(intent);
           }
       });
   }
}

Now you are all set up and have completed all the procedures for building a simple Google Maps API application. Select an Android emulator to run the app. You will get this as output in the emulator

 

Frequently Asked Questions

  1. What is the use of the API key?
    Without an API key, your API URL will not work means you will get no results.
     
  2. Are these API keys are different for everyone?
    Yes, these API keys are different for everyone. 
     
  3. What if we do not add uses-permission in the AndroidManifest.xml file?
    Your app will not get permission to access the mobile’s location and internet.

Conclusion  

In this article, we have extensively discussed the  Google Maps API in Android and its implementation in Android Studio. We discussed how API Keys could be created and used in an android application.
We hope that this blog has helped you enhance your knowledge regarding Google Maps API. If you want to learn more about using API in Android, refer to this article. And to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website. Do upvote our blog to help other ninjas grow.
Happy Coding!

 

Previous article
Difference between MVC, MVP, and MVVM Architecture in Android
Next article
Android Drag and Drop Feature
Live masterclass