Generated banner for Amazon Location Service
Generated logo for Amazon Location Service

Amazon Location Service

AWS LabsOfficialCreated by aws-geospatialDistributed by AWS Labs

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • No issues found

From the author

Integrates Amazon Location Service APIs for AWS applications. Use this skill when users want to add maps (interactive MapLibre or static images); geocode addresses to coordinates or reverse geocode coordinates to addresses; calculate routes, travel times, or service areas; find places and businesses through text search, nearby search, or autocomplete suggestions; retrieve detailed place information including hours, contacts, and addresses; monitor geographical boundaries with geofences; or track device locations. Covers authentication, SDK integration, and all Amazon Location Service capabilities.
— the description by aws-geospatial

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Amazon Location Service provides a suite of geospatial APIs for web and mobile applications. This skill covers the integration of maps, geocoding, routing, places search, geofencing, and device tracking. It emphasizes the use of the bundled JavaScript client for web development and promotes resourceless API operations to simplify deployment. The skill also provides guidance on authentication via IAM or API keys, and distinguishes between interactive address input and bulk postal address validation using the Jobs API.

What it does

  • Provides interactive maps using MapLibre and static map images.
  • Converts addresses to coordinates (geocoding) and coordinates to addresses (reverse geocoding).
  • Calculates routes, travel times, and service areas with traffic estimation.
  • Searches for places, businesses, and points of interest with autocomplete functionality.
  • Monitors geographical boundaries with geofences and tracks device locations.
  • Validates and standardizes addresses in bulk against authoritative postal data.

When to use it

  • When building location-aware web or mobile applications on AWS.
  • When you need to implement maps, routing, or place search functionality.
  • When you need to verify and standardize large datasets of addresses in the US, CA, UK, or AU.
  • When you need to track device locations or monitor entry/exit from geofenced areas.
  • When migrating from other mapping providers to Amazon Location Service.

Advantages

  • Supports resourceless API operations to reduce infrastructure management.
  • Provides a bundled JavaScript client for simplified web integration.
  • Offers flexible authentication options including API keys for public applications.
  • Includes specialized APIs for bulk address validation and postal standardization.
  • Integrates seamlessly with other AWS services and SDKs.

Usage examples

“How do I implement an address autocomplete field in my React app using Amazon Location Service?”
The agent provides a guide on using the Autocomplete API, emphasizing the use of Address.Label for display and GetPlace for retrieving full details upon selection.
“I need to validate a large database of customer addresses in the UK. How should I do this?”
The agent explains the use of the asynchronous Jobs API (StartJob with ValidateAddress) for bulk processing, noting that it provides postal-authority verdicts.
“How do I initialize a map in my web application?”
The agent provides instructions on using MapLibre with a direct URL to the map style descriptor and setting validateStyle to false for performance.
“What are the best practices for securing my map implementation on a public website?”
The agent recommends using API Keys with restricted AllowActions and AllowResources, rather than exposing IAM credentials.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/awslabs/amazon-location-service/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip amazon-location-service.zip -d .agents/skills

Documentation by aws-geospatial

Overview

Amazon Location Service provides geospatial APIs for maps, geocoding, routing, places search, geofencing, and tracking. Prefer the bundled JavaScript client (@aws/amazon-location-client) for web development and use resourceless API operations to avoid managing AWS resources.

When to Use This Skill

Use this skill when:

  • Building location-aware web or mobile applications

  • Working with Amazon Location Service projects

  • Implementing maps, geocoding, routing, or places search

  • Adding geofencing or device tracking functionality

  • Integrating geospatial features into AWS applications

Do NOT use this skill for:

  • Google Maps, Mapbox, or Leaflet-with-OSM projects (unless migrating to Amazon Location)

  • Generic GIS operations without AWS context

  • Non-AWS geospatial services

Amazon Location Service API Overview

Places (SDK: geo-places, JS: @aws-sdk/client-geo-places)

  • Geocode (Forward/Reverse): Convert addresses to coordinates and vice versa

  • Search (Text/Nearby): Find points of interest with contact and hours info

  • Autocomplete: Predict addresses based on user input

  • Suggest: Predict places and points of interest based on partial or misspelled user input

  • Get Place: Retrieve place details by place ID

Jobs (SDK: location, JS: @aws-sdk/client-location)

  • Address Validation: Verify and standardize addresses in bulk with the asynchronous Jobs API (StartJob with Action ValidateAddress, then GetJob/ListJobs/CancelJob). It adds what Geocode lacks — a postal-authority verdict (ValidationGranularity, Mailable/Locatable, per-component StatusDetail), not just coordinates. Coverage is US, CA, UK, and AU only; for other countries use Geocode.

