0% found this document useful (0 votes)
4 views

Sms

Chapter 10 discusses integrating Google Maps into Android applications, covering steps such as obtaining an API key, adding dependencies, and configuring layout elements. It outlines various types of map implementations, methods for interacting with maps, and how to handle user location updates. Additionally, it emphasizes the importance of permissions and provides guidance on obtaining and using location data effectively.

Uploaded by

INDHU MATHI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Sms

Chapter 10 discusses integrating Google Maps into Android applications, covering steps such as obtaining an API key, adding dependencies, and configuring layout elements. It outlines various types of map implementations, methods for interacting with maps, and how to handle user location updates. Additionally, it emphasizes the importance of permissions and provides guidance on obtaining and using location data effectively.

Uploaded by

INDHU MATHI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

CHAPTER 10: LOCATION_BASED SERVICES

DISPLAYING MAPS
Google Maps is a powerful mapping service provided by Google that offers a wide range of
features for Android developers to integrate into their applications. Here's an overview of
how you can integrate Google Maps into your Android app:

1. Obtain an API Key:

To use Google Maps in your Android app, you need to obtain an API key from the Google
Cloud Console. This key authenticates your app with the Google Maps service. Follow the
official documentation to obtain an API key: Get API Key

2. Add Google Play Services dependency:

Add the Google Play Services dependency to your app's build.gradle file:

implementation 'com.google.android.gms:play-services-maps:20.0.0'

3. Configure Google Maps in your layout XML:

Add a MapView element to your layout XML file where you want to display the map:

<com.google.android.gms.maps.MapView

android:id="@+id/map_view"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

4. Initialize Google Maps in your Activity:

In your Activity or Fragment, initialize the Google Maps instance using the API key obtained
earlier:

import com.google.android.gms.maps.MapView;

import com.google.android.gms.maps.OnMapReadyCallback;

import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.MapsInitializer;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {


private MapView mapView;

private GoogleMap googleMap;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_maps);

mapView = findViewById(R.id.map_view);

mapView.onCreate(savedInstanceState);

mapView.getMapAsync(this);

@Override

