Overview

You will learn: how to find and track your device location on a map.

Using the ArcGIS API for Android, it's easy to create an app that displays and tracks a device location on any style map. This can be very useful when building applications that allow you to find directions or places around you. This lab uses the AndroidLocationDataSource class provided for this purpose. This class uses the Android location API to find and update the device's location. To show your location on the map, you can use a default symbol or you can choose your own. Once the location is found, the view animates to the location and can (optionally) rotate according to the direction where the tracked device is heading.

In this lab, you will use the ArcGIS API for Android to build a simple mapping app to track your device location on a map.

Before you begin

Make sure you have installed the latest version of Android Studio.

Reuse the starter project

In a new or empty project folder, make a copy of the Create a starter app or download and unzip the project solution.

  • Open the new Android project in Android Studio.

  • Run the project and verify the project builds and the map displays in the device simulator.

  • You may be required to sync the project dependencies and refresh Gradle.

Steps

  1. Update the android manifest file to allow GPS location access. The Android manifest file is located in the project hierarchy under app > manifests > AndroidManifest.xml. Be sure to insert these new elements within the <manifest> element.

       <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
       <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  2. In the file app > java > {your.package.name} > MainActivity.java, add a new private member variable to hold a reference to the location display object.

     private MapView mMapView;
     /* ** ADD ** */
     private LocationDisplay mLocationDisplay;
    
  3. Create a new method named setupLocationDisplay(). This method handles everything your app requires to configure and start the location services. You will add more code to this method in subsequent steps.

    private void setupLocationDisplay() {
        mLocationDisplay = mMapView.getLocationDisplay();
    }
    
  4. Add an event listener to listen for location data source change events and check here if the user has granted access to the device GPS location. If permission was not granted then request permission from the user.

         mLocationDisplay = mMapView.getLocationDisplay();
         /* ** ADD ** */
         mLocationDisplay.addDataSourceStatusChangedListener(dataSourceStatusChangedEvent -> {
             if (dataSourceStatusChangedEvent.isStarted() || dataSourceStatusChangedEvent.getError() == null) {
                 return;
             }
    
             int requestPermissionsCode = 2;
             String[] requestPermissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    
             if (!(ContextCompat.checkSelfPermission(MainActivity.this, requestPermissions[0]) == PackageManager.PERMISSION_GRANTED
                 && ContextCompat.checkSelfPermission(MainActivity.this, requestPermissions[1]) == PackageManager.PERMISSION_GRANTED)) {
                 ActivityCompat.requestPermissions(MainActivity.this, requestPermissions, requestPermissionsCode);
             } else {
                 String message = String.format("Error in DataSourceStatusChangedListener: %s",
                         dataSourceStatusChangedEvent.getSource().getLocationDataSource().getError().getMessage());
                 Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
             }
         });
    
  5. Set the map pan mode for compass navigation and start the location display. This code completes the setupLocationDisplay() method.

         });
         /* ** ADD ** */
         mLocationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.COMPASS_NAVIGATION);
         mLocationDisplay.startAsync();
    
  6. Create a method to override the default Android behavior for requesting permission. Check that the user granted permission, and if so start the location display.

     @Override
     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
         if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
             mLocationDisplay.startAsync();
         } else {
             Toast.makeText(MainActivity.this, getResources().getString(R.string.location_permission_denied), Toast.LENGTH_SHORT).show();
         }
     }
    
  7. Add the error message to the string resource table. Open the file app > res > values > strings.xml and add a new string entry.

     <string name="location_permission_denied">User denied permission for device location.</string>
    
  8. Call the setupLocationDisplay() method from the onCreate() method, but after the map is set up.

         setupMap();
         /* ** ADD ** */
         setupLocationDisplay();
    
  9. Press Control-R to run your project in the simulator.

Congratulations, you're done!

Your map should now display the location of your device on the basemap. It is best to test this on a real device so that the GPS is used. Otherwise the simulator will simulate a device location. Compare your solution with our completed solution project.

Challenge

Use a different basemap

Instead of the basemap selected here, use one of the other basemaps or use the web map you created in the Display a web map lab.

Experiment with pan mode

Review the options for LocationDisplay.AutoPanMode and experiment with the different settings. Review and experiment with other available properties such as initial zoom scale, wander extent factor, and show accuracy.

Improve the UI

Implement a UI to give the user the ability to stop and start GPS tracking.