Android SharedPreferences Tutorial and Example

Accessing Google Maps API for location services in Android

Android location features combine two related services: the Maps SDK for Android renders interactive maps, while the Fused Location Provider uses GPS, Wi-Fi, cellular data, and sensors to produce position updates. Accessing Google Maps API for location services in Android therefore involves more than adding a map: your app also needs credentials, runtime permission, a location provider, and lifecycle-aware error handling.

Begin with an Android Studio project, a physical phone with Google Play services, and a billing-enabled Google Cloud project. Most mainstream Android phones sold through the Australian Google Play market include Play services, while an emulator needs a Google APIs system image. Test in central Sydney or Melbourne as well as regional areas because urban buildings and tunnels can make GPS less accurate.

Add dependencies and secure API credentials

Add the Maps and Location libraries to the app-level Gradle file using compatible releases. One example is:

implementation("com.google.android.gms:play-services-maps:19.2.0")
implementation("com.google.android.gms:play-services-location:21.3.0")

The Maps dependency provides GoogleMap and map fragments; the Location dependency provides FusedLocationProviderClient.

Requirement Recommended option Why it suits the task
Interactive map Maps SDK for Android Renders tiles, markers, controls, and camera movement
One fresh position getCurrentLocation() Returns a single fix with a cancellation token
Ongoing tracking requestLocationUpdates() Streams updates at a chosen priority and interval
No Play services LocationManager Provides a less capable fallback for location only

In Google Maps Platform, enable Maps SDK for Android and the Location API, attach a billing-enabled Cloud project, and create an Android API key. Restrict the key by package name and SHA-1 certificate. Register debug and release signing fingerprints separately, and never leave a production key unrestricted.

Keep the key out of source control by putting it in local.properties or CI secrets, then inject it as a manifest placeholder:

MAPS_API_KEY=your_key_here
<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="${MAPS_API_KEY}" />

For Gradle builds, read MAPS_API_KEY and assign it to manifestPlaceholders["MAPS_API_KEY"].

Request permission and verify location settings

Declare fine and coarse location in the manifest:

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

Request them at runtime with ActivityResultContracts.RequestMultiplePermissions when the user starts a location-dependent feature. A denial or an Android 12+ approximate grant is a valid result, so provide a manual map fallback rather than repeatedly prompting. Check permission state before every location or my-location request.

Location permission and the device's location toggle are separate. Use SettingsClient.checkLocationSettings() with a LocationSettingsRequest to detect disabled location, then offer the system resolution dialog by handling ResolvableApiException. Request background location only when continuous tracking is essential; Android imposes extra manifest, foreground-service, and disclosure requirements for that use.

Retrieve current and continuous positions

After confirming permission, obtain the client and request a single fix:

val client = LocationServices.getFusedLocationProviderClient(this)
val cancellation = CancellationTokenSource()

client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, cancellation.token)
    .addOnSuccessListener { location -> /* show or use location */ }
    .addOnFailureListener { error -> /* handle error */ }

A successful task can still return null when no recent signal is available. Use lastLocation as a possible fallback, but show its age and accuracy rather than presenting it as current. The cancellation source lets the screen stop the request when it closes.

For continuous updates, build a LocationRequest with a priority and interval, call requestLocationUpdates, and retain the callback so removeLocationUpdates(callback) runs when tracking stops. Choose balanced accuracy for ordinary tracking and high accuracy only while actively navigating. Tie collection to the lifecycle so rotation does not restart collection unnecessarily.

Coordinates use signed latitude and longitude. Sydney is approximately -33.8688, 151.2093, while Melbourne is -37.8136, 144.9631; pass these values directly to LatLng. Calculate straight-line distance with Location.distanceBetween, then format metres or kilometres using Australian spelling. Google routing and map labels also reflect Australia's left-hand traffic.

Display the map and move the camera

A SupportMapFragment is a simple XML-based container:

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Retrieve it with getMapAsync. In the callback, enable isMyLocationEnabled only after permission succeeds, then move the camera with CameraUpdateFactory.newLatLngZoom. Add a marker when the user selects a place. The blue location dot shows the device position, but it does not replace an explicit callback for business logic.

If you inflate MapView directly, forward all required lifecycle calls, including onCreate, onResume, and onDestroy, so map resources are released. Do not keep continuous location updates running merely to animate a static dot. For a map embedded in settings or forms, vertical scrollbar styling can help distinguish scrollable content from the pannable map area.

Recommendations for dependable location handling

To practise the complete flow, adapt one of the sample app projects so it requests permission, fetches one fix, displays it, and releases its resources.

  • Restrict every API key by application and signing certificate, and rotate it if it leaks.
  • Ask for permission at the moment the feature is used, while handling denial and approximate-location choices.
  • Use getCurrentLocation() for a one-off fix and location updates only for genuine continuous tracking.
  • Balance update priority, interval, and batching against battery use, especially on mobile data.
  • Handle null, stale, and inaccurate fixes by explaining the state and offering a manual retry.
  • Test physical devices, permission changes, rotation, disabled settings, weak GPS, and regional network coverage.
  • Collect only necessary location data; when history is stored, review obligations under the Australian Privacy Act and Australian Privacy Principles.

Location should be modelled as permission-dependent state with defined success, denial, disabled-settings, and unavailable-signal paths. With those states separated, the same app behaves predictably for someone in Brisbane, a commuter in Sydney, and a traveller moving through regional Australia.