Maps (SDK: geo-maps, JS: @aws-sdk/client-geo-maps)

  • Dynamic Maps: Interactive maps using tiles with MapLibre rendering

  • Static Maps: Pre-rendered, non-interactive map images, good for including an image into a web page, or for thumbnail images

Routes (SDK: geo-routes, JS: @aws-sdk/client-geo-routes)

  • Route calculation with traffic and distance estimation

  • Service area/isoline creation

  • Matrix calculations for multiple origins/destinations

  • GPS trace alignment to road segments

  • Route optimization (traveling salesman problem)

Geofences & Trackers (SDK: location, JS: @aws-sdk/client-location)

  • Geofences: Detect entry/exit from geographical boundaries

  • Trackers: Current and historical device location tracking

API Keys (SDK: location, JS: @aws-sdk/client-location)

  • API Keys: Grant access to public applications without exposing AWS credentials

Common Mistakes

Avoid these frequent errors:

  1. Using Title instead of Address.Label for display: In Autocomplete results, always display Address.Label. The Title field may show components in reverse order and is not suitable for user-facing text.

  2. Using GetStyleDescriptor API for map initialization: MUST use direct URL passing to MapLibre (https://maps.geo.{region}.amazonaws.com/v2/styles/Standard/descriptor?key={apiKey}) instead of making GetStyleDescriptor API calls. The direct URL method is required for proper map rendering.

  3. Forgetting validateStyle: false in MapLibre config: Always set validateStyle: false in the MapLibre Map constructor for faster map load times with Amazon Location styles.

  4. Mixing resource-based and resourceless operations: When possible, prefer resourceless operations (direct API calls without pre-created resources) for simpler deployment and permissions.

  5. Inconsistent API operation naming: Use the format service:Operation when referencing APIs (e.g., geo-places:Geocode, geo-maps:GetStyleDescriptor). SDK clients use @aws-sdk/client-* format.

  6. Not handling nested Address objects correctly: The Address object from GetPlace contains nested objects (Region.Code, Region.Name, Country.Code2, etc.), not flat strings. Access nested properties correctly.

  7. Wrong action names in API Key permissions: API key AllowActions use geo-maps:, geo-places:, geo-routes: prefixes (e.g., geo-places:Geocode, geo-routes:CalculateRoutes). Do NOT use SDK client names (@aws-sdk/client-geo-places) or IAM-style actions. See the Authentication and Permissions section for the complete list.

Defaults

Use these default choices unless the user explicitly requests otherwise:

  • JavaScript SDK: Bundled client (CDN) for browser-only apps; npm modular SDKs (@aws-sdk/client-geo-*) for React and build tool apps

  • API operations: Resourceless for Maps/Places/Routes (Geofencing/Tracking always require pre-created resources)

  • Authentication: API Key for Maps/Places/Routes; Cognito for Geofencing/Tracking

  • Map style: Standard

  • Coordinate format: [longitude, latitude] (GeoJSON order)

Override: User can specify "use Cognito for Maps/Places/Routes" or "use bundled client for React".

API Selection Guidance

Choose the right API for your use case:

Address Input (interactive forms)
  • Autocomplete → Type-ahead in address forms (partial input: "123 Main")

  • GetPlace → Get full details after user selects autocomplete result (by PlaceId)

  • Geocode → Resolve a complete user-typed address to coordinates. Returns coordinates, a matched label, and match quality (MatchScores overall + per-component, AddressNumberCorrected) synchronously in one call — but no postal-deliverability verdict or standardized output.

Address Validation (verify & standardize)
  • StartJob (Action ValidateAddress) → Verify and standardize addresses in bulk against authoritative postal data; async Jobs API with Parquet input/output in Amazon S3. Coverage: US, CA, UK, AU only; for other countries use Geocode.

  • GetJob / ListJobs / CancelJob → Track, enumerate, and cancel validation jobs

  • Choose the Jobs API when you need a postal-authority verdict (ValidationGranularity, Mailable/Locatable, per-component StatusDetail) or bulk throughput. For a single ad-hoc check of whether one address resolves and how well it matched, the synchronous Geocode MatchScores is the right tool — do not stand up a job. See the address-verification reference.

Finding Locations
  • SearchText → General text search ("pizza near Seattle")

  • SearchNearby → Find places near a coordinate (restaurants within 5km)

  • Suggest → Predict places/POIs from partial or misspelled input

  • Autocomplete → Address-specific predictions (not for general POI search)

Geocoding
  • Geocode (Forward) → Address string → Coordinates

  • ReverseGeocode → Coordinates → Address

Maps
  • Dynamic Maps (tiles + MapLibre) → Interactive maps requiring pan, zoom, markers

  • Static Maps (image) → Non-interactive map images for thumbnails or email

Routing
  • CalculateRoutes → Single route between origin and destination

  • CalculateRouteMatrix → Multiple origins/destinations travel times

  • CalculateIsolines → Service areas (all locations reachable within time/distance)

LLM Context Files

When you need detailed API parameter specifications or service capabilities not covered in the reference files, fetch these llms.txt resources:

Key Guidance for Better Recommendations

Prefer the Bundled JavaScript Client for Web Development

For convenient web application development, Amazon Location Service provides a bundled JavaScript client that simplifies integration and provides optimized functionality without custom bundling. This bundled client includes all libraries required to build client side web applications with Amazon Location Service.

Features included in the bundled client:

  • Enables direct pre-bundled dependency inclusion without custom bundle / build

  • Simplified authentication and API integration

  • TypeScript support with comprehensive type definitions

  • Support for all Amazon Location SDKs

Included SDKs and Libraries:

Resources:

Prefer Resourceless Operations

Amazon Location Places, Maps and Routes services offer both resource-based and resourceless API operations. Resourceless operations are often simpler and more appropriate for many use cases.

Resource-based operations require you to:

  • Create and configure Amazon Location Service resources (maps, place indexes, route calculators)

  • Manage resource lifecycle and permissions

  • Handle resource naming and organization

Resourceless operations allow you to:

  • Make API calls directly without pre-creating resources

  • Reduce deployment complexity

  • Simplify IAM permissions and API Key permissions

Authentication and Permissions

When discussing permissions for Amazon Location Places, Maps and Routes services, always include both IAM permissions and API Key permissions in your guidance. If the type of application being developed is clear, recommend the appropriate authorization tool as described below:

IAM Permissions - Recommended for server-side applications and AWS SDK usage:

  • Used with AWS credentials (access keys, roles, etc.)

  • Provide fine-grained access control

  • Required for resource management operations

API Key Permissions - Alternative authentication method, especially useful for client-side applications or applications deployed to unauthenticated (public) users:

  • Simplified authentication without exposing AWS credentials

  • Can be configured with specific allowed operations

  • Useful for web and mobile applications

  • Supports both resource-based and resourceless operations

  • Enables faster subsequent map loads through CDN caching

API Key Action Names - API keys use their own action naming convention. Do NOT use SDK client names or IAM action names — they will be rejected.

Resourceless API key actions (recommended):

ServiceAllowActionsAllowResources
Mapsgeo-maps:GetTile, geo-maps:GetStaticMaparn:aws:geo-maps:REGION::provider/default
Placesgeo-places:Autocomplete, geo-places:Geocode, geo-places:ReverseGeocode, geo-places:SearchText, geo-places:SearchNearby, geo-places:Suggest, geo-places:GetPlacearn:aws:geo-places:REGION::provider/default
Routesgeo-routes:CalculateRoutes, geo-routes:CalculateRouteMatrix, geo-routes:CalculateIsolines, geo-routes:OptimizeWaypoints, geo-routes:SnapToRoadsarn:aws:geo-routes:REGION::provider/default

Do NOT use legacy geo: prefixed actions (e.g., geo:GetMap*, geo:CalculateRoute) — these are for pre-created resources only and will not work with resourceless APIs.

LocationClient Setup

Geofencing and Tracking use LocationClient (@aws-sdk/client-location). These are resource-based operations — you MUST create resources (trackers, geofence collections) before using them.

import { LocationClient } from "@aws-sdk/client-location";

// Server-side: uses IAM credentials from environment/role
const client = new LocationClient({ region: "us-east-1" });
// Client-side: uses Amazon Cognito
import { LocationClient } from "@aws-sdk/client-location";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";

const client = new LocationClient({
  region: "us-east-1",
  credentials: fromCognitoIdentityPool({
    identityPoolId: "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    clientConfig: { region: "us-east-1" },
  }),
});

MCP Server Integration

Integrates with the AWS MCP Server (Apache-2.0 license) which provides access to AWS documentation, API references, and direct API interactions. See the Getting Started Guide for setup and credential configuration. To use a non-default region, add "--metadata", "AWS_REGION=<your-region>" to your MCP config args.

Additional Resources

Reference Files

Load these resources as needed for specific implementation guidance:

  • Address Input - Create effective address input forms for users with address type ahead completion improving input speed and accuracy

  • Address Verification - Verify and standardize addresses in bulk against authoritative postal data using the asynchronous Jobs API (StartJob with Action ValidateAddress), before persisting to databases or taking downstream actions

  • Calculate Routes - Calculate routes between locations with customizable travel options and display them on maps

  • Device Tracking - Track device locations in real time and query position history

  • Dynamic Map Rendering - Render dynamic maps with MapLibre

  • Google Maps Migration (Android) - Migrate Android application from Google Maps SDK for Android to Amazon Location Service

  • Google Maps Migration (iOS) - Migrate iOS application from Google Maps SDK for iOS to Amazon Location Service

  • Google Maps Migration (JavaScript) - Migrate JavaScript web application from Google Maps API to Amazon Location Service

  • Places Search - Search for places or points of interest

  • Web JavaScript - Integrate Amazon Location services into web browser applications

  • Zone Alerts - Monitor device positions against geographic boundaries and react to zone entry or exit

Files

references/google-migration-android.md

Google Maps Migration (Android)

Audience Note: Keywords MUST, SHOULD, MAY in this document indicate requirements for agent recommendations to users, following RFC 2119.

Migrate Android applications from Google Maps SDK for Android to Amazon Location Service using the AWS SDK for Kotlin and MapLibre Native.

Table of Contents

  • Migration Overview

  • Setup and Dependencies

  • Authentication

  • API Mappings Reference

  • Helper and Math Libraries

  • Migration Patterns

  • Migration Guide

Migration Overview

Key differences from Google Maps:

AspectGoogle Maps SDKAmazon Location Service
Drop-in SDK❌ Not availableDirect AWS SDK migration required
Map renderingGoogle Maps rendererMapLibre Native Android
API styleCallback/listener-basedKotlin coroutines / suspend functions
CoordinatesLatLng(lat, lng)listOf(lng, lat) - GeoJSON order
AuthenticationAPI Key in manifestAWS API Key or Cognito credentials
SDK packagescom.google.android.gms.mapsaws.sdk.kotlin.services.*

Migration timeline: Expect 1-2 weeks for a typical app with maps, places, and routing features.

No migration SDK available - Unlike JavaScript, there is no drop-in replacement for Android. You'll need to refactor your Google Maps code to use Amazon Location APIs directly.

Setup and Dependencies

Remove Google Maps Dependencies

In your app-level build.gradle.kts:

// Remove Google Maps dependencies
dependencies {
    // ❌ Remove these
    // implementation("com.google.android.gms:play-services-maps:18.2.0")
    // implementation("com.google.android.libraries.places:places:3.3.0")

    // ✅ Keep: FusedLocationProviderClient (device location) still comes from this package
    implementation("com.google.android.gms:play-services-location:21.0.1")
}
Add Amazon Location Dependencies

Add AWS SDK for Kotlin and MapLibre:

dependencies {
    // MapLibre for map display
    implementation("org.maplibre.gl:android-sdk:13.1.0")
    // Annotation plugin for markers/symbols (SymbolManager, SymbolOptions).
    // 4.0.0 is built against SDK 13.x. Plugin versions are numbered independently
    // of the SDK, so check its release notes when bumping android-sdk.
    implementation("org.maplibre.gl:android-plugin-annotation:4.0.0")

    // AWS SDK for Kotlin - add only what you need
    implementation("aws.sdk.kotlin:geoplaces:1.8.+")  // Places, Geocoding
    implementation("aws.sdk.kotlin:georoutes:1.8.+")  // Routing
    implementation("aws.sdk.kotlin:geomaps:1.8.+")    // Static maps
    implementation("aws.sdk.kotlin:location:1.8.+")   // Geofencing, Tracking

    // For authentication
    implementation("aws.sdk.kotlin:cognitoidentity:1.8.+")

    // Coroutines (required for AWS SDK)
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
}

In your project-level build.gradle.kts, ensure the standard repositories are present:

allprojects {
    repositories {
        google()
        mavenCentral() // MapLibre (org.maplibre.gl:android-sdk) is published here
    }
}

Note: MapLibre is available on Maven Central — no token-gated Mapbox repository is required. (The api.mapbox.com Maven repo is only needed for Mapbox's own proprietary SDK, not for MapLibre.)

Note: MapLibre is the open-source fork of Mapbox GL Native and is the recommended way to display maps with Amazon Location Service on Android.

Update AndroidManifest.xml

Remove Google Maps API key:

<!-- Remove this -->
<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="YOUR_GOOGLE_API_KEY"/>

Add permissions (if not already present):

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

Authentication

Amazon Location Service supports API Key and Cognito authentication.

Create a credential provider:

An Amazon Location API key is not an IAM access-key pair, so it must not be passed as a SigV4 access key. Use the Amazon Location Auth SDK's AuthHelper.withApiKey, which configures the client to send the key correctly (and attaches X-Android-Package / X-Android-Cert headers for app-restricted keys).

import android.content.Context
import software.amazon.location.auth.AuthHelper
import aws.sdk.kotlin.services.geoplaces.GeoPlacesClient
import aws.sdk.kotlin.services.georoutes.GeoRoutesClient

class AmazonLocationAuth {
    companion object {
        private const val API_KEY = "YOUR_AMAZON_LOCATION_API_KEY"
        private const val REGION = "us-west-2"

        // Create a Places client using the Amazon Location Auth SDK
        suspend fun createPlacesClient(context: Context): GeoPlacesClient {
            val authHelper = AuthHelper.withApiKey(API_KEY, REGION, context)
            return GeoPlacesClient(authHelper.getGeoPlacesClientConfig())
        }

        // Create a Routes client using the Amazon Location Auth SDK
        suspend fun createRoutesClient(context: Context): GeoRoutesClient {
            val authHelper = AuthHelper.withApiKey(API_KEY, REGION, context)
            return GeoRoutesClient(authHelper.getGeoRoutesClientConfig())
        }
    }
}

Add the Auth SDK dependency: implementation("software.amazon.location:auth:<version>").

Usage:

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MyActivity : AppCompatActivity() {
    private val scope = CoroutineScope(Dispatchers.Main)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        scope.launch {
            val placesClient = AmazonLocationAuth.createPlacesClient(applicationContext)
            // Use client for API calls
        }
    }
}
Cognito Authentication (Required for Geofencing, Tracking)
import aws.sdk.kotlin.services.cognitoidentity.CognitoIdentityClient
import aws.sdk.kotlin.services.cognitoidentity.model.GetCredentialsForIdentityRequest
import aws.sdk.kotlin.services.cognitoidentity.model.GetIdRequest
import aws.smithy.kotlin.runtime.auth.awscredentials.Credentials

suspend fun getCognitoCredentials(identityPoolId: String): Credentials {
    val cognitoClient = CognitoIdentityClient {
        region = "us-west-2"
    }

    // Get identity ID
    val getIdResponse = cognitoClient.getId(GetIdRequest {
        this.identityPoolId = identityPoolId
    })

    // Get temporary credentials
    val credentialsResponse = cognitoClient.getCredentialsForIdentity(
        GetCredentialsForIdentityRequest {
            identityId = getIdResponse.identityId
        }
    )

    return Credentials.invoke(
        accessKeyId = credentialsResponse.credentials?.accessKeyId ?: "",
        secretAccessKey = credentialsResponse.credentials?.secretKey ?: "",
        sessionToken = credentialsResponse.credentials?.sessionToken
    )
}

API Mappings Reference

Places API
Google Maps AndroidAmazon Location AndroidMigration Notes
PlacesClient.findCurrentPlace()SearchNearbyCommandUse device location with SearchNearby
PlacesClient.fetchPlace()GetPlaceCommandFetch place details by PlaceId
PlacesClient.findAutocompletePredictions()AutocompleteCommandAddress autocomplete
N/A (use Autocomplete widget)SuggestCommandPlace name suggestions

Example - Place Search:

// Google Maps (Before)
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest
import com.google.android.libraries.places.api.net.PlacesClient

val placesClient = Places.createClient(context)
val placeFields = listOf(Place.Field.NAME, Place.Field.LAT_LNG)
val request = FindCurrentPlaceRequest.newInstance(placeFields)

placesClient.findCurrentPlace(request).addOnSuccessListener { response ->
    for (placeLikelihood in response.placeLikelihoods) {
        val place = placeLikelihood.place
        Log.i(TAG, "Place: ${place.name}, ${place.latLng}")
    }
}

// Amazon Location (After)
import aws.sdk.kotlin.services.geoplaces.GeoPlacesClient
import aws.sdk.kotlin.services.geoplaces.model.SearchNearbyRequest

val placesClient = AmazonLocationAuth.createPlacesClient(applicationContext)

// Assume you have the device location
val deviceLocation = listOf(-97.7431, 30.2747) // [lng, lat]

val response = placesClient.searchNearby(SearchNearbyRequest {
    queryPosition = deviceLocation
    maxResults = 20
})

response.resultItems?.forEach { place ->
    Log.i(TAG, "Place: ${place.title}, ${place.position}")
}
Geocoding API
Google Maps AndroidAmazon Location AndroidMigration Notes
Geocoder.getFromLocationName()GeocodeCommandForward geocoding (address → coordinates)
Geocoder.getFromLocation()ReverseGeocodeCommandReverse geocoding (coordinates → address)

Example - Geocoding:

// Google Maps (Before)
import android.location.Geocoder
import android.location.Address

val geocoder = Geocoder(context)
val addresses = geocoder.getFromLocationName("Austin, TX", 1)
if (addresses.isNotEmpty()) {
    val location = addresses[0]
    Log.i(TAG, "Lat: ${location.latitude}, Lng: ${location.longitude}")
}

// Amazon Location (After)
import aws.sdk.kotlin.services.geoplaces.model.GeocodeRequest

val response = placesClient.geocode(GeocodeRequest {
    queryText = "Austin, TX"
    maxResults = 1
})

response.resultItems?.firstOrNull()?.let { result ->
    val (lng, lat) = result.position ?: return@let
    Log.i(TAG, "Lat: $lat, Lng: $lng")
}
Directions/Routing API
Google Maps AndroidAmazon Location AndroidMigration Notes
DirectionsApi.newRequest()CalculateRoutesCommandRoute calculation
DistanceMatrixApi.newRequest()CalculateRouteMatrixCommandMany-to-many distances

Example - Directions:

// Google Maps (Before)
import com.google.maps.DirectionsApi
import com.google.maps.GeoApiContext
import com.google.maps.model.TravelMode

val context = GeoApiContext.Builder()
    .apiKey("YOUR_API_KEY")
    .build()

val directions = DirectionsApi.newRequest(context)
    .origin("Austin, TX")
    .destination("Dallas, TX")
    .mode(TravelMode.DRIVING)
    .await()

Log.i(TAG, "Distance: ${directions.routes[0].legs[0].distance}")

// Amazon Location (After)
import aws.sdk.kotlin.services.georoutes.GeoRoutesClient
import aws.sdk.kotlin.services.georoutes.model.CalculateRoutesRequest

val routesClient = AmazonLocationAuth.createRoutesClient(applicationContext)

val response = routesClient.calculateRoutes(CalculateRoutesRequest {
    origin = listOf(-97.7431, 30.2747) // Austin [lng, lat]
    destination = listOf(-96.7970, 32.7767) // Dallas [lng, lat]
    travelMode = aws.sdk.kotlin.services.georoutes.model.RouteTravelMode.Car
    legAdditionalFeatures = listOf(aws.sdk.kotlin.services.georoutes.model.RouteLegAdditionalFeature.Summary)
})

response.routes?.firstOrNull()?.let { route ->
    val leg = route.legs?.firstOrNull()
    val distance = leg?.vehicleLegDetails?.summary?.overview?.distance
    Log.i(TAG, "Distance: $distance meters")
}
Map Display
Google Maps AndroidAmazon Location AndroidMigration Notes
MapFragment / MapViewMapView (MapLibre)Different rendering engine
GoogleMap.addMarker()SymbolManager.create()MapLibre marker API
GoogleMap.addPolyline()Add LineLayerGeoJSON-based rendering
GoogleMap.moveCamera()MapLibreMap.moveCamera()Similar camera API

Example - Display Map:

// Google Maps (Before)
import com.google.android.gms.maps.MapFragment
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

class MapActivity : AppCompatActivity(), OnMapReadyCallback {
    override fun onMapReady(googleMap: GoogleMap) {
        val austin = LatLng(30.2747, -97.7431)
        googleMap.addMarker(
            MarkerOptions()
                .position(austin)
                .title("Austin")
        )
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(austin, 10f))
    }
}

