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://mp-staging.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-ios.md

Google Maps Migration (iOS)

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

Migrate iOS applications from Google Maps SDK for iOS to Amazon Location Service using the AWS SDK for Swift 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 iOS
API styleDelegate/completion-basedSwift async/await
CoordinatesCLLocationCoordinate2D(latitude:longitude:)[longitude, latitude] - GeoJSON order
AuthenticationAPI Key in AppDelegateAWS API Key or Cognito credentials
SDK frameworksGoogleMaps, GooglePlacesAWSGeoPlaces, AWSGeoRoutes, etc.

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 iOS. You'll need to refactor your Google Maps code to use Amazon Location APIs directly.

Setup and Dependencies

Remove Google Maps Dependencies

In your Podfile:

# Remove Google Maps pods
# pod 'GoogleMaps'
# pod 'GooglePlaces'
# pod 'GoogleMapsUtils'

Or if using Swift Package Manager, remove Google Maps packages from Xcode:

  • File → Swift Packages → Remove Package

Add Amazon Location Dependencies

Using Swift Package Manager (Recommended):

  1. In Xcode: File → Add Packages...

  2. Add Amazon Location Mobile Auth SDK:

    • URL: https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios

    • Select product: AmazonLocationiOSAuthSDK

  3. Add AWS SDK for Swift:

    • URL: https://github.com/awslabs/aws-sdk-swift

    • Select products: AWSGeoPlaces, AWSGeoRoutes, AWSGeoMaps, AWSLocation

  4. Add MapLibre:

    • URL: https://github.com/maplibre/maplibre-gl-native-distribution

Note: Amazon Location's Swift packages (AWSGeoPlaces, AWSGeoRoutes, AWSGeoMaps, AWSLocation, and AmazonLocationiOSAuthSDK) are distributed via Swift Package Manager only — they are not published to CocoaPods. Use SPM as shown above.

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

Update AppDelegate and Info.plist

Remove the Google Maps API key setup: Google Maps for iOS registers its API key with a GMSServices.provideAPIKey(...) call in AppDelegate.swift — not via an Info.plist entry. Remove that call:

// Remove this from AppDelegate.swift
import GoogleMaps

func application(_ application: UIApplication,
                didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    GMSServices.provideAPIKey("YOUR_GOOGLE_API_KEY")  // ← remove this line
    return true
}

Add location permissions to Info.plist (if not already present):

<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to show nearby places</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We need your location for tracking features</string>

Authentication

Amazon Location Service supports API Key and Cognito authentication. Use the Amazon Location Mobile Auth SDK for simplified authentication setup.

Using the Amazon Location Mobile Auth SDK:

import AmazonLocationiOSAuthSDK
import AWSGeoPlaces

class AmazonLocationAuth {
    static let apiKey = "YOUR_AMAZON_LOCATION_API_KEY"
    static let region = "us-west-2"

    // Create an authentication helper using your API key and region
    static func createAuthHelper() async throws -> AuthHelper {
        return try await AuthHelper.withApiKey(apiKey: apiKey, region: region)
    }

    // Create a Places client
    static func createPlacesClient() async throws -> GeoPlacesClient {
        let authHelper = try await createAuthHelper()
        return GeoPlacesClient(config: authHelper.getGeoPlacesClientConfig())
    }

    // Create a Routes client
    static func createRoutesClient() async throws -> GeoRoutesClient {
        let authHelper = try await createAuthHelper()
        return GeoRoutesClient(config: authHelper.getGeoRoutesClientConfig())
    }

    // Create a Location client (for geofencing/tracking)
    static func createLocationClient() async throws -> LocationClient {
        let authHelper = try await createAuthHelper()
        return LocationClient(config: authHelper.getLocationClientConfig())
    }
}

Usage:

import AWSGeoPlaces

class PlacesViewController: UIViewController {
    var placesClient: GeoPlacesClient?

