Java Android App Development Course, Utilizing Google Maps

Understanding the use of Google Maps in Android app development is of great value to many developers.
By utilizing the Google Maps API, various functions can be implemented, such as allowing users to view real-time map information, find specific locations, and provide navigation features. In this article, we will explain in detail how to implement Google Maps in an Android app using Java and provide some example codes.

1. What is Google Maps API?

Google Maps API is a service that allows developers to easily implement map features in websites or mobile applications using map information provided by Google. By using this API, users can access information such as maps, markers, and routes for their desired areas. To use Google Maps in an Android app, it is necessary to integrate the Google Maps API.

2. Creating a Google Maps API Key

To use Google Maps in the app, an API key is required. Here’s how to create an API key.

  1. Log in to Google Cloud Platform. (Google Cloud Console)
  2. Create a new project.
  3. Navigate to ‘API and Services’ > ‘Library’ from the dashboard.
  4. Search for ‘Maps SDK for Android’ and enable it.
  5. Navigate to ‘API and Services’ > ‘Credentials’ to generate the API key.

3. Setting Up the Android Project

Once the API key is ready, set up the Android project. Open Android Studio and create a new project.
Here, we will select ‘Empty Activity’.

3.1. Modifying the Gradle File

Open the `build.gradle` file and add the following dependency:


    dependencies {
        implementation 'com.google.android.gms:play-services-maps:17.0.1' // Google Maps dependency
    }
    

3.2. Modifying AndroidManifest.xml

Add the permissions and API key in the `AndroidManifest.xml` file as follows:


    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.mymapapp">

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

        <application
            ...
            android:meta-data
                android:name="com.google.android.geo.API_KEY"
                android:value="YOUR_API_KEY"/>
        </application>
    </manifest>
    

4. Implementing the Map Display

Now we will display the map on the screen. Modify the `activity_main.xml` file to add a map fragment.


    <LinearLayout 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"
        android:orientation="vertical"
        tools:context=".MainActivity">

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

    </LinearLayout>
    

4.1. Implementing MainActivity.java

Modify the `MainActivity.java` file as follows to control the map.


    package com.example.mymapapp;

    import android.os.Bundle;
    import androidx.fragment.app.FragmentActivity;
    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 MainActivity extends FragmentActivity implements OnMapReadyCallback {

        private GoogleMap mMap;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;

            // Example Location: Seoul
            LatLng seoul = new LatLng(37.5665, 126.978);
            mMap.addMarker(new MarkerOptions().position(seoul).title("Marker in Seoul"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(seoul));
        }
    }
    

5. Adding Markers

We will implement the function to add markers so that users can easily find various places. Although we have already added one marker in the example code, I will show you how to add multiple markers.


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Seoul Marker
        LatLng seoul = new LatLng(37.5665, 126.978);
        mMap.addMarker(new MarkerOptions().position(seoul).title("Marker in Seoul"));

        // Busan Marker
        LatLng busan = new LatLng(35.1796, 129.0756);
        mMap.addMarker(new MarkerOptions().position(busan).title("Marker in Busan"));

        // Daegu Marker
        LatLng daegu = new LatLng(35.8714, 128.6014);
        mMap.addMarker(new MarkerOptions().position(daegu).title("Marker in Daegu"));

        // Change camera position
        mMap.moveCamera(CameraUpdateFactory.newLatLng(seoul));
    }
    

6. Requesting Location Access Permission

When implementing location-based services, it is necessary to request location access permission from the user. Here’s how to request location permission.


    import android.Manifest;
    import android.content.pm.PackageManager;
    import androidx.core.app.ActivityCompat;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // Request location permission
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            mMap.setMyLocationEnabled(true);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mMap.setMyLocationEnabled(true);
                }
            }
        }
    }
    

7. Displaying Current Location

Let’s implement how to display the user’s current location on the map. With the code just added, you can display the current location using the .setMyLocationEnabled(true) method. To move the camera to the current location, modify it as follows.


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Display current location based on user's permission
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        }

        // Seoul Marker
        LatLng seoul = new LatLng(37.5665, 126.978);
        mMap.addMarker(new MarkerOptions().position(seoul).title("Marker in Seoul"));
        
        // Change camera position
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(seoul, 10));
    }
    

8. Implementing Route Finding Functionality

The route finding function is used to find the path between the user and a specific destination. You can use the Google Directions API
to find routes, but additional work is required for this.

To call the Directions API, you can use an HTTP client such as Axios or Retrofit to send requests and analyze the returned route data
to display it on the map’s Polyline. This part will be briefly explained.


    // Calling Directions API using Retrofit
    public interface DirectionsService {
        @GET("directions/json")
        Call getDirections(@Query("origin") String origin,
                                          @Query("destination") String destination,
                                          @Query("key") String apiKey);
    }
    

Using the route data obtained from this API, you can add the Polyline to the map to display the route.

9. Conclusion

In this article, we explored the basic setup and functionality for utilizing Google Maps in Android app development.
By leveraging the Google Maps API, you can create powerful applications that provide various location-based services.
I recommend adding user-friendly features and implementing complex route finding functionality using the Directions API.

The path of app development is not easy, but the possibilities of providing a rich user experience using Google Maps are endless.
I hope this helps you bring your ideas to life.

© 2023 Blog Ideas