// Amazon Location (After)
import org.maplibre.android.MapLibre
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.plugins.annotation.SymbolManager
import org.maplibre.android.plugins.annotation.SymbolOptions

class MapActivity : AppCompatActivity() {
    private lateinit var mapView: MapView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        MapLibre.getInstance(this)
        mapView = MapView(this)
        setContentView(mapView)

        mapView.getMapAsync { map ->
            // Get Amazon Location map style
            val styleUrl = "https://maps.geo.us-west-2.amazonaws.com/v2/styles/Standard/descriptor?key=$API_KEY"

            map.setStyle(Style.Builder().fromUri(styleUrl)) { style ->
                // Add marker
                val symbolManager = SymbolManager(mapView, map, style)
                symbolManager.create(
                    SymbolOptions()
                        .withLatLng(LatLng(30.2747, -97.7431))
                        .withTextField("Austin")
                )

                // Move camera
                map.cameraPosition = CameraPosition.Builder()
                    .target(LatLng(30.2747, -97.7431))
                    .zoom(10.0)
                    .build()
            }
        }
    }
}

Helper and Math Libraries

Google Maps SDK includes utility classes for geometry operations. For Amazon Location, use these alternatives:

Polyline Encoding/Decoding
Google Maps AndroidAmazon Location AlternativePackage
PolyUtil.encode()Polyline.encodeFromLngLatArrayaws-geospatial/polyline
PolyUtil.decode()Polyline.decodeToLineStringFeatureaws-geospatial/polyline