    override func viewDidLoad() {
        super.viewDidLoad()

        Task {
            // Simple one-line client creation
            placesClient = try await AmazonLocationAuth.createPlacesClient()

            // Use client for API calls
            let input = SearchTextInput(
                biasPosition: [-97.7431, 30.2747],
                queryText: "coffee shops"
            )
            let response = try await placesClient?.searchText(input: input)
        }
    }
}
Cognito Authentication (Required for Geofencing, Tracking)

Using the Amazon Location Mobile Auth SDK with Cognito:

import AmazonLocationiOSAuthSDK
import AWSLocation

func createLocationClientWithCognito() async throws -> LocationClient {
    let identityPoolId = "YOUR_IDENTITY_POOL_ID"

    // Create authentication helper using Cognito credentials
    let authHelper = try await AuthHelper.withIdentityPoolId(identityPoolId: identityPoolId)

    // Configure the LocationClient to use credentials from Cognito
    return LocationClient(config: authHelper.getLocationClientConfig())
}

Key benefits of using the Auth SDK:

  • ✅ Simplified API Key and Cognito authentication

  • ✅ Automatic credential management

  • ✅ Pre-configured client configurations for all Amazon Location services

  • ✅ Handles region and endpoint configuration automatically

API Mappings Reference

Places API
Google Maps iOSAmazon Location iOSMigration Notes
GMSPlacesClient.currentPlace()searchNearby(input:)Use device location with SearchNearby
GMSPlacesClient.fetchPlace()getPlace(input:)Fetch place details by PlaceId
GMSAutocompleteViewControllerautocomplete(input:) + custom UIAddress autocomplete
GMSPlacesClient.findAutocompletePredictions()autocomplete(input:)Programmatic autocomplete

Example - Place Search:

// Google Maps (Before)
import GooglePlaces

let placesClient = GMSPlacesClient.shared()
let filter = GMSAutocompleteFilter()
filter.types = ["restaurant"]

placesClient.currentPlace { (placeLikelihoodList, error) in
    if let error = error {
        print("Error: \(error)")
        return
    }

    guard let placeLikelihoods = placeLikelihoodList?.likelihoods else {
        return
    }

    for likelihood in placeLikelihoods {
        let place = likelihood.place
        print("Place: \(place.name), \(place.coordinate)")
    }
}

// Amazon Location (After)
import AmazonLocationiOSAuthSDK
import AWSGeoPlaces
import CoreLocation

let placesClient = try await AmazonLocationAuth.createPlacesClient()

// Assume you have device location
let deviceLocation: [Double] = [-97.7431, 30.2747] // [lng, lat]

let input = SearchNearbyInput(
    filter: GeoPlacesClientTypes.SearchNearbyFilter(
        includeCategories: ["restaurant"]
    ),
    maxResults: 20,
    queryPosition: deviceLocation
)

let response = try await placesClient.searchNearby(input: input)

response.resultItems?.forEach { place in
    print("Place: \(place.title ?? ""), \(place.position ?? [])")
}
Geocoding API
Google Maps iOSAmazon Location iOSMigration Notes
Google Geocoding web API (HTTP)geocode(input:)Forward geocoding — Google's iOS SDK has no forward geocoder, so you call the web service
GMSGeocoder.reverseGeocodeCoordinate()reverseGeocode(input:)Reverse geocoding (coordinates → address)

Example - Geocoding:

// Google Maps (Before)
// Google's iOS Maps SDK does NOT support forward geocoding; call the web service:
let apiKey = "YOUR_GOOGLE_API_KEY"
let query = "Austin, TX".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(query)&key=\(apiKey)")!
URLSession.shared.dataTask(with: url) { data, _, error in
    guard let data = data else { return }
    let result = try? JSONDecoder().decode(GeocodeResponse.self, from: data)
    // result.results[0].geometry.location.lat / .lng
}.resume()

// Amazon Location (After)
import AmazonLocationiOSAuthSDK
import AWSGeoPlaces

let placesClient = try await AmazonLocationAuth.createPlacesClient()

let input = GeocodeInput(
    maxResults: 1,
    queryText: "Austin, TX"
)

