How to Integrate Google Maps Android

Google Maps app Android

0 535

Google provides developers API or SDK, that allows us to add Google Maps in Android. It allows you to show any of the locations on the map or even it helps you to generate different routes. Here is a step by steps guide on how to integrate google maps android

Step 1

The first and most important step is to activate the Google Maps API from Google Developer Console. If you don’t have the API key you won’t be able to display the Maps into your APP. To do this go to this URL (https://console.developers.google.com/project). You will see the following Screen below and list of projects that you have created before on your Google Developer Console. If there are no projects you go and create one by clicking on Create Project Button and giving a project Name.

When the project is created you are automatically redirected to Project Home Screen.

 

 

Now Click on the Menu Button to open the API Manager.

Once you are into API Manager you will see the following screen. This screen contains all of the available API’s the Google Provides you. For now, just Find the Google Maps SDK for Android and click on it.

On the next screen, you can now see more details about this API and there is a Blue button named Enable, click on that button to enable this API for further use

Once you enable the API it will ask you to generate the Credentials. The credential is basically the API Key that you will be using in your APP to display the Google Maps. To generate your Credentials click on Credentials button in the left menu.

Here you can now generate your API key. To Generate the API Key you will need following things

  • SHA-1 Fingerprints of Android Studio / Eclipse whatever IDE you are using. (Note: Every IDE has it’s on SHA-1)
  • Package Name of your Application.

To generate the SHA-1 Fingerprints for Android Studio is quite simple.  Just create a New Google Maps Activity and get your SHA1. Please note that the Activity you just created is for getting the SHA-1 Finger Prints we will not be using this activity anywhere so you can also safely delete it.

Once your activity is created you to res/values/ you will find google_maps_api.xml file over here. Open this file. You can see in the files your SHA-1 Fingerprint along with your package name. Just copy this whole line.

Now come back to your Google Developer Console and create the new Credentials and select API Key.

Now you will be asked for the 4 options

  • Server key
  • Browser key
  • Android key
  • iOS key

You have to select the android key and just paste in the line that you copied from Android Studio (google_maps_api.xml file) as described in the image below.

 

The red part is SHA-1 fingerprint past it in the SHA-1 Section. The blue part is your package name paste it in the package name section and click on the create button. Once you click on the Create button it will take something like 5 – 6 seconds to generate your API key.

Copy this API key to your google_maps_api.xml file in Android Studio.

You are all done with Step 1. This was the main step for using Google Maps into your Application. Next, let us start off by creating the Layout for the Map in the XML file

Step 2:

Implementing the Maps in Android Studio. Go to your MainActivity XML file. As in step 1 we created a google maps activity for now just put the activity aside or you and delete it from your project as well. Write up the following code in your XML file.

 

 <fragment

android:id="@+id/map"

android:name="com.google.android.gms.maps.MapFragment"

android:layout_width="fill_parent"

android:layout_height="match_parent"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" /> 

 

This code is basically being used to display the Map. Now go to your java file and let us start implementing Google Maps to use.

 

 private GoogleMap googleMap; //google maps object

boolean isZoom = false; // a boolen varibale to check the zoom level of google maps

private LocationManager locationManager; // a locaiton manager object to display the current location on the map 

 

Create a new method called initMaps (or you can name it as you want) and add up the following code in it.

 

 private void initilizeMap() {

try {

if (googleMap == null) {

googleMap = ((MapFragment) getFragmentManager()

.findFragmentById(R.id.map)).getMap();

// check if map is created successfully or not

googleMap.setOnMapLongClickListener(this); // if you tap on map for 3 seconds you can perform a certain event for the map such as getting latitude longitude

// location name or anything that is related to place you tap on

googleMap.setMyLocationEnabled(true); //this lines gets your current location

googleMap.getUiSettings().setMyLocationButtonEnabled(true); //this will enable the find current location button on the map

googleMap.setOnMarkerDragListener(this); // in case you want to enable the drag evetns for the markers on the google maps

googleMap.setOnMarkerClickListener(this); // this event is being used to set the click events for the marker

if (googleMap == null) {

Toast.makeText(getApplicationContext(),

"Sorry! unable to create maps", Toast.LENGTH_SHORT)

.show();

}

}

} catch (Exception e) {

e.printStackTrace();

}

} 

 

In the above code, there are a few lines which will cause errors and you won’t be able to run the application. These lines are

 

 googleMap.setOnMapLongClickListener(this); // if you tap on map for 3 seconds you can perform a certain event for the map such as getting latitude longitude

// location name or anything that is related to place you tap on

googleMap.setMyLocationEnabled(true); //this lines gets your current location

googleMap.getUiSettings().setMyLocationButtonEnabled(true); //this will enable the find current location button on the map

googleMap.setOnMarkerDragListener(this); // in case you want to enable the drag evetns for the markers on the google maps

googleMap.setOnMarkerClickListener(this); // this event is being used to set the click events for the marker 

 

I have mentioned what these lines are being used for. if you don’t want to use these functions you can comment them out. Or if you want to just add up the following code at the top level where your class is defined,

 

 public class MainActivity extends AppCompatActivity implements GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerDragListener, GoogleMap.OnMarkerClickListener 

 

Now add up the following methods in your code to implement these functions.

 

 // long press events for the maps goes here

@Override

public void onMapLongClick(LatLng latLng) {

 

}

 

 

// if you want a drag events for the marker add thiese here

@Override

public void onMarkerDragStart(Marker marker) {

 

}

 

//during marker being drag event

@Override

public void onMarkerDrag(Marker marker) {

 

}

 

//when the marker drags end

 

@Override

public void onMarkerDragEnd(Marker marker) {

 

}

 

//market click event code be done here

@Override

public boolean onMarkerClick(Marker marker) {

return false;

} 

 

Add the following lines in your Manifest file

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

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

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

 

Currently, if we call this (initilizeMap()  or whatever you named it) method in the onCreate method of your activity and run the application you will be able to see the Maps on to your phone. But let us not end here. Let us move on and show our current location on the maps and perform some events.

To show your current location on the Map add up the following code in the onCreate method of your activity

 

 try {

 

Location location = null;

 

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

locationManager.requestLocationUpdates(

LocationManager.NETWORK_PROVIDER, 0, 0, this);

location = locationManager

.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

 

// drawCurrentLocation(location);

if (location == null) {

locationManager.requestLocationUpdates(

LocationManager.GPS_PROVIDER, 0, 0, this);

 

location = locationManager

.getLastKnownLocation(LocationManager.GPS_PROVIDER);

// drawCurrentLocation(location);

 

}

initilizeMap(); //calling your map initlizing method over here

 

if (!isZoom) {

googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(

new LatLng(location.getLatitude(), location

.getLongitude()), 15));

googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

isZoom = true;

}

} catch (Exception e) {

e.printStackTrace();

} 

 

Now if you run the application you will be able to see your current location as well on the MAP. Make sure your Location Services are enabled. If not you can add a check to your application to see whether location services are enabled or not. If they are not enabled application will prompt you to enable these services.

 

 private void checkLocationSettings()

{

LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);

if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||

!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

// Build the alert dialog

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Location Services Not Active");

builder.setMessage("Please enable Location Services and GPS");

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialogInterface, int i) {

// Show location settings when the user acknowledges the alert dialog

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

startActivity(intent);

}

});

Dialog alertDialog = builder.create();

alertDialog.setCanceledOnTouchOutside(false);

alertDialog.show();

}

} 

That’s all for this tutorial. You can download the complete code from GITHUB (https://github.com/codearraydev/GoogleMapsTutorial) and use it as you want. Please note that you would need to generate your API Key. Also please note that Maps won’t work on Android Emulator. You would need to a real device to test the Google Maps.

 

80%
Awesome
  • Design

- Advertisement -

Leave A Reply

Your email address will not be published.