Example - Polyline Decoding (using aws-geospatial/polyline):

Amazon Location routing returns FlexiblePolyline, not Google's Polyline5. A hand-rolled / 1e5 decoder assumes Polyline5 precision and produces wrong coordinates. Use the official aws-geospatial/polyline library, which decodes FlexiblePolyline directly into MapLibre-ready GeoJSON.

Add the dependency: implementation("software.amazon.location:polyline:0.1.0").

// Google Maps (Before)
import com.google.maps.android.PolyUtil

val points = PolyUtil.decode(encodedPolyline)

// Amazon Location (After) - official library
import software.amazon.location.polyline.Polyline

// Decode the FlexiblePolyline returned by Amazon Location routing
val feature = Polyline.decodeToLineStringFeature(encodedPolyline)
// `feature` is a GeoJSON LineString Feature, ready to add to a MapLibre source
Geometry Operations
Google Maps AndroidAmazon Location AlternativeApproach
SphericalUtil.computeDistanceBetween()Use Haversine formulaImplement or use library
PolyUtil.containsLocation()Use point-in-polygon algorithmImplement or use library
PolyUtil.isLocationOnPath()Use point-to-line distanceImplement or use library

Example - Distance Calculation:

// Google Maps (Before)
import com.google.maps.android.SphericalUtil
import com.google.android.gms.maps.model.LatLng

