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/web-javascript.md

Web JavaScript

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

Integrate Amazon Location Service into web applications using the bundled JavaScript client.

Table of Contents

  • Overview

  • Installation

  • Authentication

  • Client Usage

  • Error Handling

  • Best Practices

Overview

The @aws/amazon-location-client package provides a pre-bundled JavaScript SDK for browser applications with:

  • All Amazon Location Service clients (geo-places, geo-routes, geo-maps, location)

  • Authentication helpers for API Keys and Cognito

  • TypeScript type definitions

  • No build step required

npm Package: @aws/amazon-location-client

Installation

Via Bundled Client
<!DOCTYPE html>
<html>
  <head>
    <title>Amazon Location Example</title>
  </head>
  <body>
    <!-- Load bundled client from CDN -->
    <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1"></script>

    <script>
      // All functions available under amazonLocationClient global
      console.log(amazonLocationClient);
    </script>
  </body>
</html>
Via npm (For Modular Applications)

For applications using build tools (webpack, Vite, etc.), install only the AWS SDK clients you need:

# Install only what you need
npm install @aws-sdk/client-geo-places  # For Places, Geocoding
npm install @aws-sdk/client-geo-routes  # For Routing
npm install @aws-sdk/client-geo-maps    # For Maps
npm install @aws-sdk/client-location    # For Geofencing, Tracking
// Example: Import GeoPlacesClient for Places API
import { GeoPlacesClient, GeocodeCommand } from "@aws-sdk/client-geo-places";

Note: The rest of this document focuses on the bundled client. For detailed AWS SDK usage, see the AWS SDK for JavaScript documentation.

Authentication

The bundled client supports three authentication methods:

  1. API Key (Recommended for Maps, Places, Routes)

  2. Cognito Identity Pool (Required for Geofencing, Tracking)

  3. Custom Credential Provider (Advanced/Fallback only)

// Simple API key authentication
const API_KEY = "your-api-key";
const REGION = "us-west-2";

const authHelper = amazonLocationClient.withAPIKey(API_KEY, REGION);

// Use authHelper.getClientConfig() to configure clients
const config = authHelper.getClientConfig();

When to use:

  • ✅ Recommended for Maps, Places, and Routes APIs

  • ✅ Public client-side applications where AWS credentials cannot be exposed

  • ✅ Simpler setup without identity pool configuration

  • ⚠️ Not available for Geofencing and Tracking APIs (use Cognito instead)

Cognito Authentication
// Cognito Identity Pool authentication
const IDENTITY_POOL_ID = "us-west-2:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

const authHelper =
  await amazonLocationClient.withIdentityPoolId(IDENTITY_POOL_ID);

const config = authHelper.getClientConfig();

When to use:

  • ✅ Required for Geofencing and Tracking APIs

  • ✅ Applications with user authentication

  • ✅ When you need per-user authorization or temporary AWS credentials

  • ⚠️ More complex setup than API keys

Custom Credential Provider (Advanced/Fallback)
// Custom credential provider - use only when API Key or Cognito don't meet your needs
import { fromEnv } from "@aws-sdk/credential-providers";

const authHelper = amazonLocationClient.withCredentialProvider(
  fromEnv(), // Or any custom credential provider
  REGION,
);

const config = authHelper.getClientConfig();

When to use:

  • ⚠️ Fallback option only - not recommended over API Key or Cognito

  • Advanced use cases with custom credential providers

  • Static credentials from environment variables

  • Authentication through a separate backend service

  • Only use if specifically needed - prefer API Key for Maps/Places/Routes and Cognito for Geofencing/Tracking

Reference: amazon-location-client-js documentation

Authentication Error Handling
// For Maps, Places, Routes - use API Key
async function initializeAuthForMapsPlacesRoutes() {
  try {
    if (!API_KEY) {
      throw new Error("API key not configured");
    }

    const authHelper = amazonLocationClient.withAPIKey(API_KEY, REGION);
    return authHelper;
  } catch (error) {
    console.error("Authentication failed:", error);
    alert("Failed to initialize API key authentication: " + error.message);
    throw error;
  }
}

// For Geofencing, Tracking - use Cognito
async function initializeAuthForGeofencingTracking() {
  try {
    if (!IDENTITY_POOL_ID) {
      throw new Error("Cognito Identity Pool ID not configured");
    }

    const authHelper =
      await amazonLocationClient.withIdentityPoolId(IDENTITY_POOL_ID);
    return authHelper;
  } catch (error) {
    console.error("Authentication failed:", error);

    if (error.message.includes("Invalid identity pool")) {
      alert(
        "Authentication configuration error. Please check Identity Pool ID.",
      );
    } else if (error.message.includes("credentials")) {
      alert("Failed to obtain credentials. Please try again.");
    } else {
      alert("Authentication failed: " + error.message);
    }

    throw error;
  }
}