let response = try await placesClient.geocode(input: input)

if let result = response.resultItems?.first,
   let position = result.position {
    let lng = position[0]
    let lat = position[1]
    print("Lat: \(lat), Lng: \(lng)")
}
Directions/Routing API
Google Maps iOSAmazon Location iOSMigration Notes
Directions API (REST web service)calculateRoutes(input:)Google has no native iOS class; call via URLSession
Distance Matrix API (REST web service)calculateRouteMatrix(input:)Google has no native iOS class; call via URLSession

Example - Directions:

// Google Maps (Before)
// Directions is a Google web service (REST) API — there is no native iOS SDK
// class for it, so it is called over HTTPS with URLSession.
import Foundation

let origin = "Austin, TX"
let destination = "Dallas, TX"
let apiKey = "YOUR_GOOGLE_API_KEY"

var components = URLComponents(string: "https://maps.googleapis.com/maps/api/directions/json")!
components.queryItems = [
    URLQueryItem(name: "origin", value: origin),
    URLQueryItem(name: "destination", value: destination),
    URLQueryItem(name: "key", value: apiKey),
]

let (data, _) = try await URLSession.shared.data(from: components.url!)
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]

if let routes = json?["routes"] as? [[String: Any]],
   let leg = (routes.first?["legs"] as? [[String: Any]])?.first,
   let distance = (leg["distance"] as? [String: Any])?["value"] as? Int {
    print("Distance: \(distance)")
}

// Amazon Location (After)
import AmazonLocationiOSAuthSDK
import AWSGeoRoutes

let routesClient = try await AmazonLocationAuth.createRoutesClient()

let input = CalculateRoutesInput(
    destination: [-96.7970, 32.7767], // Dallas [lng, lat]
    legAdditionalFeatures: [.summary],
    origin: [-97.7431, 30.2747], // Austin [lng, lat]
    travelMode: .car
)

let response = try await routesClient.calculateRoutes(input: input)

if let route = response.routes?.first,
   let leg = route.legs?.first,
   let distance = leg.vehicleLegDetails?.summary?.overview?.distance {
    print("Distance: \(distance) meters")
}
Map Display
Google Maps iOSAmazon Location iOSMigration Notes
GMSMapViewMLNMapView (MapLibre)Different rendering engine
GMSMarkerMLNPointAnnotationMapLibre annotation API
GMSPolylineMLNPolylineSimilar polyline API
GMSCameraPositionMLNMapCameraSimilar camera API

Example - Display Map:

// Google Maps (Before)
import GoogleMaps

class MapViewController: UIViewController {
    var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let camera = GMSCameraPosition.camera(
            withLatitude: 30.2747,
            longitude: -97.7431,
            zoom: 10
        )
        mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
        view.addSubview(mapView)

        // Add marker
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: 30.2747, longitude: -97.7431)
        marker.title = "Austin"
        marker.map = mapView
    }
}

// Amazon Location (After)
import MapLibre

class MapViewController: UIViewController {
    var mapView: MLNMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create map with Amazon Location style
        let apiKey = AmazonLocationAuth.apiKey
        let region = AmazonLocationAuth.region
        let styleURL = URL(string: "https://maps.geo.\(region).amazonaws.com/v2/styles/Standard/descriptor?key=\(apiKey)")!

        mapView = MLNMapView(frame: view.bounds, styleURL: styleURL)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.setCenter(
            CLLocationCoordinate2D(latitude: 30.2747, longitude: -97.7431),
            zoomLevel: 10,
            animated: false
        )
        view.addSubview(mapView)

        // Add marker
        let annotation = MLNPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: 30.2747, longitude: -97.7431)
        annotation.title = "Austin"
        mapView.addAnnotation(annotation)
    }
}

Helper and Math Libraries

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

Polyline Encoding/Decoding
Google Maps iOSAmazon Location AlternativePackage
GMSPath(fromEncodedPath:)Polyline.decodeToLineStringFeatureaws-geospatial/polyline
GMSPath.encodedPath()Polyline.encodeFromLngLatArrayaws-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 via Swift Package Manager: https://github.com/aws-geospatial/polyline/