val distance = SphericalUtil.computeDistanceBetween(
    LatLng(30.2747, -97.7431),
    LatLng(32.7767, -96.7970)
)

// Amazon Location (After) - Haversine implementation
object GeoUtils {
    private const val EARTH_RADIUS = 6371000.0 // meters

    fun computeDistanceBetween(
        lat1: Double, lng1: Double,
        lat2: Double, lng2: Double
    ): Double {
        val dLat = Math.toRadians(lat2 - lat1)
        val dLng = Math.toRadians(lng2 - lng1)

        val a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                Math.sin(dLng / 2) * Math.sin(dLng / 2)

        val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
        return EARTH_RADIUS * c
    }
}

val distance = GeoUtils.computeDistanceBetween(
    30.2747, -97.7431,
    32.7767, -96.7970
)

For complex geometry operations, consider using:

  • Turf for Android - Port of Turf.js for Android

  • Implement algorithms based on standard formulas (Haversine, point-in-polygon, etc.)

Coordinate System Differences

Critical: Google Maps uses LatLng(lat, lng) while Amazon Location uses listOf(lng, lat) (GeoJSON order).

// Google Maps
val location = LatLng(30.2747, -97.7431) // lat, lng

// Amazon Location
val position = listOf(-97.7431, 30.2747) // lng, lat

// Converting between them
fun LatLng.toAmazonLocation(): List<Double> = listOf(longitude, latitude)
fun List<Double>.toLatLng(): LatLng = LatLng(this[1], this[0])

Migration Patterns

Pattern 1: Places Autocomplete

Google Maps:

import com.google.android.libraries.places.widget.AutocompleteSupportFragment

val autocompleteFragment = supportFragmentManager.findFragmentById(R.id.autocomplete_fragment)
    as AutocompleteSupportFragment

autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
    override fun onPlaceSelected(place: Place) {
        Log.i(TAG, "Place: ${place.name}, ${place.latLng}")
    }

    override fun onError(status: Status) {
        Log.e(TAG, "Error: $status")
    }
})

Amazon Location:

import aws.sdk.kotlin.services.geoplaces.model.AutocompleteRequest
import kotlinx.coroutines.launch

// In your custom autocomplete UI
searchEditText.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable?) {
        val query = s.toString()
        if (query.length < 3) return

        scope.launch {
            val response = placesClient.autocomplete(AutocompleteRequest {
                queryText = query
                maxResults = 5
            })

            response.resultItems?.let { suggestions ->
                updateSuggestionsList(suggestions)
            }
        }
    }
})

// When user selects a suggestion
fun onSuggestionSelected(placeId: String) {
    scope.launch {
        val response = placesClient.getPlace(GetPlaceRequest {
            this.placeId = placeId
        })

        response.position?.let { position ->
            val (lng, lat) = position
            Log.i(TAG, "Selected: Lat $lat, Lng $lng")
        }
    }
}
Pattern 2: Current Location on Map