// Usage
const authHelper = await initializeAuthForMapsPlacesRoutes();

Client Usage

Standard Pattern

Every Amazon Location API call follows this pattern:

// 1. Create auth helper
const authHelper = amazonLocationClient.withAPIKey(API_KEY, REGION);

// 2. Create service client
const client = new amazonLocationClient.GeoPlacesClient(
  authHelper.getClientConfig(),
);

// 3. Create command with parameters
const command = new amazonLocationClient.places.GeocodeCommand({
  QueryText: "123 Main St, Austin, TX",
});

// 4. Send command and await response
const response = await client.send(command);
console.log(response);
GeoPlacesClient (Places, Geocoding)
const placesClient = new amazonLocationClient.GeoPlacesClient(
  authHelper.getClientConfig(),
);

// Geocode
const geocodeCommand = new amazonLocationClient.places.GeocodeCommand({
  QueryText: "Texas State Capitol, Austin, TX",
  MaxResults: 1,
});
const geocodeResponse = await placesClient.send(geocodeCommand);

// Reverse Geocode
const reverseCommand = new amazonLocationClient.places.ReverseGeocodeCommand({
  QueryPosition: [-97.7431, 30.2747],
  MaxResults: 1,
});
const reverseResponse = await placesClient.send(reverseCommand);

// Search Text
const searchCommand = new amazonLocationClient.places.SearchTextCommand({
  QueryText: "coffee shops",
  MaxResults: 10,
});
const searchResponse = await placesClient.send(searchCommand);

// Search Nearby
const nearbyCommand = new amazonLocationClient.places.SearchNearbyCommand({
  QueryPosition: [-97.7431, 30.2747],
  MaxResults: 10,
});
const nearbyResponse = await placesClient.send(nearbyCommand);

// Autocomplete
const autocompleteCommand = new amazonLocationClient.places.AutocompleteCommand(
  {
    QueryText: "123 Main",
    MaxResults: 5,
  },
);
const autocompleteResponse = await placesClient.send(autocompleteCommand);

// Get Place
const getPlaceCommand = new amazonLocationClient.places.GetPlaceCommand({
  PlaceId: "place-id-from-search",
});
const placeResponse = await placesClient.send(getPlaceCommand);

// Suggest
const suggestCommand = new amazonLocationClient.places.SuggestCommand({
  QueryText: "star",
  MaxResults: 5,
});
const suggestResponse = await placesClient.send(suggestCommand);
GeoRoutesClient (Routing)
const routesClient = new amazonLocationClient.GeoRoutesClient(
  authHelper.getClientConfig(),
);

// Calculate Route
const routeCommand = new amazonLocationClient.routes.CalculateRoutesCommand({
  Origin: [-97.7431, 30.2747],
  Destination: [-97.6885, 30.2241],
  TravelMode: "Car",
});
const routeResponse = await routesClient.send(routeCommand);

// Calculate Route Matrix
const matrixCommand =
  new amazonLocationClient.routes.CalculateRouteMatrixCommand({
    Origins: [
      { Position: [-97.7431, 30.2747] },
      { Position: [-97.6885, 30.2241] },
    ],
    Destinations: [{ Position: [-121.8863, 37.3382] }],
    TravelMode: "Car",
  });
const matrixResponse = await routesClient.send(matrixCommand);

// Calculate Isolines
const isolineCommand = new amazonLocationClient.routes.CalculateIsolinesCommand(
  {
    Origin: [-97.7431, 30.2747],
    Thresholds: {
      Time: [300, 600, 900], // 5, 10, 15 minutes
    },
    TravelMode: "Car",
  },
);
const isolineResponse = await routesClient.send(isolineCommand);
GeoMapsClient (Static Maps)
const mapsClient = new amazonLocationClient.GeoMapsClient(
  authHelper.getClientConfig(),
);

// Get Static Map
const staticMapCommand = new amazonLocationClient.maps.GetStaticMapCommand({
  FileName: "map",
  Height: 400,
  Width: 600,
  Center: [-97.7431, 30.2747],
  Zoom: 10,
});
const mapResponse = await mapsClient.send(staticMapCommand);

// Response contains image as blob
const blob = mapResponse.Blob; // Uint8Array, not a stream
const imageUrl = URL.createObjectURL(new Blob([blob], { type: "image/jpeg" }));
document.getElementById("map-img").src = imageUrl;
LocationClient (Geofences, Trackers)
const locationClient = new amazonLocationClient.LocationClient(
  authHelper.getClientConfig(),
);

// List Geofences
const listCommand = new amazonLocationClient.ListGeofencesCommand({
  CollectionName: "my-geofence-collection",
  MaxResults: 100,
});
const listResponse = await locationClient.send(listCommand);

