Integrating Google Maps in Android Applications

548
SHARES
2.5k
VIEWS

In the previous lecture, we’ve discussed the basic types of google maps and in today’s tutorial, we will learn how we can integrate the google map in our android apps. Before you start, make sure you have registered your application in the Google Developer Console and obtained the API key for it. Then, set up Google Play services and define the API Key in manifest. Now, let’s see how we can implement different types of maps in our android applications.

Open Android Studio and create a new project. Let’s see the code needed for a layout file. We can use MapFragment class to load map in our layout. In activity_maps.xml:

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

Implementing Map in Android

The first step is to initialize a GoogleMap object. Then, we should call the setMapType() method on the GoogleMap object, which takes the same type of the map as an argument. Now, let’s see the code for our activity:

package com.codemeals.googlemapapp;

import android.app.Activity;
import android.os.Bundle;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;

public class MapsActivity extends Activity implements OnMapReadyCallback {

    MapFragment mapFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        mapFragment = ((MapFragment)   getFragmentManager().findFragmentById(R.id.map));
        mapFragment.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap map) {
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }
}

In the above code the MAP_TYPE_NORMAL constant loads the normal map. Now, if you run the application on your device, you should see a normal Google map in your device:

To change the map type , you just need to change one line of code:

// Below we are changing the map type to Terrain

map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

// Other available types are

map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

If you want to display nothing, Use the constant MAP_TYPE_NONE and it will render an empty grid for you, thus creating a custom application.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending