Android - Google Maps Tutorial
Android allows us to integrate google maps in our application. You can show any location on the map , or can show different routes on the map e.t.c. You can also customize the map according to your choices.
Adding Google Map
Google provides this facility using google play services library which you have to download externally. After downloading, you have to integrate it with your project.In the end you have to integrate your application with google via google console. This is completely discussed in the example.
Google Map - Activity file
Google provides GoogleMap and MapFragment api to integrate map in your android application. In order to use GoogleMap , you have to create an object of GoogleMap and get the reference of map from the xml layout file.Its syntax is given below −
GoogleMap googleMap; googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
Google Map - Layout file
Now you have to add the map fragment into xml layout file. Its syntax is given below −
<fragment android:id="@+id/map" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/>
Google Map - AndroidManifest file
The next thing you need to do is to add some permissions along with the Google Map API key in the AndroidManifest.XML file. Its syntax is given below −
<!--Permissions--> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!--Google MAP API key--> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />
Customizing Google Map
You can easily customize google map from its default view , and change it according to your demand.
Adding Marker
You can place a maker with some text over it displaying your location on the map. It can be done by via addMarker() method. Its syntax is given below −
final LatLng TutorialsPoint = new LatLng(21 , 57); Marker TP = googleMap.addMarker(new MarkerOptions().position(TutorialsPoint).title("TutorialsPoint"));
Channing Map Type
You can also change the type of the MAP. There are four different types of map and each give different view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as below
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
Enable/Disable zoom
You can also enable or disable the zoom gestures in the map by calling thesetZoomControlsEnabled(boolean) method. Its syntax is given below −
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Apart from these customization, there are other methods available in the GoogleMap class , that helps you more customize the map. They are listed below −
Sr.No | Method & description |
---|---|
1 | addCircle(CircleOptions options)
This method add a circle to the map
|
2 | addPolygon(PolygonOptions options)
This method add a polygon to the map
|
3 | addTileOverlay(TileOverlayOptions options)
This method add tile overlay to the map
|
4 | animateCamera(CameraUpdate update)
This method Moves the map according to the update with an animation
|
5 | clear()
This method removes everything from the map.
|
6 | getMyLocation()
This method returns the currently displayed user location.
|
7 | moveCamera(CameraUpdate update)
This method repositions the camera according to the instructions defined in the update
|
8 | setTrafficEnabled(boolean enabled)
This method Toggles the traffic layer on or off.
|
9 | snapshot(GoogleMap.SnapshotReadyCallback callback)
This method Takes a snapshot of the map
|
10 | stopAnimation()
This method stops the camera animation if there is one in progress
|
Example
Here is an example demonstrating the use of GoogleMap class. It creates a basic M application that allows you to navigate through the map.
To experiment with this example , you can run this on an actual device or in an emulator.
Steps | Description |
---|---|
1 | Integrate google maps in your application. |
2 | You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs. |
3 | Modify src/MainActivity.java file to add necessary code. |
4 | Modify the res/layout/activity_main to add respective XML components |
5 | Modify AndroidManifest.xml to add necessary internet permission |
6 | Run the application and choose a running android device and install the application on it and verify the results |
Integrating Google Maps
Integrating google maps in your application basically consists of these 4 steps.
- Download and configure. Google Play Services SDK
- Obtain API key from google console
- Specify Android Manifest settings
Download and configure. Google Play Services SDK
Install Google services SDK
Right click on your application, you would get open module setting by clicking an option, the project structure window appears shortly, need to select dependencies tab. over there, you would get a symbol as "+". in that you need to select library dependencies. you need to add google services in that window
Import SDK to eclipse
After you download the SDK , click on file tab and select import option. Select existing android application code and press ok. Browse to your android folder and then sdk folder. In sdk folder expand extras folder. Expand google folder and select google play services.
Configure your project with SDK
After you import the SDK , you have to add it into your project. For this , right click on your eclipse project and select properties. Select android from left tab and then select add from right below panel and add the project. It would be like this
Obtaining the API key
This part is further divided into two steps. First you have to get an SHA1 fingerprint key from your pc and then you have to get map API key from google console.
Getting Certificate from KeyTool
You need to get a certificate key because you have to provide it to google console in order to get your API key for map.
Open your command prompt and move to the path where your java jre has been placed. Now type this command.
keytool -list -v -alias androiddebugkey -keystore %%Your path%% -storepass android -keypass android
Replace the percentage part of the command with the path which you will copy from by selecting the window tab and selecting the preferences tab and then selecting the build option under android from left side.
Copy the default debug keystore path and replace it in the command and hit enter. The following result would appear.
Copy the SHA1 key because you need it in the next step.
Getting key from Google Console
Open Google Console and sign in by clicking a new project.
Click on services from the left tab and then navigate to the Google Maps Android API v2. You have to turn them on like this
Now again go to the left tab and select API access. And click on create new android key. Now paste the key that you copied and put a semicolon and paste your project name and click create. It would be like this.
Now copy the API key that has been given to your by android , because you have to paste it into your manifest file.
Specify Android Manifest settings
The final step is to add the API key to your application. Open your manifest file and place this code right before closing the application tag.
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="API_KEY"/>
In the second line replace API_KEY with your api key and you are done. You need to add some permissions in your manifest too which are given below in the manifest file.
Adding Google Maps to your application.
Following is the content of the modified main activity filesrc/com.example.googlemaps/MainActivity.java.
package com.example.googlemaps; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import android.os.Bundle; import android.app.Activity; import android.widget.Toast; public class MainActivity extends Activity { static final LatLng TutorialsPoint = new LatLng(21 , 57); private GoogleMap googleMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { if (googleMap == null) { googleMap = ((MapFragment) getFragmentManager(). findFragmentById(R.id.map)).getMap(); } googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); Marker TP = googleMap.addMarker(new MarkerOptions(). position(TutorialsPoint).title("TutorialsPoint")); } catch (Exception e) { e.printStackTrace(); } } }
Following is the modified content of the xml res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.googlemaps" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="com.example.googlemaps.permission.MAPS_RECEIVE" /> <uses-sdk android:minSdkVersion="12" android:targetSdkVersion="17" /> <permission android:name="com.example.googlemaps.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.google.android.providers. gsf.permission. READ_GSERVICES" /> <uses-permission android:name="android.permission. WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.googlemaps.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" /> </application> </manifest>
Let's try to run your GoogleMaps application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.
Now what you need to do is to tap on the balloon to see the text.
Now you can customize the google map according to your choice with the functions given in the GoogleMap API.
Comments
Post a Comment