public void onMapReady(GoogleMap map) {

googleMap = map;

// You can customize the map here

@Override

public void onResume() {

super.onResume();

mapView.onResume();

}
@Override

public void onPause() {

super.onPause();

mapView.onPause();

@Override

public void onDestroy() {

super.onDestroy();

mapView.onDestroy();

@Override

public void onLowMemory() {

super.onLowMemory();

mapView.onLowMemory();

5. Customize and Interact with the Map:

Once you have the Google Map instance, you can customize it and add various features such
as markers, polygons, polylines, and more. You can also handle user interactions like tapping
on markers or dragging the map.

6. Permissions:

Ensure that your app has the necessary permissions declared in the AndroidManifest.xml
file, such as ACCESS_FINE_LOCATION for accessing the user's location.

7. Additional Features:
Explore additional features provided by the Google Maps SDK, such as Street View,
Geocoding, Places API, Directions API, and more.

TYPES OF GOOGLE MAPS


In Android mobile application development, there are primarily three types of Google Maps
implementations:

1. Basic Map Display:

This type involves displaying a basic map in your application, usually with default map tiles
provided by Google. Users can interact with the map by panning, zooming, and tapping on
it.

Use cases: Displaying points of interest, landmarks, or general geographical information


within your app.

2. Map with Markers:

In addition to displaying the map, this type involves adding markers to specific locations on
the map. Markers can represent points of interest, locations of interest, or custom data
points.

Use cases: Showing the location of nearby businesses, events, or attractions. Also commonly
used for navigation apps to display waypoints or destinations.

3. Map with Advanced Features:

This type extends beyond basic map display and marker placement to include more
advanced features such as:

 Custom markers: Use custom icons or graphics for markers.


 Info windows: Display additional information when a user taps on a marker.
 Polylines and polygons: Draw lines or shapes on the map to represent routes,
boundaries, or areas of interest.
 User location: Display the user's current location on the map, with or without
continuous updates.
 Geocoding and reverse geocoding: Convert between geographic coordinates and
human-readable addresses, and vice versa.
 Street View: Embed Street View imagery in your app to provide a 360-degree
panoramic view of locations.
 Places API: Integrate Google Places API to search for places, get place details, and
display place autocomplete suggestions.
 Directions API: Request directions between two or more locations, with options for
different travel modes (driving, walking, transit, etc.).
 Use cases: Building navigation apps, location-based services, delivery or
transportation apps, re al-time tracking, and more.

METHODS OF GOOGLE MAPS

In Android development, Google Maps functionality is primarily accessed and utilized


through methods provided by the Google Maps Android API. These methods allow
developers to interact with maps, add markers, draw shapes, obtain user location, and
more. Here are some common methods used in Google Maps Android API:

1. getMapAsync(OnMapReadyCallback callback):

This method is used to asynchronously initialize the map and set up its properties.

It takes an OnMapReadyCallback as a parameter, which is invoked when the map is


ready to be used.

mapView.getMapAsync(new OnMapReadyCallback() {

@Override

public void onMapReady(GoogleMap googleMap) {

// Map setup code

});

2. addMarker(MarkerOptions options):

This method adds a marker to the map at a specified location with the given options.
It returns a Marker object representing the added marker, which can be used to
manipulate the marker later.

Example:

MarkerOptions markerOptions = new MarkerOptions()

.position(new LatLng(latitude, longitude))

.title("Marker Title")

.snippet("Marker Snippet");
Marker marker = googleMap.addMarker(markerOptions);

3. moveCamera(CameraUpdate update):
This method moves the camera position to the specified location or zoom level on
the map.
It takes a CameraUpdate object as a parameter, which can be created using various
factory methods like newLatLng() or newLatLngZoom().

Example:

CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new


LatLng(latitude, longitude), 15);

googleMap.moveCamera(cameraUpdate);

4. setOnMarkerClickListener(GoogleMap.OnMarkerClickListener listener):

This method sets a listener to be notified when a marker on the map is clicked.

It takes a GoogleMap.OnMarkerClickListener object as a parameter, with a callback


method onMarkerClick() to handle marker click events.

Example:

googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

@Override

public boolean onMarkerClick(Marker marker) {

// Handle marker click

return true; // Return true to consume the event

});

5. setMyLocationEnabled(boolean enabled):

This method enables or disables the "My Location" layer on the map, which shows
the user's current location.

It requires the appropriate permissions and runtime permission checks for accessing
the device's location.

Example:
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {

googleMap.setMyLocationEnabled(true);

These are just a few examples of the many methods provided by the Google
Maps Android API. Depending on your application's requirements, you can use these
methods and more to create rich and interactive map experiences for your users.

STEPS FOR GETTING THE GOOGLE MAPS API KEY


The steps for obtaining a Google Maps API key for mobile application development:

1. Create a Google Cloud Platform (GCP) Account: If you don't have one already, sign up
for a Google Cloud Platform account.

2. Enable the Maps SDK for Android or iOS: Go to the Google Cloud Platform Console
and enable the Maps SDK for Android or iOS, depending on the platform you're
developing for.

3. Create a New Project: Create a new project in the Google Cloud Platform Console for
your mobile application.

4. Create an API Key: Navigate to the "APIs & Services" > "Credentials" page in the
Google Cloud Platform Console. Click on "Create credentials" and select "API key".

5. Restrict the API Key (Optional but Recommended): To enhance security, restrict your
API key by specifying which APIs it can access and from which applications. You can
set restrictions based on Android apps, iOS apps, or HTTP referrers.

6. Add the API Key to your Mobile Application: Once you have your API key, integrate it
into your mobile application code by adding it to the appropriate configuration file
(like AndroidManifest.xml for Android or Info.plist for iOS).

7. Test your Application: Test your application to ensure that the Google Maps
functionality is working correctly.
8. Monitor Usage and Billing: Keep an eye on your usage through the Google Cloud
Platform Console to ensure that you stay within any free usage limits and to monitor
any associated charges.

CALLBACKS IN GOOGLE MAPS


Callbacks in Google Maps API are functions that you can define to be executed when certain
events occur within the map. These callbacks allow you to customize the behavior of your
map application and respond to user interactions or changes in the map state. Here are
some common callbacks available in Google Maps API:

1. Event Listeners: Event listeners are used to listen for various user interactions with
the map, such as clicks, mouse movements, or changes in the map's viewport. For
example, you can use addListener() to listen for a click event on a map marker and
execute a function when the marker is clicked.
2. Map Events: Google Maps API provides several map events that you can listen to,
such as bounds_changed, center_changed, or zoom_changed. These events allow
you to detect changes in the map's state, such as when the map viewport changes or
when the user zooms in or out.
3. Marker Events: When working with markers on the map, you can define callbacks for
various marker events such as click, mouseover, or drag. These callbacks allow you to
respond to user interactions with markers, such as when a marker is clicked or
dragged.
4. Info Window Events: Info windows are used to display additional information when a
marker is clicked. You can define callbacks for info window events such as closeclick
or domready to customize the behavior of info windows.
5. Polygon, Polyline, and Circle Events: If you're working with polygons, polylines, or
circles on the map, you can define callbacks for events such as click, mouseover, or
drag. These callbacks allow you to respond to user interactions with these map
overlays.
6. Directions Service Callbacks: When using the Directions Service to display routes on
the map, you can define callbacks to handle the response returned by the service,
such as directions_changed to detect changes in the route or error to handle errors.

In Google Maps API, you can control the zoom level and rotation of the map
programmatically. Here's how you can do it:
1. Zoom Control: You can control the zoom level of the map using methods provided by
the Google Maps JavaScript API.

// Get the current zoom level

var zoomLevel = map.getZoom();

// Set the zoom level

map.setZoom(newZoomLevel);

Replace newZoomLevel with the desired zoom level you want to set.

2. Rotation Control: Google Maps JavaScript API does not directly support map
rotation, but you can achieve a similar effect by rotating the map container using CSS
or by using a third-party library.

For example, using CSS:

#map-container {

transform: rotate(45deg);

This rotates the map container by 45 degrees. However, keep in mind that rotating the map
container does not rotate the map controls or markers.

Alternatively, you can use a third-party library like Mapbox GL JS or Leaflet.js if you need
more advanced map rotation capabilities.

Remember that while you can control the zoom level and rotation of the map
programmatically, it's essential to provide a smooth and intuitive user experience. Ensure
that zooming and rotation are accessible and easy to use for your users.

THE LOCATION OBJECT


GET THE CURRENT LOCATION

To get the current location of a user in a mobile application using Google Maps API, you
typically utilize the device's GPS or location services. Here's how you can do it in Android
and iOS applications:

Android (Java/Kotlin):

You need to request permission to access the device's location and then use the Location
Services API to get the current location.
1. Request Location Permission:

Make sure to include the necessary permissions in your AndroidManifest.xml file:

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

2. Use Location Services API:

In your activity or fragment, you can use the Fused Location Provider API to
request the last known location:

// Create a FusedLocationProviderClient.
FusedLocationProviderClient fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);

// Check for permission


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
// Get the last known location
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// Use the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
});
}

