In this Android Google Maps API Tutorial, we will create a simple map to save our favourite places in SQLite Database. So basically in this tutorial we will be creating an Android Location Manager to store our favorite places on map.
So lets begin our Android Google Maps Tutorial.
To use Google Maps we need Google Maps Android API. Now don’t worry about getting an API is very easy. First lets create our android project for this Android Google Maps Tutorial.
Android Google Maps Tutorial
- Open android studio and create a new Android Project.
- I named it GoogleMaps. Remember this time we will select Google Maps Activity from the predefined templates. (This will simplify the process of adding google map)
- Now click next -> and finish.
- You will see the below screen when your android google maps tutorial project is fully loaded.
- See the highlighted text it is a link. Copy this and paste it to your browser (Make sure you are logged in your google account). You will see this.
- Click on continue.
- Now click on Go to credentials.
- Now click on Create and you will get Your API Key.
- Now copy the API Key to your String inside google_maps_api.xml file. (From where you copied the link to create the api).
- Now run your application and you will that the app Start Google Maps (See the screenshot of my output).
- For this android google maps tutorial app we will create some buttons at the bottom of the map. For buttons I have used images, you can get the images from below. Paste the images inside your drawable folder.
- Now come inside activity_maps.xml and write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<FrameLayout 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=".MapsActivity"> <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:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="net.simplifiedcoding.mymapapp.MapsActivity" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="bottom" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#cc3b60a7" android:orientation="horizontal"> <ImageButton android:id="@+id/buttonCurrent" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:background="@drawable/current" /> <ImageButton android:id="@+id/buttonSave" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:background="@drawable/save" /> <ImageButton android:id="@+id/buttonView" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="15dp" android:background="@drawable/view" /> </LinearLayout> </LinearLayout> </FrameLayout> |
- This code would produce the following layout. This is the main layout of this android google maps tutorial. You can change the look if you want.
- We have created three buttons first one would be used to move to the current location, second will save a given location and the last one will be used for viewing the saved locations.
- Come inside MapsActivity.java.Â
- First we will implement the following interfaces.
1 2 3 4 5 6 7 8 9 |
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, View.OnClickListener{ |
- Now you will be seeing red lines, because we didn’t yet implemented the methods of the interfaces. So just put your cursor over red line and press alt+enter and click on implement methods (as shown in image).
- Now click ok and all the methods will be implemented.
- Now inside the class declare the following variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, View.OnClickListener{ //Our Map private GoogleMap mMap; //To store longitude and latitude from map private double longitude; private double latitude; //Buttons private ImageButton buttonSave; private ImageButton buttonCurrent; private ImageButton buttonView; //Google ApiClient private GoogleApiClient googleApiClient; |
- Now write the following inside onCreate().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); //Initializing googleapi client googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); //Initializing views and adding onclick listeners buttonSave = (ImageButton) findViewById(R.id.buttonSave); buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent); buttonView = (ImageButton) findViewById(R.id.buttonView); buttonSave.setOnClickListener(this); buttonCurrent.setOnClickListener(this); buttonView.setOnClickListener(this); } |
- We need to override onStart() and onStop() to connect and disconnect to our Google Api Client. Write the following code to do this.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Override protected void onStart() { googleApiClient.connect(); super.onStart(); } @Override protected void onStop() { googleApiClient.disconnect(); super.onStop(); } |
- We will initialize our Map inside the overriden method onMapReady().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Override public void onMapReady(GoogleMap googleMap) { //Initializing our map mMap = googleMap; //Creating a random coordinate LatLng latLng = new LatLng(-34, 151); //Adding marker to that coordinate mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); //Setting onMarkerDragListener to track the marker drag mMap.setOnMarkerDragListener(this); //Adding a long click listener to the map mMap.setOnMapLongClickListener(this); } |
- Now we will create two more methods one to get the current location getCurrentLocation()Â and other to move the map camera moveMap()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
//Getting current location private void getCurrentLocation() { //Creating a location object Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (location != null) { //Getting longitude and latitude longitude = location.getLongitude(); latitude = location.getLatitude(); //moving the map to location moveMap(); } } //Function to move the map private void moveMap() { //String to display current latitude and longitude String msg = latitude + ", "+longitude; //Creating a LatLng Object to store Coordinates LatLng latLng = new LatLng(latitude, longitude); //Adding marker to map mMap.addMarker(new MarkerOptions() .position(latLng) //setting position .draggable(true) //Making the marker draggable .title("Current Location")); //Adding a title //Moving the camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); //Animating the camera mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); //Displaying current coordinates in toast Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } |
- Come inside onConnected() method. This is also an overriden method, here we will call the getCurrentLocation() method.
1 2 3 4 5 6 |
@Override public void onConnected(Bundle bundle) { getCurrentLocation(); } |
- When user will tap on the map for a long time we will add a marker at that position. We will also remove the previous marker. So come inside overriden method onMapLongClick().
1 2 3 4 5 6 7 8 9 10 11 12 |
@Override public void onMapLongClick(LatLng latLng) { //Clearing all the markers mMap.clear(); //Adding a new marker to the current pressed position we are also making the draggable true mMap.addMarker(new MarkerOptions() .position(latLng) .draggable(true)); } |
- To get the coordinates after the drag we will use the overriden method onMarkerDragEnd(). Write the following code inside onMarkerDragEnd().
1 2 3 4 5 6 7 8 9 10 11 |
@Override public void onMarkerDragEnd(Marker marker) { //Getting the coordinates latitude = marker.getPosition().latitude; longitude = marker.getPosition().longitude; //Moving the map moveMap(); } |
- Inside the onClick() method we will perform the button clicks. Write the following code inside onClick().
1 2 3 4 5 6 7 8 9 |
@Override public void onClick(View v) { if(v == buttonCurrent){ getCurrentLocation(); moveMap(); } } |
- So far the full code we just created is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
package net.simplifiedcoding.googlemaps; import android.location.Location; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; 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.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, View.OnClickListener{ //Our Map private GoogleMap mMap; //To store longitude and latitude from map private double longitude; private double latitude; //Buttons private ImageButton buttonSave; private ImageButton buttonCurrent; private ImageButton buttonView; //Google ApiClient private GoogleApiClient googleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); //Initializing googleapi client googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); //Initializing views and adding onclick listeners buttonSave = (ImageButton) findViewById(R.id.buttonSave); buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent); buttonView = (ImageButton) findViewById(R.id.buttonView); buttonSave.setOnClickListener(this); buttonCurrent.setOnClickListener(this); buttonView.setOnClickListener(this); } @Override protected void onStart() { googleApiClient.connect(); super.onStart(); } @Override protected void onStop() { googleApiClient.disconnect(); super.onStop(); } //Getting current location private void getCurrentLocation() { mMap.clear(); //Creating a location object Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (location != null) { //Getting longitude and latitude longitude = location.getLongitude(); latitude = location.getLatitude(); //moving the map to location moveMap(); } } //Function to move the map private void moveMap() { //String to display current latitude and longitude String msg = latitude + ", "+longitude; //Creating a LatLng Object to store Coordinates LatLng latLng = new LatLng(latitude, longitude); //Adding marker to map mMap.addMarker(new MarkerOptions() .position(latLng) //setting position .draggable(true) //Making the marker draggable .title("Current Location")); //Adding a title //Moving the camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); //Animating the camera mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); //Displaying current coordinates in toast Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng latLng = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.setOnMarkerDragListener(this); mMap.setOnMapLongClickListener(this); } @Override public void onConnected(Bundle bundle) { getCurrentLocation(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } @Override public void onMapLongClick(LatLng latLng) { //Clearing all the markers mMap.clear(); //Adding a new marker to the current pressed position mMap.addMarker(new MarkerOptions() .position(latLng) .draggable(true)); } @Override public void onMarkerDragStart(Marker marker) { } @Override public void onMarkerDrag(Marker marker) { } @Override public void onMarkerDragEnd(Marker marker) { //Getting the coordinates latitude = marker.getPosition().latitude; longitude = marker.getPosition().longitude; //Moving the map moveMap(); } @Override public void onClick(View v) { if(v == buttonCurrent){ getCurrentLocation(); moveMap(); } } } |
- We will also need the following permission to be added in our manifest.
1 2 3 4 5 |
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> |
- Now lets run this Android Google Maps Tutorial App. You will see the following output.
- If we will tap the first button (Only this button is working now). We will move the the current location.
- Bingo! Our Android Google Maps Tutorial  is working fine. Though we have to code a bit more to fully complete our Android Locator.
- To drag the marker just long click over the marker and move your thumb to drag it. When you will press the first button it will again come to the current location. You can get my source code from my GitHub Repository from the link given below.
Get This Android Google Maps Tutorial Source from GitHub
[sociallocker id=1372]Android Google Maps Tutorial[/sociallocker]
[wp_ad_camp_1]
This Android Google Maps Tutorial is little long that is why I am breaking this part here in the next part we will add the functionality to remaining two button which is save and view.
So wait for the next part of Android Google Maps Tutorial or you can try completing it yourself. In the next part of our Android Google Maps Tutorial we will complete this app. Thank You 🙂