// Put Geofence
const putCommand = new amazonLocationClient.PutGeofenceCommand({
  CollectionName: "my-geofence-collection",
  GeofenceId: "geofence-1",
  Geometry: {
    Circle: {
      Center: [-97.7431, 30.2747],
      Radius: 1000, // meters
    },
  },
});
await locationClient.send(putCommand);

// Batch Update Device Position
const updateCommand = new amazonLocationClient.BatchUpdateDevicePositionCommand(
  {
    TrackerName: "my-tracker",
    Updates: [
      {
        DeviceId: "device-1",
        Position: [-97.7431, 30.2747],
        SampleTime: new Date().toISOString(),
      },
    ],
  },
);
const updateResponse = await locationClient.send(updateCommand);

Error Handling

Standard Error Handling Pattern
async function callLocationAPI(commandFn) {
  try {
    const response = await commandFn();
    return { success: true, data: response };
  } catch (error) {
    console.error("API Error:", error);

    // Parse error details
    const errorInfo = {
      success: false,
      error: error.name,
      message: error.message,
    };

    // Handle specific error types
    if (error.name === "ValidationException") {
      errorInfo.userMessage = "Invalid input. Please check your parameters.";
    } else if (error.name === "AccessDeniedException") {
      errorInfo.userMessage =
        "Permission denied. Check your API key permissions.";
    } else if (error.name === "ResourceNotFoundException") {
      errorInfo.userMessage = "Resource not found.";
    } else if (error.name === "ThrottlingException") {
      errorInfo.userMessage = "Too many requests. Please wait and try again.";
    } else if (error.message.includes("Network")) {
      errorInfo.userMessage = "Network error. Please check your connection.";
    } else {
      errorInfo.userMessage = "An error occurred. Please try again.";
    }

    return errorInfo;
  }
}

// Usage
const result = await callLocationAPI(async () => {
  const client = new amazonLocationClient.GeoPlacesClient(
    authHelper.getClientConfig(),
  );
  const command = new amazonLocationClient.places.GeocodeCommand({
    QueryText: "Austin",
  });
  return await client.send(command);
});

if (result.success) {
  console.log("Success:", result.data);
} else {
  alert(result.userMessage);
}
Retry Logic
async function callWithRetry(commandFn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await commandFn();
    } catch (error) {
      const isLastAttempt = i === maxRetries - 1;

      if (error.name === "ThrottlingException" && !isLastAttempt) {
        // Exponential backoff
        const delay = Math.pow(2, i) * 1000;
        console.log(`Retrying after ${delay}ms...`);
        await new Promise((resolve) => setTimeout(resolve, delay));
        continue;
      }

      throw error; // Rethrow if not retryable or last attempt
    }
  }
}

Best Practices

Initialization
  • Initialize once: Create auth helper and clients once, reuse across app

  • Store globally: Keep auth helper in app state, don't recreate per request

  • Check credentials: Validate API key format before initializing

Performance
  • Reuse clients: Don't create new client for each API call

  • Cancel requests: Cancel in-flight requests when user navigates away

  • Implement caching: Cache geocoding and search results (5-10 minutes)

  • Debounce input: Wait 300ms after user stops typing before API calls

Security
  • API keys are client-safe: Unlike AWS credentials, API keys are designed for client-side use and will be visible in browser source

  • Follow AWS best practices: See API Key Best Practices for domain restrictions and key rotation

  • Restrict API key permissions: Configure API key to only access needed operations (Maps, Places, Routes)

  • Prefer API keys for Maps/Places/Routes: Simpler and recommended for these APIs

  • Use Cognito when required: For Geofencing/Tracking or per-user authorization

Error Handling
  • Always use try-catch: Wrap all API calls in try-catch blocks

  • Show user-friendly messages: Translate error codes to readable messages

  • Log for debugging: Log full error objects to console

  • Implement retry: Retry on throttling and network errors

Code Organization
// Good: Centralized client management
class LocationService {
  constructor(apiKey, region) {
    this.authHelper = amazonLocationClient.withAPIKey(apiKey, region);
    this.placesClient = new amazonLocationClient.GeoPlacesClient(
      this.authHelper.getClientConfig(),
    );
    this.routesClient = new amazonLocationClient.GeoRoutesClient(
      this.authHelper.getClientConfig(),
    );
  }

  async geocode(address) {
    const command = new amazonLocationClient.places.GeocodeCommand({
      QueryText: address,
    });
    return await this.placesClient.send(command);
  }

  async calculateRoute(origin, destination) {
    const command = new amazonLocationClient.routes.CalculateRoutesCommand({
      Origin: origin,
      Destination: destination,
      TravelMode: "Car",
    });
    return await this.routesClient.send(command);
  }
}

// Usage
const locationService = new LocationService(API_KEY, REGION);
const result = await locationService.geocode("Austin");

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