Android Google Map
Android provides facility to integrate Google map in our application by using Maps SDK for Android API.
With the Maps SDK for Android, you can add maps based on Google Maps data to your application. The API automatically handles access to Google Maps servers, data downloading, map display, and response to map gestures. You can also use API calls to add markers, polygons, and overlays to a basic map, and to change the user’s view of a particular map area. These objects provide additional information for map locations, and allow user interaction with the map. The API allows you to add these graphics to a map:
- Icons indicate a single location on the map (Markers).
- Sets of line segments (Polylines).
- Enclosed segments (Polygons).
- Bitmap graphics that are tied to specific positions on the map (Ground Overlays).
- Sets of images which are displayed on top of the base map tiles (Tile Overlays).
This article aims to give knowledge about how to implement Google Maps into your applications and also covered some basic topics.
Let’s start creating an example of Google map integration within our app.
Creating New Project
1. Start Android Studio.
2. Create a new project as follows:
- If you see the Welcome to Android Studio dialog, choose Start a new Android Studio project, available under ‘Quick Start’ on the right of the dialog.
- Otherwise, click File in the Android Studio menu bar, then New, New Project.
3. In the Choose your project dialog, select the tab that corresponds to the platform you intended to develop for. Most users will want to keep the default Phone and Tablet.
4. Select Google Maps Activity, then click Next.
5. Enter your app name, package name, and project location, programming language (Java or Kotlin), and the minimum Android API level supported by your app, then click Finish.
6. Copy the URL from google_map_api.xml file to generate Google map API key.
7. Paste the copied URL at the browser. It will open the following page.
8. Click on Create API key to generate API key.
9. After clicking on Create API key, it will generate an API key displaying the following screen.
10. Copy this generated API key and paste it in your google_map_api.xml file
11. Open build.gradle.Here you can see a new library to integrate google Maps gets added.
build.gradle
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0' //Google Map implementation 'com.google.android.gms:play-services-maps:17.0.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' }
12. Open AndroidManifest.xml file and add the below user-permissions as shown below.
INTERNET – To check internet connection status
ACCESS_COARSE_LOCATION – To determine user’s location using WiFi and mobile cell data
ACCESS_FINE_LOCATION – To determine user’s location using GPS, WiFi and mobile cell data
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.googlemapdemo"> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MapsActivity" android:label="@string/title_activity_maps"> <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.geo.API_KEY" android:value="@string/google_maps_key" /> </application> </manifest>
13. Google maps are implemented using SupportMapFragment which is a subclass of Fragment class. By default, the XML file that defines the app’s layout is at res/layout/activity_maps.xml. It contains the following code:
activity_maps.xml
<?xml version="1.0" encoding="utf-8"?> <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=".MapsActivity" />
14. To get the GoogleMap object in our MapsActivity.java class we need to implement the OnMapReadyCallback interface and override the onMapReady() callback method.
MapsActivity.java
package com.example.googlemapdemo; import android.os.Bundle; 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.MarkerOptions; import androidx.fragment.app.FragmentActivity; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @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); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } }
When you run your app it will look like this as shown below:
Changing Map Type
Google provides 4 kinds of map types Normal, Hybrid, Satellite and Terrain. You can toggle to any kind of map using googleMap.setMapType() method.
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
NORMAL HYBRID
SATELLITE TERRAIN
Placing a Marker
You can place a marker on the map by using the following code.
// latitude and longitude double latitude = ; double longitude = ; // create marker MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps "); // adding marker googleMap.addMarker(marker);
Output
Changing Marker Color
By default map marker color will be RED. Google maps provides some set of predefined colored icons for the marker.
// ROSE color icon marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)); // GREEN color icon marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
You can set the following predefined colored icons for the marker:
HUE_AZURE HUE_BLUE
HUE_CYAN HUE_GREEN
HUE_MAGENTA HUE_ORANGE
HUE_RED HUE_ROSE
HUE_VIOLET HUE_YELLOW
Custom Marker Icon
Apart from maps native marker icons, you can use own image to show as a marker. You can load the icon from any kind of supported sources.
fromAsset(String assetName) – Loading from assets folder
fromBitmap (Bitmap image) – Loading bitmap image
fromFile (String path) – Loading from file
fromResource (int resourceId) – Loading from drawable resource
Below I loaded a custom marker icon from drawable folder
// latitude and longitude double latitude = 12.9716; double longitude = 77.5946; // create marker MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps"); // Changing marker icon marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_marker_icon))); // adding marker googleMap.addMarker(marker);
UI controls
The Maps API offers built-in UI controls that are similar to those found in the Google Maps application on your Android phone. You can toggle the visibility of these controls using the UiSettings class which can be obtained from a GoogleMap with the GoogleMap.getUiSettings method.
Zoom Controls
You can call setZoomControlsEnabled() function to enable zooming controls on the map. By disabling these buttons map zooming functionality still work by pinching gesture. These are disabled by default but can be enabled by calling setZoomControlsEnabled() method
googleMap.getUiSettings().setZoomControlsEnabled(true);
Compass
The compass will only ever appear when the camera is oriented such that it has a non-zero bearing or non-zero tilt. When the user clicks on the compass, the camera animates back to a position with bearing and tilt of zero (the default orientation) and the compass fades away shortly afterwards. You can disable the compass appearing altogether by calling setCompassEnabled() function
googleMap.getUiSettings().setCompassEnabled(false);
My Location Button
My location button will be used to move map to your current location. This button can be shown / hidden by calling setMyLocationButtonEnabled() function
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
Level Picker
The indoor map is normally shown with a level picker, which shows different maps for different floors. By default, a level picker (floor picker) appears near the center right-hand edge of the screen when the user is viewing an indoor map. You can disable or enable the level picker control by calling setIndoorLevelPickerEnabled()
googleMap.getUiSettings().setIndoorLevelPickerEnabled(true);
Map Gesture
A map created with the Maps SDK for Android supports the same gestures as the Google Maps application. However, there might be situations where you want to disable certain gestures in order to preserve the state of the map.
Zoom Gesture
A user can change the zoom level of the camera(ie. zoom in, zoom out). If enabled, users can either double tap/two-finger tap or pinch to zoom the camera. If disabled, these gestures have no effect. This setting doesn’t affect the zoom buttons. You can disable zoom gestures by calling setZoomGesturesEnabled(boolean) method
googleMap.getUiSettings().setZoomGesturesEnabled(false);
Scroll Gesture
A user can scroll (pan) around the map by dragging the map with their finger. You can disable scrolling by calling setScrollGesturesEnabled(boolean) method
googleMap.getUiSettings().setScrollGesturesEnabled(false);
Tilt Gesture
A user can tilt the map by placing two fingers on the map and moving them down or up together to increase or decrease the tilt angle respectively. You can disable tilt gestures by calling setTiltGesturesEnabled(boolean) method
googleMap.getUiSettings().setTiltGesturesEnabled(false);
Rotate Gesture
A user can rotate the map by placing two fingers on the map and applying a rotate motion. You can disable rotation by calling setRotateGesturesEnabled(boolean) method
googleMap.getUiSettings().setRotateGesturesEnabled(false);
Moving Camera to a Location with animation
You may want to move the camera to a particular position. Google maps provide a set of functions to achieve this.
CameraPosition cameraPosition = new CameraPosition.Builder().target( new LatLng(12.9716, 77.5946)).zoom(12).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Although google maps provides a lot of other features, I covered only basic topics in this tutorial. Remaining topics seem to be pretty much lengthy, so I’ll post them as separate articles.
So helpful, can know ur contact details, so can I contact you
Thanks, This is my contact number +91 9980285683