Google Maps:

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

val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

fusedLocationClient.lastLocation.addOnSuccessListener { location ->
    if (location != null) {
        val currentLatLng = LatLng(location.latitude, location.longitude)
        googleMap.addMarker(MarkerOptions().position(currentLatLng))
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15f))
    }
}

Amazon Location:

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

// Still use FusedLocationProviderClient for device location
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

fusedLocationClient.lastLocation.addOnSuccessListener { location ->
    if (location != null) {
        val currentLatLng = LatLng(location.latitude, location.longitude)

        // Use MapLibre to display
        mapLibreMap.cameraPosition = CameraPosition.Builder()
            .target(currentLatLng)
            .zoom(15.0)
            .build()

        symbolManager.create(
            SymbolOptions()
                .withLatLng(currentLatLng)
                .withIconImage("marker-icon")
        )
    }
}
Pattern 3: Route Display on Map

Google Maps:

import com.google.android.gms.maps.model.PolylineOptions

val polylineOptions = PolylineOptions()
    .addAll(decodedPath)
    .color(Color.BLUE)
    .width(5f)

googleMap.addPolyline(polylineOptions)

Amazon Location:

import org.maplibre.android.style.layers.LineLayer
import org.maplibre.android.style.layers.PropertyFactory.*
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.geojson.Feature
import org.maplibre.geojson.LineString
import org.maplibre.geojson.Point