// Google Maps (Before)
import GoogleMaps

let path = GMSPath(fromEncodedPath: encodedPolyline)

// Amazon Location (After) - official library
import Polyline

// Decode the FlexiblePolyline returned by Amazon Location routing
let feature = Polyline.decodeToLineStringFeature(encodedPolyline)
// `feature` is a GeoJSON LineString Feature, ready to add to a MapLibre source
Geometry Operations
Google Maps iOSAmazon Location AlternativeApproach
GMSGeometryDistance()Use Haversine formulaImplement calculation
GMSGeometryContainsLocation()Point-in-polygon algorithmImplement or use library
GMSGeometryIsLocationOnPath()Point-to-line distanceImplement calculation

Example - Distance Calculation:

// Google Maps (Before)
import GoogleMaps

let from = CLLocationCoordinate2D(latitude: 30.2747, longitude: -97.7431)
let to = CLLocationCoordinate2D(latitude: 32.7767, longitude: -96.7970)
let distance = GMSGeometryDistance(from, to)

// Amazon Location (After) - Haversine implementation
import CoreLocation

extension CLLocationCoordinate2D {
    func distance(to: CLLocationCoordinate2D) -> Double {
        let earthRadius = 6371000.0 // meters

        let lat1 = self.latitude * .pi / 180
        let lat2 = to.latitude * .pi / 180
        let dLat = (to.latitude - self.latitude) * .pi / 180
        let dLng = (to.longitude - self.longitude) * .pi / 180

        let a = sin(dLat / 2) * sin(dLat / 2) +
                cos(lat1) * cos(lat2) *
                sin(dLng / 2) * sin(dLng / 2)

        let c = 2 * atan2(sqrt(a), sqrt(1 - a))
        return earthRadius * c
    }
}

let from = CLLocationCoordinate2D(latitude: 30.2747, longitude: -97.7431)
let to = CLLocationCoordinate2D(latitude: 32.7767, longitude: -96.7970)
let distance = from.distance(to: to)

For complex geometry operations, consider:

  • Implementing standard algorithms (Haversine, point-in-polygon)

  • Using Turf Swift - Port of Turf.js for iOS

Coordinate System Differences

Critical: Google Maps uses CLLocationCoordinate2D(latitude:longitude:) while Amazon Location uses [longitude, latitude] (GeoJSON order).

// Google Maps
let coordinate = CLLocationCoordinate2D(latitude: 30.2747, longitude: -97.7431)

// Amazon Location
let position: [Double] = [-97.7431, 30.2747] // [lng, lat]

// Converting between them
extension CLLocationCoordinate2D {
    func toGeoJsonPosition() -> [Double] {
        return [longitude, latitude]
    }

    init(geoJsonPosition: [Double]) {
        self.init(latitude: geoJsonPosition[1], longitude: geoJsonPosition[0])
    }
}

Migration Patterns

Pattern 1: Places Autocomplete

Google Maps:

import GooglePlaces

let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self

present(autocompleteController, animated: true, completion: nil)

// GMSAutocompleteViewControllerDelegate
func viewController(_ viewController: GMSAutocompleteViewController,
                   didAutocompleteWith place: GMSPlace) {
    print("Place: \(place.name), \(place.coordinate)")
    dismiss(animated: true, completion: nil)
}

Amazon Location:

import AWSGeoPlaces
import UIKit

// Custom autocomplete UI
class AutocompleteViewController: UIViewController, UISearchBarDelegate {
    let searchBar = UISearchBar()
    let tableView = UITableView()
    var suggestions: [GeoPlacesClientTypes.AutocompleteResultItem] = []

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        guard searchText.count >= 3 else { return }