iOS (Swift):
In iOS, you need to request permission to access the device's location and use the Core
Location framework to get the current location.

1. Request Location Permission:


Add the necessary permissions to your Info.plist file:

<key>NSLocationWhenInUseUsageDescription</key>

<string>We need your location to provide the best experience.</string>

2. Use Core Location Framework:

In your view controller, import CoreLocation and implement CLLocationManagerDelegate:

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

let locationManager = CLLocationManager()

override func viewDidLoad() {

super.viewDidLoad()

locationManager.delegate = self

locationManager.requestWhenInUseAuthorization()

locationManager.startUpdatingLocation()

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:


[CLLocation]) {

guard let location = locations.last else { return }

// Use the location

let latitude = location.coordinate.latitude

let longitude = location.coordinate.longitude

By using these methods, you can obtain the current location of the user in your
Android and iOS applications using Google Maps API. Remember to handle cases where the
location might not be available or permission is denied by the user.
GET THE UPDATED LOCATION

To continuously get updated location information in a mobile application using Google Maps
API, you need to implement location updates using either the Android Location API or the
Core Location framework in iOS. Here's how you can achieve that in both platforms:

Android (Java/Kotlin):

1. Request Location Updates:

You can use the requestLocationUpdates() method of the LocationManager class to


receive location updates at a specified interval or distance.

// Define a location listener

LocationListener locationListener = new LocationListener() {

@Override

public void onLocationChanged(Location location) {

// Handle updated location

double latitude = location.getLatitude();

double longitude = location.getLongitude();

@Override

public void onStatusChanged(String provider, int status, Bundle extras) {}

@Override

public void onProviderEnabled(String provider) {}

@Override

public void onProviderDisabled(String provider) {}

};

// Request location updates


locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,

MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,
locationListener);

iOS (Swift):

Request Location Updates:

Use the startUpdatingLocation() method of the CLLocationManager class to begin receiving


location updates.

locationManager.delegate = self

locationManager.startUpdatingLocation()

2. Handle Updated Locations:

Implement the didUpdateLocations method of the CLLocationManagerDelegate


protocol to receive updated location information.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:


[CLLocation]) {

guard let location = locations.last else { return }

// Handle updated location

let latitude = location.coordinate.latitude

let longitude = location.coordinate.longitude

Ensure you have appropriate permissions set up for location access in both
platforms, and handle any potential errors or permission denials gracefully. Continuous
location updates can impact battery life, so use them judiciously and consider adjusting the
update frequency based on your application's needs.

GETTING LOCATION DATA


To get location data in an Android application, you can use the Android Location API. Here's
a step-by-step guide to help you:
1. Add Permissions:

Make sure to add the necessary permissions in your AndroidManifest.xml file to access the
device's location. You'll need either `ACCESS_FINE_LOCATION` or
`ACCESS_COARSE_LOCATION` permission depending on your accuracy requirements:

```xml

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

```

2. Check Permissions at Runtime:

In your activity or fragment where you want to get the location data, check for
permissions at runtime. You can use the following code snippet to request permissions if
they are not granted:

```java

private static final int LOCATION_PERMISSION_REQUEST = 1001;

private void checkLocationPermission() {

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{

ActivityCompat.requestPermissions(this, new String[]


{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST);

} else {

// Permission already granted, proceed with location retrieval

getLocation();

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == LOCATION_PERMISSION_REQUEST) {

if (grantResults.length > 0 && grantResults[0] ==


PackageManager.PERMISSION_GRANTED) {

// Permission granted, proceed with location retrieval

getLocation();

} else {

// Permission denied, handle accordingly (e.g., show a message)

```

3. Retrieve Location Data:

Use the `LocationManager` or the Fused Location Provider API (recommended) to retrieve
location data. Here's an example using the Fused Location Provider API:

```java

import android.location.Location;

import com.google.android.gms.location.FusedLocationProviderClient;

import com.google.android.gms.location.LocationServices;

import com.google.android.gms.tasks.OnSuccessListener;

private void getLocation() {

FusedLocationProviderClient fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient.getLastLocation()

.addOnSuccessListener(this, new OnSuccessListener<Location>() {

@Override

public void onSuccess(Location location) {

if (location != null) {

double latitude = location.getLatitude();

double longitude = location.getLongitude();

// Use latitude and longitude as needed

});

```

4. Handle Location Updates (Optional):

If you need continuous location updates, you can request them using the Fused Location
Provider API's `requestLocationUpdates` method. This is useful for tracking a user's
movement over time.

5. Run Permission Check and Get Location:

Call `checkLocationPermission()` from your activity's `onCreate` or wherever appropriate


to check permissions and initiate the location retrieval process.

Remember to handle cases where the location might be null (if a location fix is not available)
and to handle exceptions that may occur during location retrieval.

MONITORING A LOCATION
Monitoring a location in an Android application typically involves setting up a geofence or
continuously tracking the device's location. Here's how you can monitor a location using
geofencing and continuous location updates:

Geofencing

1. Add Permissions:

Ensure that you have the necessary permissions in your AndroidManifest.xml file:

```xml

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

```

2. Set Up Geofence:

Create a geofence using the `Geofence.Builder` class and add it to the `GeofencingClient`:

```java

import com.google.android.gms.location.Geofence;

import com.google.android.gms.location.GeofencingClient;

import com.google.android.gms.location.GeofencingRequest;

import com.google.android.gms.location.LocationServices;

private static final String GEOFENCE_ID = "my_geofence";

private GeofencingClient geofencingClient;

private void createGeofence(double latitude, double longitude, float radius) {

Geofence geofence = new Geofence.Builder()

.setRequestId(GEOFENCE_ID)

.setCircularRegion(latitude, longitude, radius)


.setExpirationDuration(Geofence.NEVER_EXPIRE)

.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)

.build();

GeofencingRequest geofenceRequest = new GeofencingRequest.Builder()

.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)

.addGeofence(geofence)

.build();

geofencingClient = LocationServices.getGeofencingClient(this);

geofencingClient.addGeofences(geofenceRequest, getGeofencePendingIntent())

.addOnSuccessListener(this, new OnSuccessListener<Void>() {

@Override

public void onSuccess(Void aVoid) {

// Geofence added successfully

})

.addOnFailureListener(this, new OnFailureListener() {

@Override

public void onFailure(@NonNull Exception e) {

// Failed to add geofence

});

```
3. Handle Geofence Events:

Create a PendingIntent to handle geofence events, such as entering or exiting the


geofence:

```java

import android.app.PendingIntent;

import android.content.Intent;

import com.google.android.gms.location.Geofence;

import com.google.android.gms.location.GeofenceStatusCodes;

private PendingIntent getGeofencePendingIntent() {

Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);

return PendingIntent.getBroadcast(this, 0, intent,


PendingIntent.FLAG_UPDATE_CURRENT);

```

4. Broadcast Receiver for Geofence Events:

Create a broadcast receiver to handle geofence transition events:

```java

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.widget.Toast;

public class GeofenceBroadcastReceiver extends BroadcastReceiver {


@Override

public void onReceive(Context context, Intent intent) {

if (GeofencingEvent.fromIntent(intent).hasError()) {

int errorCode = GeofencingEvent.fromIntent(intent).getErrorCode();

String errorMessage = GeofenceStatusCodes.getStatusCodeString(errorCode);

Toast.makeText(context, "Geofence error: " + errorMessage,


Toast.LENGTH_SHORT).show();

return;

int transitionType = GeofencingEvent.fromIntent(intent).getGeofenceTransition();

if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) {

// Handle entering geofence

Toast.makeText(context, "Entered geofence", Toast.LENGTH_SHORT).show();

} else if (transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {

// Handle exiting geofence

Toast.makeText(context, "Exited geofence", Toast.LENGTH_SHORT).show();

```

Continuous Location Updates

1. Set Up Location Updates:

Use the Fused Location Provider API to request continuous location updates:
```java

import com.google.android.gms.location.LocationCallback;

import com.google.android.gms.location.LocationRequest;

import com.google.android.gms.location.LocationServices;

private static final long UPDATE_INTERVAL = 10 * 1000; // 10 seconds

private static final long FASTEST_INTERVAL = 5 * 1000; // 5 seconds

private void requestLocationUpdates() {

LocationRequest locationRequest = LocationRequest.create()

.setInterval(UPDATE_INTERVAL)

.setFastestInterval(FASTEST_INTERVAL)

.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

LocationCallback locationCallback = new LocationCallback() {

@Override

public void onLocationResult(LocationResult locationResult) {

if (locationResult != null) {

Location location = locationResult.getLastLocation();

// Handle new location updates

};

LocationServices.getFusedLocationProviderClient(this)

.requestLocationUpdates(locationRequest, locationCallback, null);


}

```

2. Handle Location Updates:

Implement the `onLocationResult` method in the `LocationCallback` to handle new


location updates as they arrive.

Remember to handle permissions for accessing the device's location as described in the
previous response.

You might also like