// Convert route to GeoJSON
val coordinates = routePoints.map { Point.fromLngLat(it.second, it.first) }
val lineString = LineString.fromLngLats(coordinates)
val feature = Feature.fromGeometry(lineString)

// Add source and layer
val source = GeoJsonSource("route-source", feature)
style.addSource(source)

val lineLayer = LineLayer("route-layer", "route-source").withProperties(
    lineColor(Color.BLUE),
    lineWidth(5f)
)
style.addLayer(lineLayer)

Migration Guide

Official AWS Migration Guide
AWS SDK Documentation
MapLibre Documentation

Best Practices

Coroutines and Lifecycle
  • Use lifecycleScope or viewModelScope for API calls

  • Cancel coroutines when Activity/Fragment is destroyed

  • Handle errors with try-catch blocks

lifecycleScope.launch {
    try {
        val response = placesClient.geocode(/* ... */)
        // Handle response
    } catch (e: Exception) {
        Log.e(TAG, "Geocoding failed", e)
        // Show error to user
    }
}
Coordinate Conversion
  • Create extension functions for easy conversion between Google and Amazon Location formats

  • Always verify coordinate order when debugging

fun LatLng.toGeoJsonPosition(): List<Double> = listOf(longitude, latitude)
fun List<Double>.toLatLng(): LatLng = LatLng(this[1], this[0])
Error Handling
  • Implement proper error handling for network failures

  • Show user-friendly error messages

  • Implement retry logic for transient failures

Testing
  • Test with different device locations

  • Verify coordinate conversions

  • Test offline behavior

Troubleshooting

Common Issues

Issue: Map not displaying

  • Cause: Incorrect API key or style URL

  • Fix: Verify API key has Maps permissions, check style URL format

Issue: Coordinates in wrong location

  • Cause: Lat/Lng order swapped

  • Fix: Remember Amazon Location uses [lng, lat] order

Issue: Autocomplete not working

  • Cause: Need to build custom UI, no widget available

  • Fix: Implement custom autocomplete UI with EditText and RecyclerView

Issue: Build errors after adding dependencies

  • Cause: Dependency conflicts or missing repositories

  • Fix: Verify google() and mavenCentral() are present in your repositories, check dependency versions

Getting Help

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs an API key

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
aws-geospatial
Publisher
AWS Labs (Official)
Distributed by
AWS Labs
Source
awslabs/agent-plugins · plugins/amazon-location-service/skills/amazon-location-service · commit fbefb37
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • NOTICE (added by AutoGineer from NOTICE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by aws-geospatial or AWS Labs.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download amazon-location-service.zip