        Task {
            let input = AutocompleteInput(
                maxResults: 5,
                queryText: searchText
            )

            let response = try await placesClient.autocomplete(input: input)
            suggestions = response.resultItems ?? []
            tableView.reloadData()
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let suggestion = suggestions[indexPath.row]

        Task {
            if let placeId = suggestion.placeId {
                let input = GetPlaceInput(placeId: placeId)
                let response = try await placesClient.getPlace(input: input)

                if let position = response.position {
                    let coordinate = CLLocationCoordinate2D(geoJsonPosition: position)
                    print("Selected: \(coordinate)")
                }
            }
        }
    }
}
Pattern 2: Current Location on Map

Google Maps:

import GoogleMaps
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate {
    let locationManager = CLLocationManager()
    var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager,
                        didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else { return }

        let camera = GMSCameraPosition.camera(
            withTarget: location.coordinate,
            zoom: 15
        )
        mapView.camera = camera

        let marker = GMSMarker(position: location.coordinate)
        marker.map = mapView

        locationManager.stopUpdatingLocation()
    }
}

Amazon Location:

import MapLibre
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate {
    let locationManager = CLLocationManager()
    var mapView: MLNMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let styleURL = URL(string: "https://maps.geo.us-west-2.amazonaws.com/v2/styles/Standard/descriptor?key=\(apiKey)")!
        mapView = MLNMapView(frame: view.bounds, styleURL: styleURL)
        view.addSubview(mapView)

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager,
                        didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else { return }

        mapView.setCenter(
            location.coordinate,
            zoomLevel: 15,
            animated: true
        )

        let annotation = MLNPointAnnotation()
        annotation.coordinate = location.coordinate
        mapView.addAnnotation(annotation)

        locationManager.stopUpdatingLocation()
    }
}
Pattern 3: Route Display on Map

Google Maps:

import GoogleMaps

let path = GMSMutablePath()
routeCoordinates.forEach { path.add($0) }

let polyline = GMSPolyline(path: path)
polyline.strokeColor = .blue
polyline.strokeWidth = 5
polyline.map = mapView

Amazon Location:

import MapLibre

// Create polyline from coordinates
let polyline = MLNPolyline(coordinates: routeCoordinates, count: UInt(routeCoordinates.count))

// Add polyline to map
mapView.addAnnotation(polyline)

// Customize appearance using MLNMapViewDelegate
func mapView(_ mapView: MLNMapView, strokeColorForShapeAnnotation annotation: MLNShape) -> UIColor {
    return .blue
}

func mapView(_ mapView: MLNMapView, lineWidthForPolylineAnnotation annotation: MLNPolyline) -> CGFloat {
    return 5
}

Migration Guide

Official AWS Migration Guide
AWS SDK Documentation
MapLibre Documentation

Best Practices

Swift Concurrency
  • Use async/await for API calls

  • Handle errors with do-catch blocks

  • Use Task for launching asynchronous work from synchronous contexts

Task {
    do {
        let response = try await placesClient.geocode(input: input)
        // Handle response
    } catch {
        print("Geocoding failed: \(error)")
        // Show error to user
    }
}
Coordinate Conversion
  • Create extension methods for easy conversion

  • Always verify coordinate order when debugging

extension CLLocationCoordinate2D {
    func toGeoJsonPosition() -> [Double] {
        [longitude, latitude]
    }

    init(geoJsonPosition: [Double]) {
        self.init(latitude: geoJsonPosition[1], longitude: geoJsonPosition[0])
    }
}
Memory Management
  • Weak reference delegates to avoid retain cycles

  • Properly manage MapView lifecycle

class MapViewController: UIViewController, MLNMapViewDelegate {
    var mapView: MLNMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self
    }

    deinit {
        mapView.delegate = nil
    }
}
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 UISearchBar and UITableView

Issue: Build errors after adding dependencies

  • Cause: Dependency conflicts or version mismatches

  • Fix: Verify CocoaPods/SPM configuration, check dependency versions

Issue: Async/await not available

  • Cause: Minimum iOS version too low

  • Fix: Set minimum deployment target to iOS 15.0 or higher

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