Android Google Maps API Tutorial to implement map

This tutorial explains how to implement autocomplete search box to find Google Places and place them on Google Map View in Android Application.

 

Introduction

Google Maps is a web-based service developed by Google. It provides detailed information about geographical regions and sites around the world.

In this tutorial, we will implement autocomplete search box to find Google Places using Google Places API and display place on Google Map Using Google Map API. I have explained how to implement autocomplete search box to find Google Places using Google Places API. Please refer Android Google Places API Tutorial to Search Google Places.

Next, we will implement Google Map and display the searched place on Google Map




Enable Google Map API

First, we need to integrate Google Places API with an android application then enable Google Map API. To integrate Google Places API, please follow Search Google Places using Google Places API in Android Tutorial

Now, we will enable Google Map API to integrate Google Map with an android application. To enable Google Map API, follow these step:

  1. Login to your Google Developer account.

  2. Go to Google Developer Console

     

    dashboard Google Map
  3.  

  4. Click on the My Project then a drop down list will be open then click on the Manage all projects and click on your project.

     

    dashboard google

    myproject

    select project
  5.  

  6. Click on the enable and manage APIs option.

     

    enable google map api
  7.  

  8. Now, click on the Google Maps Android API

  9.  

    enable google map api

     

  10. Click on the enable button to enable Google Map API. Now, you enabled Google Map API.

     

    click enable button

 

Create Intent Object

We have received component of searched place in onActivityResult() method of the MainActivity.java file. Now, create an Intent object in onActivityResult() to start another activity with component of the searched place. Now, here is final MainActivity.java file:

 


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void findPlace(View view) {
        try {
            Intent intent =
                    new PlaceAutocomplete
                         .IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                         .build(this);
            startActivityForResult(intent, 1);

        } catch (GooglePlayServicesRepairableException e) {
            // TODO: Handle the error.
        } catch (GooglePlayServicesNotAvailableException e) {
            // TODO: Handle the error.
        }
    }

    // A place has been received; use requestCode to track the request.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, 
      Intent data) {
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this, data);
                Log.e("Tag", "Place: "
                          + place.getAddress() 
                          + place.getPhoneNumber() 
                          + place.getLatLng().latitude);

                Intent intent = new Intent(MainActivity.this, 
                                            GoogleMapActivity.class);
                intent.putExtra("latitude",place.getLatLng().latitude);
                intent.putExtra("longitute",place.getLatLng().longitude);
                intent.putExtra("name",place.getName());
                intent.putExtra("address",place.getAddress());
                startActivity(intent);

            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                // TODO: Handle the error.
                Log.e("Tag", status.getStatusMessage());

            } else if (resultCode == RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
    }
}

 

Create a New Activity

We will create a new Activity called GoogleMapActivity. In this Activity, we will display searched place on Map.

 

Add Fragment

Add a fragment element to the activity_google_map.xml file to define a Fragment object. In this element, set the android:name attribute to “com.google.android.gms.maps.MapFragment”. This automatically attaches a MapFragment to the activity.

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

 

Get the Intent

We retrieve the component of search place by using getIntent(). Use the following code in GoogleMapActivity.java file:
 

public class GoogleMapActivity extends AppCompatActivity {
    String title, address;
    double latitude,longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_map);

        Intent intent = getIntent();
        latitude = intent.getDoubleExtra("latitude", 0d);
        longitude = intent.getDoubleExtra("longitute",0d);
        title = intent.getStringExtra("name");
        address = intent.getStringExtra("address");
    }
}

 

Implement OnMapReadyCallback

To display map inside an application, we need to implement the OnMapReadyCallback interface and set an instance of the callback on a SupportMapFragment object, because that’s the most common way of adding a map to an app.

 

public class GoogleMapActivity extends AppCompatActivity
  implements OnMapReadyCallback {

    String title, address;
    double latitude,longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_map);

        Intent intent = getIntent();
        latitude = intent.getDoubleExtra("latitude", 0d);
        longitude = intent.getDoubleExtra("longitute",0d);
        title = intent.getStringExtra("name");
        address = intent.getStringExtra("address");
    }
}

 

Handle Fragment

Get a handle to the fragment by calling getSupportFragmentManager().findFragmentById(), passing it the resource ID of element. The resource ID R.id.map is added automatically to the Android project when build the layout file.

To set the callback on the fragment, use getMapAsync() method.
 

public class GoogleMapActivity extends AppCompatActivity 
                                   implements OnMapReadyCallback {
    String title, address;
    double latitude,longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_map);

        Intent intent = getIntent();
        latitude = intent.getDoubleExtra("latitude", 0d);
        longitude = intent.getDoubleExtra("longitute",0d);
        title = intent.getStringExtra("name");
        address = intent.getStringExtra("address");

        SupportMapFragment mapFragment = (SupportMapFragment)
                                              getSupportFragmentManager()
                                              .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
}

 

Handle Google Map

We will handle the Google Map by using onMapReady(GoogleMap) callback method. When map is ready to be use this callback method triggered. We can use GoogleMap object to set the view options for the map or add a marker.
 

public class GoogleMapActivity extends AppCompatActivity 
                                   implements OnMapReadyCallback {
    String title, address;
    double latitude,longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_map);

        Intent intent = getIntent();
        latitude = intent.getDoubleExtra("latitude", 0d);
        longitude = intent.getDoubleExtra("longitute",0d);
        title = intent.getStringExtra("name");
        address = intent.getStringExtra("address");

        SupportMapFragment mapFragment = (SupportMapFragment)
                                              getSupportFragmentManager()
                                              .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    
    public void onMapReady(GoogleMap map){

        LatLng latlng = new LatLng(latitude,longitude);
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 13));
        map.addMarker( new MarkerOptions()
                .title(title)
                .snippet(address)
                .position(sydney));
    }
}

 

search button

google search

search address

google maps

 
  



The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com