Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 17

Unit 5

Working with Location Services and Maps


Google Map API
 Maps are of great use and it increases the productivity of an app.
 Google Maps API allows Android developers to integrate Google
Maps in their app.
 The location APIs available in Google Play services facilitate
adding location awareness to your app with automated location
tracking, wrong-side-of-the-street detection, geofencing, and
activity recognition.
 We can show any location on the map , or can show different routes
on the map , also customize the map according to our choices.
 Request location permissions
 To protect user privacy, apps that use location services must request location
permissions.
 It includes multiple permissions related to location.
 Which permissions you request, and how you request them, depend on the
location requirements for your app's use case.
Types of Google Maps
 There are four different types of Google maps, as well as an
optional to no map at all.
 Each of them gives different view on map. These maps are as
follow:
 Normal: This type of map displays typical road map, natural
features like river and some features build by humans.
 Hybrid: This type of map displays satellite photograph data
with typical road maps. It also displays road and feature labels.
 Satellite: Satellite type displays satellite photograph data, but
doesn't display road and feature labels.
 Terrain: This type displays photographic data. This includes
colors, contour lines and labels and perspective shading.
 None: This type displays an empty grid with no tiles loaded.
Elements of Google Map
 GoogleMap
 Responsible for downloading and displaying map tiles and different map controls
 This is the main class of the Maps SDK for Android.
 MapView
 A subclass of View class, provides the view canvas onto which map is drawn by
GoogleMap objects
 SupportMapFragment
 A subclass of Fragment class, allows a map to be placed within a fragment
 Manages the lifecycle of the map and is the parent element of the app's UI.
 My Location Layer
 Displays a button on the map, when selected, centers the map on the user’s
current geographical location
 Marker
 Allow locations to be marked on the map. The position of the marker is defined
via Latitude and Longitude
Steps to add Google Map in Android
Application [1]
 Create new project in Android studio.
 Add the Google Maps Views Activity:
 Right-click on the app folder in your project.
 Select New > Google > Google Maps Views Activity.
 Set up your Google Cloud project.
 In the Google Cloud Console, on the project selector page, click Create Project to
begin creating a new Cloud project.
 To use Google Maps Platform, you must enable the APIs or SDKs you plan to use
with your project.
 Get the API key.
 Add the API key to your app
 In your AndroidManifest.xml file: Add <meta-data > as a child of the <application> tag
 <meta-data
android:name="com.google.android.geo.API_KEY"
android:value="${YOUR API KEY}" />
 Look at the code: modify your code in MapsActivity.java file, activity_maps.xml and add
maps dependency in Module build.gradle file
 dependencies {

// Maps SDK for Android


implementation 'com.google.android.gms:play-services-maps:18.2.0'
}
 Deploy and run the app.
Steps to Get API key for Google Map
 Go to the Google Maps Platform >
Credentials page.
 On the Credentials page, click Create credentials >
API key.
The API key created dialog displays your newly
created API key.
 Click Close.
The new API key is listed on the Credentials page
under API keys.
Add a Map
 // Implement OnMapReadyCallback.
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the layout file as the content view.
setContentView(R.layout.activity_main);

// Get a handle to the fragment and register the callback.


SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

// Get a handle to the GoogleMap object and display marker.


@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)) .title("Marker"));
}
Types of Location Access
 Each permission has a combination of the following characteristics:
 Category: Either foreground location or background location.
 Foreground Location: If your app contains a feature that shares or receives location
information only once, or for a defined amount of time, then that feature requires
foreground location access.
 Background Location: An app requires background location access if a feature
within the app constantly shares location with other users or uses the Geofencing API.
 Accuracy: Either approximate location or precise location.
 Approximate: Provides an estimate of the device's location, to within about 1 mile
(1.6 km).
Permission required is ACCESS_COARSE_LOCATION

 Precise: Provides an estimate of the device's location that is as accurate as possible,


usually within about 160 feet (50 meters) and sometimes as accurate as within 10 feet
(a few meters) or better.
Permission required is ACCESS_FINE_LOCATION
Get the last known location
 Using the Google Play services location APIs, your app can
request the last known location of the user's device.
 Use the fused location provider to retrieve the device's last
known location.
 The fused location provider is one of the location APIs in
Google Play services.
 It manages the underlying location technology and provides
a simple API so that you can specify requirements at a high
level, like high accuracy or low power.
 It also optimizes the device's use of battery power.
Get the Current Location
 add maps dependency in Module build.gradle file
 dependencies {

// Maps SDK for Android


implementation 'com.google.android.gms:play-services-location:20.0.0'
}
 Add permission in manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION"/>
 Declare objects:
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private GoogleMap map;
// The entry point to the Fused Location Provider.
private FusedLocationProviderClient fusedLocationProviderClient;
/ /The geographical location where the device is currently located. That is, the last-
known location retrieved by the Fused Location Provider.
private Location lastKnownLocation;
 Add in java file:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Construct a FusedLocationProviderClient.
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

SupportMapFragment mapFragment = (SupportMapFragment)


getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

// Get a handle to the GoogleMap object and display marker.


@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)) .title("Marker"));
}
 Create function getDeviceLocation() :
private void getDeviceLocation() {
//check permission
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION)!=
PackageManager.PERMISSION_GRANTED)

{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;

}
Task<Location> locationResult = fusedLocationProviderClient.getLastLocation();
locationResult.addOnSuccessListener(this, new
OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
lastKnownLocation=location;
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()), DEFAULT_ZOOM));
}
}
});
Geocoding
 Geocoding is the process of transforming a street address
or other description of a location into a (latitude,
longitude) coordinate.
 Reverse geocoding is the process of transforming a
(latitude, longitude) coordinate into a (partial) address.
 The amount of detail in a reverse geocoded location
description may vary, for example one might contain the
full street address of the closest building, while another
might contain only a city name and postal code.
 Geocoding is the process of converting addresses (like a street
address e.g. "1600 Pennsylvania Avenue NW") into geographic
coordinates (like latitude and longitude- e.g., 38.8811111,-
77.036871).
 This can be helpful for many things, including:
 Recognizing geographical patterns
 Analyzing customer data
 Verifying customer addresses
 Planning retail locations

 Geocoding is used by Global Positioning Systems (GPS).


 Geocoding is more than just obtaining a long list of coordinates. It is
valuable data that allows businesses across various industries and
verticals to uncover opportunities for growth.
 Relevant location information can’t be obtained from just addresses.
Addresses are pieces of text and can change over time, but
coordinates will always be the same.
 Geocoding converts location information into numbers so that it is
structured and ready to be integrated for analysis.
 Reverse geocoding, as the name suggests, is the process by which
geographic coordinates are converted into a physical address that is
human-readable address.
 While underused compared to geocoding, reverse geocoding is most
helpful in identifying addresses from a given geographic point on a
map. This can be used to find the nearest store, restaurant, or other
location to a given address.
 It can also be used to find the address of a location (i.e., "what's the
closest city?").
References
 https://developers.google.com/maps/documentation/androi
d-sdk/start#create-project
 https://developers.google.com/maps/documentation/androi
d-sdk/map

You might also like