⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v1.1

amazon-location-service

awslabs@awslabs⭐ 943 stars· last commit 5d ago· 15 open issues

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

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐⭐⭐ 943 on GitHubGitHub ↗

Popular

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Agent Plugins for AWS

Read this in other languages: 日本語

[!IMPORTANT] Generative AI can make mistakes. You should consider reviewing all output and costs generated by your chosen AI model and agentic coding assistant. See AWS Responsible AI Policy.

What's new

[!TIP] The Agent Toolkit for AWS is now live! The Agent Toolkit for AWS is the successor to the MCP servers, plugins, and skills available on AWS Labs, and was informed by feedback from customers like you. If you're building production software using coding agents or building agents for your own customers, we recommend Agent Toolkit for AWS. It includes IAM condition keys to distinguish agent actions from human ones, CloudWatch and CloudTrail visibility, and skills that have been evaluated for accuracy and effectiveness. This repo continues to work and accept contributions. Over time, the most useful projects here will move into Agent Toolkit for AWS.


Agent Plugins for AWS

Agent Plugins for AWS equip AI coding agents with the skills to help you architect, deploy, and operate on AWS. Agent plugins are currently supported by Claude Code, Codex, and Cursor.

AI coding agents are increasingly used in software development, helping developers write, review, and deploy code more efficiently. Agent skills and the broader agent plugin packaging model are emerging as best practices for steering coding agents toward reliable outcomes without bloating model context. Instead of repeatedly pasting long AWS guidance into prompts, developers can now encode that guidance as reusable, versioned capabilities that agents invoke when relevant. This improves determinism, reduces context overhead, and makes agent behavior easier to standardize across teams. Agent plugins act as containers that package different types of expertise artifacts together. A single agent plugin can include:

  • Agent skills – Structured workflows and best-practice playbooks that guide AI through complex tasks like deployment, code review, or architecture planning. Agent skills encode domain expertise as step-by-step processes.
  • MCP servers – Connections to external services, data sources, and APIs. MCP servers give your assistant access to live documentation, pricing data, and other resources at runtime. Learn more about MCP servers for AWS.
  • Hooks – Automation and guardrails that run on developer actions. Hooks can validate changes, enforce standards, or trigger workflows automatically.
  • References – Documentation, configuration defaults, and knowledge that the agent skill can consult. References make agent skills smarter without bloating the prompt.

As new types of expertise artifacts emerge in this space, they can be packaged into agent plugins, making the evolution transparent to developers.

Best practices

To maximize the benefits of plugin-assisted development while maintaining security and code quality, follow these essential guidelines:

  • Always review generated code before deployment (for example, against your constraints for security, cost, resilience)
  • Use plugins as accelerators, not replacements for developer judgment and expertise.
  • Keep plugins updated to benefit from the latest AWS best practices.
  • Follow the principle of least privilege when configuring AWS credentials.
  • Run security scanning tools on generated infrastructure code.

Plugins

PluginDescriptionStatus
amazon-location-serviceAdd maps, geocoding, routing, places search, and geospatial features to applications with Amazon Location ServiceAvailable
aws-amplifyBuild full-stack apps with AWS Amplify Gen 2 using guided workflows for auth, data, storage, and functionsAvailable
aws-serverlessBuild serverless applications with Lambda, API Gateway, EventBridge, Step Functions, durable functions, and Lambda Managed InstancesAvailable
aws-transformMigrate, modernize, and upgrade codebases to AWS — .NET to .NET 8/10, mainframe COBOL to Java, VMware to EC2, SQL Server to Aurora, and language/SDK upgradesAvailable
codebase-documentor-for-awsAnalyze AWS-deployed services and codebases to generate structured technical documentation with source-of-truth citationsAvailable
databases-on-awsDatabase guidance for the AWS database portfolio — schema design, queries, migrations, and multi-tenant patternsSome Services Available (Aurora DSQL)
deploy-on-awsDeploy applications to AWS with architecture recommendations, cost estimates, and IaC deploymentAvailable
migration-to-awsMigrate GCP infrastructure to AWS with resource discovery, architecture mapping, cost analysis, and execution planningAvailable
sagemaker-aiBuild, train, and deploy AI models with deep AWS AI/ML expertise brought directly into your coding assistants, covering the surface area of Amazon SageMaker AIAvailable

Installation

Claude Code

Add the marketplace

/plugin marketplace add awslabs/agent-plugins

Install a plugin

/plugin install amazon-location-service@agent-plugins-for-aws

or

/plugin install aws-amplify@agent-plugins-for-aws

or

/plugin install aws-serverless@agent-plugins-for-aws

or

/plugin install codebase-documentor-for-aws@agent-plugins-for-aws

or

/plugin install databases-on-aws@agent-plugins-for-aws

or

/plugin install deploy-on-aws@agent-plugins-for-aws

or

/plugin install sagemaker-ai@agent-plugins-for-aws

Codex

Codex supports repo-local marketplaces and plugin manifests through .agents/plugins/marketplace.json and per-plugin manifests under plugins/*/.codex-plugin/plugin.json; this repo includes both, following the official Codex plugin packaging guidance in Build plugins.

To try these plugins in Codex from this repo:

  1. Clone this repository locally.
  2. Open the repo in Codex so Codex can discover .agents/plugins/marketplace.json.
  3. Restart Codex.
  4. Open the plugin directory, choose the Agent Plugins for AWS marketplace, and install the plugin you want to use.

Known limitation:

  • Claude-specific automatic hooks are not yet wired into the Codex manifests.
  • The `datab

// HOW IT'S BUILT

// FILES

13 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • plugins/amazon-location-service/skills/amazon-location-service/SKILL.md16 KB845dcb3efdd8upstream ↗
    ---
    name: amazon-location-service
    description: 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.
    license: Apache-2.0
    metadata:
      author: aws-geospatial
      version: "1.1"
    ---
    
    ## 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](https://maplibre.org/) 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:
    
    - **Developer Guide**: https://docs.aws.amazon.com/location/latest/developerguide/llms.txt
    - **API Reference**: https://docs.aws.amazon.com/location/latest/APIReference/llms.txt
    
    ## 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:**
    
    - @aws-sdk/client-geo-maps
    - @aws-sdk/client-geo-places
    - @aws-sdk/client-geo-routes
    - @aws-sdk/client-location
    - @aws-sdk/credential-providers
    - https://github.com/aws-geospatial/amazon-location-utilities-auth-helper-js
    
    **Resources:**
    
    - NPM Package: [@aws/amazon-location-client](https://www.npmjs.com/package/@aws/amazon-location-client)
    - GitHub Repository: [aws-geospatial/amazon-location-client-js](https://github.com/aws-geospatial/amazon-location-client-js)
    
    ### 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):
    
    | Service | AllowActions                                                                                                                                                                  | AllowResources                                |
    | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
    | Maps    | `geo-maps:GetTile`, `geo-maps:GetStaticMap`                                                                                                                                   | `arn:aws:geo-maps:REGION::provider/default`   |
    | Places  | `geo-places:Autocomplete`, `geo-places:Geocode`, `geo-places:ReverseGeocode`, `geo-places:SearchText`, `geo-places:SearchNearby`, `geo-places:Suggest`, `geo-places:GetPlace` | `arn:aws:geo-places:REGION::provider/default` |
    | Routes  | `geo-routes:CalculateRoutes`, `geo-routes:CalculateRouteMatrix`, `geo-routes:CalculateIsolines`, `geo-routes:OptimizeWaypoints`, `geo-routes:SnapToRoads`                     | `arn: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.
    
    ```javascript
    import { LocationClient } from "@aws-sdk/client-location";
    
    // Server-side: uses IAM credentials from environment/role
    const client = new LocationClient({ region: "us-east-1" });
    ```
    
    ```javascript
    // 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](https://docs.aws.amazon.com/aws-mcp/latest/userguide/what-is-aws-mcp-server.html) (Apache-2.0 license) which provides access to AWS documentation, API references, and direct API interactions. See the [Getting Started Guide](https://docs.aws.amazon.com/aws-mcp/latest/userguide/getting-started-aws-mcp-server.html) for setup and credential configuration. To use a non-default region, add `"--metadata", "AWS_REGION=<your-region>"` to your MCP config args.
    
    ## Additional Resources
    
    - [Amazon Location Service Developer Guide](https://docs.aws.amazon.com/location/latest/developerguide/)
    - [Amazon Location Service API Reference](https://docs.aws.amazon.com/location/latest/APIReference/)
    - [Amazon Location Service Samples](https://github.com/aws-geospatial)
    
    ## Reference Files
    
    Load these resources as needed for specific implementation guidance:
    
    - [Address Input](./references/address-input.md) - Create effective address input forms for users with address type ahead completion improving input speed and accuracy
    - [Address Verification](./references/address-verification.md) - 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](./references/calculate-routes.md) - Calculate routes between locations with customizable travel options and display them on maps
    - [Device Tracking](./references/device-tracking.md) - Track device locations in real time and query position history
    - [Dynamic Map Rendering](./references/dynamic-map.md) - Render dynamic maps with MapLibre
    - [Google Maps Migration (Android)](./references/google-migration-android.md) - Migrate Android application from Google Maps SDK for Android to Amazon Location Service
    - [Google Maps Migration (iOS)](./references/google-migration-ios.md) - Migrate iOS application from Google Maps SDK for iOS to Amazon Location Service
    - [Google Maps Migration (JavaScript)](./references/google-migration-web.md) - Migrate JavaScript web application from Google Maps API to Amazon Location Service
    - [Places Search](./references/places-search.md) - Search for places or points of interest
    - [Web JavaScript](./references/web-javascript.md) - Integrate Amazon Location services into web browser applications
    - [Zone Alerts](./references/zone-alerts.md) - Monitor device positions against geographic boundaries and react to zone entry or exit
    
  • plugins/amazon-location-service/skills/amazon-location-service/references/address-input.md10 KBe65c68482848upstream ↗
    # Address Input
    
    > **Audience Note**: Keywords MUST, SHOULD, MAY in this document indicate requirements for agent recommendations to users, following RFC 2119.
    
    Create effective address input forms with type-ahead completion that improves input speed and accuracy using Amazon Location Service Places APIs.
    
    **Distinction from Address Verification**: This reference covers the interactive UI/UX of collecting a single address from a user (autocomplete, type-ahead, and resolving a typed address to coordinates). It is NOT postal address validation. To verify and standardize addresses against authoritative postal data — producing a match-confidence verdict and per-component status — use the asynchronous Jobs API (`StartJob` with Action `ValidateAddress`); see the address-verification reference. Geocode returns coordinates and a matched label, not a postal-deliverability verdict.
    
    ## Table of Contents
    
    - [Overview](#overview)
    - [Complete Implementation Flow](#complete-implementation-flow)
    - [API Details](#api-details)
    - [Code Examples](#code-examples)
    - [Error Handling](#error-handling)
    - [Best Practices](#best-practices)
    
    ## Overview
    
    Address input forms SHOULD implement this three-stage flow:
    
    1. **Autocomplete** - Type-ahead suggestions as user types
    2. **GetPlace** - Fetch complete details when user selects a suggestion
    3. **Geocode** - Resolve the address to coordinates if the user types a complete address without selecting a suggestion
    
    ## Complete Implementation Flow
    
    ```javascript
    // Stage 1: User types in address field → Autocomplete
    // Stage 2: User selects suggestion → GetPlace
    // Stage 3: User submits without selection → Geocode (resolve to coordinates)
    
    // HTML Structure
    <input id="address-input" type="text" placeholder="Enter address">
    <div id="suggestions"></div>
    <button id="submit">Submit</button>
    ```
    
    ## API Details
    
    ### Autocomplete
    
    **Purpose**: Provide type-ahead suggestions for partially typed addresses.
    
    **When to use**: As user types in address input field (typically after 3+ characters).
    
    **Critical**: Always display `Address.Label` to users, NOT `Title`. The `Title` field may show components in reverse order and is not suitable for display.
    
    **Returns**: Array of suggestions, each with:
    
    - `PlaceId` - Use this to fetch full details with GetPlace
    - `Address.Label` - Display this to users (e.g., "123 Main St, Seattle, WA 98101")
    - `Title` - DO NOT display (may be reversed: "98101, WA, Seattle, Main St, 123")
    
    ### GetPlace
    
    **Purpose**: Retrieve complete place details after user selects autocomplete suggestion.
    
    **When to use**: When user clicks/selects an autocomplete suggestion.
    
    **Input**: `PlaceId` from Autocomplete result.
    
    **Returns**: Complete place object with nested Address structure:
    
    ```javascript
    {
      PlaceId: "string",
      Address: {
        Label: "123 Main St, Seattle, WA 98101, USA",
        Region: {
          Code: "WA",           // State/province code
          Name: "Washington"    // Full state name
        },
        Country: {
          Code2: "US",          // ISO 2-letter country code
          Code3: "USA",         // ISO 3-letter country code
          Name: "United States" // Full country name
        },
        Locality: "Seattle",    // City name (string)
        PostalCode: "98101",    // Postal code (string)
        Street: "Main St",      // Street name (string)
        AddressNumber: "123"    // Street number (string)
      },
      Position: [lon, lat]      // Coordinates
    }
    ```
    
    **Important**: Address properties are nested objects, not flat strings. Access as `address.Region.Code`, not `address.RegionCode`.
    
    ### Geocode
    
    **Purpose**: Resolve a complete address typed by the user (when they don't select an autocomplete suggestion) to coordinates and a matched address label.
    
    **When to use**: On form submission if the user typed an address but didn't select any autocomplete suggestion.
    
    **Input**: Complete address string.
    
    **Returns**: Array of matching addresses with coordinates and a formatted label.
    
    **Note**: Geocode is NOT postal address validation. It returns coordinates, a best-match label, and `MatchScores` (match confidence), but not a postal-deliverability verdict (whether an address is mailable/locatable) or standardized per-component validation status. For verifying and standardizing addresses against authoritative postal data, use the asynchronous Jobs API (`StartJob` with Action `ValidateAddress`) — see the address-verification reference.
    
    ## Code Examples
    
    ### Complete Implementation
    
    ```javascript
    // Initialize client
    const authHelper = amazonLocationClient.withAPIKey(API_KEY, REGION);
    const client = new amazonLocationClient.GeoPlacesClient(
      authHelper.getClientConfig(),
    );
    
    let selectedPlaceId = null;
    
    // Stage 1: Autocomplete as user types
    document
      .getElementById("address-input")
      .addEventListener("input", async (e) => {
        const query = e.target.value;
    
        if (query.length < 3) {
          document.getElementById("suggestions").innerHTML = "";
          return;
        }
    
        try {
          const command = new amazonLocationClient.places.AutocompleteCommand({
            QueryText: query,
            MaxResults: 5,
          });
    
          const response = await client.send(command);
    
          // Display suggestions using Address.Label (NOT Title!)
          const suggestionsHtml = response.ResultItems.map(
            (item) =>
              `<div class="suggestion" data-place-id="${item.Place?.PlaceId}">
            ${item.Address.Label}
          </div>`,
          ).join("");
    
          document.getElementById("suggestions").innerHTML = suggestionsHtml;
        } catch (error) {
          console.error("Autocomplete error:", error);
          // Show error to user
        }
      });
    
    // Stage 2: User selects suggestion → GetPlace
    document.getElementById("suggestions").addEventListener("click", async (e) => {
      if (!e.target.classList.contains("suggestion")) return;
    
      const placeId = e.target.dataset.placeId;
      selectedPlaceId = placeId;
    
      try {
        const command = new amazonLocationClient.places.GetPlaceCommand({
          PlaceId: placeId,
        });
    
        const response = await client.send(command);
        const place = response;
    
        // Populate form with complete details
        document.getElementById("address-input").value = place.Address.Label;
        document.getElementById("street").value =
          `${place.Address.AddressNumber || ""} ${place.Address.Street || ""}`.trim();
        document.getElementById("city").value = place.Address.Locality || "";
        document.getElementById("state").value = place.Address.Region?.Code || "";
        document.getElementById("zip").value = place.Address.PostalCode || "";
        document.getElementById("country").value =
          place.Address.Country?.Code2 || "";
    
        // Store coordinates for later use
        document.getElementById("lat").value = place.Position[1];
        document.getElementById("lon").value = place.Position[0];
    
        // Clear suggestions
        document.getElementById("suggestions").innerHTML = "";
      } catch (error) {
        console.error("GetPlace error:", error);
        alert("Failed to fetch address details");
      }
    });
    
    // Stage 3: User submits without selecting → Geocode (resolve to coordinates)
    document.getElementById("submit").addEventListener("click", async () => {
      if (selectedPlaceId) {
        // User selected from autocomplete, proceed
        submitForm();
        return;
      }
    
      // User typed address without selecting; resolve it to coordinates with Geocode
      const query = document.getElementById("address-input").value;
    
      if (!query) {
        alert("Please enter an address");
        return;
      }
    
      try {
        const command = new amazonLocationClient.places.GeocodeCommand({
          QueryText: query,
          MaxResults: 1,
        });
    
        const response = await client.send(command);
    
        if (response.ResultItems.length === 0) {
          alert("Address not found. Please check and try again.");
          return;
        }
    
        const result = response.ResultItems[0];
    
        // Confirm with user if address was standardized
        if (result.Address.Label !== query) {
          const confirmed = confirm(`Did you mean: ${result.Address.Label}?`);
          if (!confirmed) return;
        }
    
        // Populate with geocoded result
        document.getElementById("lat").value = result.Position[1];
        document.getElementById("lon").value = result.Position[0];
    
        submitForm();
      } catch (error) {
        console.error("Geocode error:", error);
        alert("Failed to resolve address");
      }
    });
    
    function submitForm() {
      // Proceed with form submission
      console.log("Submitting form with resolved address");
    }
    ```
    
    ## Error Handling
    
    ### Autocomplete Errors
    
    - **Rate limiting**: Implement debouncing (300ms delay) before calling API
    - **Network failures**: Show cached suggestions or friendly message
    - **No results**: Allow user to continue typing or submit for geocoding
    
    ### GetPlace Errors
    
    - **Invalid PlaceId**: Should not happen if using autocomplete results, but handle gracefully
    - **Network timeout**: Retry once, then show error message
    
    ### Geocode Errors
    
    - **No results**: Prompt user to check spelling or use autocomplete
    - **Multiple results**: Present user with options to select correct one
    - **Ambiguous address**: Ask for more details (e.g., city/state)
    
    ## Best Practices
    
    ### Performance
    
    - **Debounce autocomplete**: Wait 300ms after user stops typing before API call
    - **Cancel previous requests**: Cancel in-flight autocomplete requests when new input arrives
    - **Cache results**: Cache autocomplete results for repeated queries
    
    ### User Experience
    
    - **Always use Address.Label**: Never display the `Title` field - it may be reversed
    - **Show visual feedback**: Loading indicators during API calls
    - **Keyboard navigation**: Allow arrow keys and Enter to navigate suggestions
    - **Clear affordances**: Make it obvious when an address suggestion has been selected or resolved
    
    ### Data Handling
    
    - **Store PlaceId**: Keep PlaceId with address for future reference
    - **Store coordinates**: Save Position for mapping and distance calculations
    - **Handle missing fields**: Not all addresses have all components (e.g., AddressNumber)
    - **Respect nested structure**: Access `address.Region.Code`, not `address.RegionCode`
    
    ### Accessibility
    
    - **ARIA labels**: Use proper ARIA attributes for autocomplete
    - **Keyboard support**: Full keyboard navigation for suggestions
    - **Screen reader announcements**: Announce number of suggestions found
    
  • plugins/amazon-location-service/skills/amazon-location-service/references/address-verification.md24 KB6e8b42a388f6upstream ↗
    # Address Verification
    
    > **Audience Note**: Keywords MUST, SHOULD, MAY in this document indicate requirements for agent recommendations to users, following RFC 2119.
    
    Verify and standardize addresses in bulk against authoritative postal data using the Amazon Location Service **Jobs API** (`StartJob` with Action `ValidateAddress`).
    
    **Distinction from Address Input**: The address-input reference covers the interactive UI/UX of collecting a single address from a user (autocomplete, type-ahead, and resolving a typed address to coordinates with Geocode). This reference covers **postal address validation** — verifying and standardizing addresses against authoritative postal reference data (USPS, Royal Mail, Australia Post, Canada Post) in bulk.
    
    **What Geocode does NOT give you.** Geocode (`geo-places:Geocode`) does return match quality — a `MatchScores` object with an overall score (1.0 = all input tokens matched) plus per-component scores, and an `AddressNumberCorrected` flag — with no opt-in required. So "match confidence" and "did a component change" are _not_ the dividing line. What Geocode lacks, and what `ValidateAddress` adds, is **postal-authority verification and standardization**:
    
    - `ValidationGranularity` — an explicit Premise/Street/LocalityAndPostalCode/Locality verdict for how deep the match validated.
    - Delivery indicators — `Mailable` / `Locatable` from postal-carrier data.
    - Per-component `StatusDetail` — `Corrected` / `Appended` / `Alias` / `StandardizedNoMatch` / `OutOfRange`, telling you _how_ each component was resolved against the postal dataset.
    - Standardized `Output_*` components formatted to official postal standards.
    
    **When to use which.** For a single interactive or ad-hoc address ("does this typed address resolve, and how well?"), Geocode's one synchronous call — including its `MatchScores` — is the correct answer; do NOT stand up a job for it. Reach for the Jobs API (`StartJob` with Action `ValidateAddress`, then `GetJob`/`ListJobs`/`CancelJob`) when you need a postal-deliverability verdict, standardized output, or bulk throughput. Note the Jobs API covers only the US, Canada, UK, and Australia (see [Supported Countries](#supported-countries)); for addresses elsewhere, Geocode is the available option for address resolution.
    
    ## Table of Contents
    
    - [Overview](#overview)
    - [When to Validate Addresses](#when-to-validate-addresses)
    - [Supported Countries](#supported-countries)
    - [Job Workflow](#job-workflow)
    - [Input Schema](#input-schema)
    - [Starting a Validation Job](#starting-a-validation-job)
    - [Tracking a Job](#tracking-a-job)
    - [Interpreting Results](#interpreting-results)
    - [Handling Partial Matches](#handling-partial-matches)
    - [Listing and Canceling Jobs](#listing-and-canceling-jobs)
    - [Error Handling](#error-handling)
    - [Pricing](#pricing)
    - [Best Practices](#best-practices)
    
    ## Overview
    
    Address validation jobs process address data to verify and standardize addresses. The service:
    
    1. **Validates** - Confirms the address exists and is deliverable by checking it against authoritative postal datasets
    2. **Standardizes** - Formats the address according to official postal standards (consistent abbreviations, casing, punctuation)
    3. **Corrects and completes** - Fixes spelling mistakes and appends missing components such as postal codes or street names
    4. **Enriches (optional)** - Adds geographic coordinates and country-specific postal attributes when requested
    
    Validation runs as an **asynchronous bulk job**: you stage input in Amazon S3 as Apache Parquet, submit a job with `StartJob`, poll `GetJob` (or subscribe via EventBridge) until it completes, then read Parquet results from your S3 output location. This is designed for processing many addresses in a single operation, not for real-time single-address lookups during form entry.
    
    ## When to Validate Addresses
    
    Use address validation jobs in these scenarios:
    
    - **Database cleansing**: Clean and standardize existing address databases in bulk
    - **Data migration**: One-time address cleanup during system transitions
    - **Before shipping/logistics**: Validate delivery addresses to reduce failed deliveries
    - **Identity and risk workflows**: Standardize customer addresses for verification, risk assessment, and fraud prevention
    - **Analytics and entity resolution**: Standardize addresses for location-based analytics, demographic analysis, and CRM deduplication
    - **Regulatory reporting**: Validate patient/provider or customer addresses to meet compliance requirements
    
    For interactive, single-address entry during a form session, use Autocomplete + GetPlace instead (see the address-input reference). Do NOT stand up a validation job on every keystroke or form submit.
    
    ## Supported Countries
    
    Address validation supports addresses from: **United States, Canada, United Kingdom, and Australia**. The optional `Position` feature (coordinates) is available only in the United States, Canada, and Australia.
    
    ## Job Workflow
    
    ```
    1. Prepare input   → Write addresses to a Parquet file in Amazon S3
    2. StartJob        → Action=ValidateAddress, ExecutionRoleArn, Input/Output S3 locations
    3. Track           → Poll GetJob (or listen on EventBridge) until Status is terminal
    4. Retrieve        → Read Parquet result files from the S3 output location
    ```
    
    Job status transitions: `Pending → Running → Completed` (or `Failed`), and `Cancelling → Cancelled` if you cancel it.
    
    The Jobs API operations use `LocationClient` (`@aws-sdk/client-location`) with SigV4 (IAM) credentials — these are server-side/back-office operations, not API-key client-side calls.
    
    ## Input Schema
    
    Input data MUST be Apache Parquet stored in Amazon S3 (limit: 10 GB per file, 1 GB per Parquet row-group). The schema supports free-form address lines, structured components, or a combination:
    
    | Field                                                         | Description                                                                                                            |
    | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
    | `Id`                                                          | Optional per-record identifier. Mirrored in output as `Input_Id` so you can correlate results to inputs.               |
    | `AddressLines_1` … `AddressLines_5`                           | Free-form address lines. Put single-line input in `AddressLines_1`; order multi-line input as it would appear on mail. |
    | `AddressComponents_Country`                                   | Alpha-2, alpha-3 code, or full country name.                                                                           |
    | `AddressComponents_Region`                                    | State, province, or territory.                                                                                         |
    | `AddressComponents_SubRegion`                                 | County or equivalent.                                                                                                  |
    | `AddressComponents_Locality`                                  | City or town.                                                                                                          |
    | `AddressComponents_PostalCode`                                | Postal / ZIP code.                                                                                                     |
    | `AddressComponents_Street`                                    | Street name.                                                                                                           |
    | `AddressComponents_AddressNumber`                             | House / building number.                                                                                               |
    | `AddressComponents_Unit` / `AddressComponents_UnitDesignator` | Unit value and designator (e.g. `Apt`, `Suite`, `#`).                                                                  |
    
    **Note**: When combining `AddressLines` with `AddressComponents`, put first-line components (`AddressNumber`, `Street`, `Unit`, `UnitDesignator`) in `AddressLines`, and last-line components (`Locality`, `Region`, `SubRegion`, `Country`, `PostalCode`) in `AddressComponents`.
    
    Example: create a Parquet input file with PyArrow.
    
    ```python
    import pyarrow as pa
    import pyarrow.parquet as pq
    
    data = [
        {"Id": "record-001", "AddressLines_1": "Pike Place", "AddressLines_2": "Apartment 4B",
         "AddressComponents_Country": "USA", "AddressComponents_PostalCode": "98101"},
        {"Id": "record-002", "AddressLines_1": "2901 E Madison St",
         "AddressComponents_Country": "USA", "AddressComponents_PostalCode": "98112"},
    ]
    
    schema = pa.schema([
        ("Id", pa.string()),
        ("AddressLines_1", pa.string()),
        ("AddressLines_2", pa.string()),
        ("AddressComponents_Country", pa.string()),
        ("AddressComponents_PostalCode", pa.string()),
    ])
    
    pq.write_table(pa.Table.from_pylist(data, schema=schema), "addresses.parquet")
    # Upload addresses.parquet to your input S3 bucket/prefix.
    ```
    
    ## Starting a Validation Job
    
    `StartJob` requires the action, an `ExecutionRoleArn` that Amazon Location assumes to read your input and write your output S3 locations, and the input/output configuration. `AdditionalFeatures` is optional.
    
    **Request shape:**
    
    ```json
    {
      "Action": "ValidateAddress",
      "Name": "customer-db-cleanup-2025-06",
      "ExecutionRoleArn": "arn:aws:iam::YOUR_ACCOUNT_ID:role/LocationServiceJobExecutionRole",
      "InputOptions": {
        "Format": "Parquet",
        "Location": "arn:aws:s3:::YOUR_INPUT_BUCKET/addresses.parquet"
      },
      "OutputOptions": {
        "Format": "Parquet",
        "Location": "arn:aws:s3:::YOUR_OUTPUT_BUCKET/results/"
      },
      "ActionOptions": {
        "ValidateAddress": {
          "AdditionalFeatures": ["Position", "CountrySpecificAttributes"]
        }
      }
    }
    ```
    
    **`AdditionalFeatures`** (optional, choose 1–2):
    
    - `Position` - Return WGS 84 longitude/latitude for validated addresses. US, Canada, and Australia only; incurs additional cost.
    - `CountrySpecificAttributes` - Return country-specific postal/census data (e.g. USPS carrier route and delivery point for US; Australia Post / G-NAF identifiers for Australia; Royal Mail UDPRN for UK; Canada Post record type for Canada).
    
    **JavaScript SDK:**
    
    ```javascript
    import { LocationClient, StartJobCommand } from "@aws-sdk/client-location";
    
    // Server-side: IAM credentials from environment/role
    const client = new LocationClient({ region: "us-east-1" });
    
    const response = await client.send(
      new StartJobCommand({
        Action: "ValidateAddress",
        Name: "customer-db-cleanup-2025-06",
        ExecutionRoleArn:
          "arn:aws:iam::YOUR_ACCOUNT_ID:role/LocationServiceJobExecutionRole",
        InputOptions: {
          Format: "Parquet",
          Location: "arn:aws:s3:::YOUR_INPUT_BUCKET/addresses.parquet",
        },
        OutputOptions: {
          Format: "Parquet",
          Location: "arn:aws:s3:::YOUR_OUTPUT_BUCKET/results/",
        },
        ActionOptions: {
          ValidateAddress: { AdditionalFeatures: ["Position"] },
        },
      }),
    );
    
    // Response: { JobId, JobArn, Status: "Pending", CreatedAt }
    console.log("Started job:", response.JobId, response.Status);
    ```
    
    **AWS CLI:**
    
    ```bash
    aws location start-job \
      --action ValidateAddress \
      --execution-role-arn "arn:aws:iam::YOUR_ACCOUNT_ID:role/LocationServiceJobExecutionRole" \
      --input-options Location=arn:aws:s3:::YOUR_INPUT_BUCKET/addresses.parquet,Format=Parquet \
      --output-options Location=arn:aws:s3:::YOUR_OUTPUT_BUCKET/results/,Format=Parquet \
      --action-options '{"ValidateAddress":{"AdditionalFeatures":["Position"]}}' \
      --region us-east-1
    ```
    
    The `ExecutionRoleArn` MUST be an IAM role in the same account that Amazon Location assumes during processing, so you do not pass long-term credentials for S3 access. Two requirements are easy to miss — omit either and `StartJob` succeeds, reports `Pending`, then flips to `Failed`:
    
    **1. Trust policy — the role must let `geo.amazonaws.com` assume it.** The permission policy alone is not enough; without this trust relationship the `AssumeRole` fails. Scope it to your account with an `aws:SourceAccount` condition:
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": { "Service": "geo.amazonaws.com" },
          "Action": "sts:AssumeRole",
          "Condition": {
            "StringEquals": { "aws:SourceAccount": "YOUR_ACCOUNT_ID" }
          }
        }
      ]
    }
    ```
    
    **2. Bucket versioning must be enabled** on the input and output buckets — Amazon Location requires it, which is why the input policy needs `s3:GetObjectVersion`. Grant list/version actions on the input bucket, and `PutObject`/`AbortMultipartUpload` (for cleaning up failed multipart uploads of large output files) on the output bucket:
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "s3:GetObject",
            "s3:GetObjectVersion",
            "s3:ListBucket",
            "s3:GetBucketVersioning"
          ],
          "Resource": [
            "arn:aws:s3:::YOUR_INPUT_BUCKET",
            "arn:aws:s3:::YOUR_INPUT_BUCKET/*"
          ]
        },
        {
          "Effect": "Allow",
          "Action": ["s3:PutObject", "s3:AbortMultipartUpload"],
          "Resource": "arn:aws:s3:::YOUR_OUTPUT_BUCKET/*"
        }
      ]
    }
    ```
    
    Enable versioning with `aws s3api put-bucket-versioning --bucket YOUR_INPUT_BUCKET --versioning-configuration Status=Enabled` (repeat for the output bucket).
    
    ## Tracking a Job
    
    Poll `GetJob` with the `JobId` until `Status` is terminal (`Completed`, `Failed`, or `Cancelled`). For event-driven workflows, subscribe to job status changes via Amazon EventBridge instead of polling.
    
    ```javascript
    import { GetJobCommand } from "@aws-sdk/client-location";
    
    async function waitForJob(client, jobId) {
      const terminal = new Set(["Completed", "Failed", "Cancelled"]);
      while (true) {
        const job = await client.send(new GetJobCommand({ JobId: jobId }));
        if (terminal.has(job.Status)) return job;
        // Back off between polls; jobs are asynchronous and may run for a while.
        await new Promise((r) => setTimeout(r, 30000));
      }
    }
    
    const job = await waitForJob(client, jobId);
    if (job.Status === "Failed") {
      // GetJob returns Error.Code and Error.Messages for failed jobs
      console.error("Job failed:", job.Error?.Code, job.Error?.Messages);
    } else if (job.Status === "Completed") {
      // Results are in the OutputOptions.Location S3 prefix
      console.log("Results at:", job.OutputOptions.Location);
    }
    ```
    
    `GetJob` also returns the full job configuration (`Action`, `ActionOptions`, `ExecutionRoleArn`, `InputOptions`, `OutputOptions`), timestamps (`CreatedAt`, `UpdatedAt`, `EndedAt`), and `Error` details if it failed.
    
    ## Interpreting Results
    
    When a job completes, read the Parquet result files from the S3 output prefix. Output **preserves all input fields with an `Input_` prefix** (so `Id` → `Input_Id`) and adds `Output_`-prefixed result fields. Records that failed to process include `ErrorType` and `ErrorMessage`.
    
    **Overall verdict** (per record):
    
    - `Output_ValidationResults_MatchConfidence` - `High`, `MediumHigh`, `Medium`, `MediumLow`, or `Low`
    - `Output_ValidationResults_MatchConfidenceScore` - Precise score from 0 to 1.0 (1.0 = perfect match)
    - `Output_ValidationResults_ValidationGranularity` - How deep the match validated:
      - `Premise` - Validated to the address-number level
      - `Street` - Validated to the street level
      - `LocalityAndPostalCode` - Locality, postal code, and country validated
      - `Locality` - Locality and country validated
    
    **Standardized address** (`Output_Address_*` and `Output_AddressLines_*`): canonical, postal-formatted components — `Output_Address_Label`, `Output_Address_Street`, `Output_Address_AddressNumber`, `Output_Address_Locality`, `Output_Address_Region_Code`/`_Name`, `Output_Address_PostalCode`, country codes, secondary-address (unit/floor) components, and per-line output.
    
    **Delivery indicators**: `Output_AddressMetadata_DeliveryIndicators_Mailable` and `_Locatable` (`true`/`false`).
    
    **Per-component status**: each component's status lives in a fully-qualified column of the form `Output_ValidationResults_Components_Address_<Component>_Status` (and `..._StatusDetail`) — the `Components_Address_` infix is part of the real column name. For example, the address-number status is `Output_ValidationResults_Components_Address_AddressNumber_Status`, and the street status is `Output_ValidationResults_Components_Address_Street_Status`. For each component (`Country`, `Region`, `Locality`, `Street`, `AddressNumber`, `PostalCodeDetails_Base`, unit, floor, …):
    
    - `_Status`: `Validated` or `Unconfirmed`
    - `_StatusDetail`: `Exact` (validated unchanged), `Corrected` (fixed from reference data), `Appended` (added from reference data), `Alias` (validated via alias), `StandardizedNoMatch` (parsed/standardized but not found), `OutOfRange` (e.g. address number outside known range), `NotFound` (empty or not found)
    
    **Optional feature output**: `Output_Position_Longitude`/`_Latitude` (if `Position` requested) and `Output_CountrySpecificAttributes_*` (if `CountrySpecificAttributes` requested).
    
    ```javascript
    // After reading a result record (e.g. via a Parquet reader):
    function summarizeRecord(rec) {
      return {
        inputId: rec.Input_Id,
        confidence: rec.Output_ValidationResults_MatchConfidence,
        score: rec.Output_ValidationResults_MatchConfidenceScore,
        granularity: rec.Output_ValidationResults_ValidationGranularity,
        standardized: rec.Output_Address_Label,
        mailable: rec.Output_AddressMetadata_DeliveryIndicators_Mailable,
        coordinates: rec.Output_Position_Longitude != null
          ? {
              lon: rec.Output_Position_Longitude,
              lat: rec.Output_Position_Latitude,
            }
          : null,
        error: rec.ErrorType ? rec.ErrorMessage : null,
      };
    }
    ```
    
    ## Handling Partial Matches
    
    Some addresses come back with lower `MatchConfidence` and coarser `ValidationGranularity`. Use the overall verdict together with per-component `Status`/`StatusDetail` to decide whether to accept, correct, or reject each record:
    
    - **Accept**: `MatchConfidence` is `High`/`MediumHigh`, `ValidationGranularity` is `Premise` (or `Street` if street-level is sufficient), delivery indicators are `Mailable`, and components are `Validated` with `StatusDetail` of `Exact`/`Corrected`/`Alias`/`Appended`. Store the standardized `Output_*` values.
    - **Correct / review**: Medium confidence, or key components `Unconfirmed` with `StandardizedNoMatch` or `OutOfRange` (e.g. a valid street but an out-of-range house number). Route these to a review queue or attempt a corrected re-submission.
    - **Reject / re-collect**: `Low` confidence, `Locality`-only granularity, `NotFound` on street/address number, or not `Mailable`. Ask the source (or user) for a corrected address.
    
    Prefer the standardized `Output_*` components over the raw input when a record is accepted, and record the confidence/granularity alongside the stored address for auditability.
    
    ```javascript
    function triage(rec) {
      const conf = rec.Output_ValidationResults_MatchConfidence;
      const gran = rec.Output_ValidationResults_ValidationGranularity;
      const mailable = rec.Output_AddressMetadata_DeliveryIndicators_Mailable;
      // Per-component status columns carry the `Components_Address_` infix — the
      // bare `AddressNumber_Status` column does not exist in the output.
      const numberStatus =
        rec.Output_ValidationResults_Components_Address_AddressNumber_Status;
      const numberDetail =
        rec.Output_ValidationResults_Components_Address_AddressNumber_StatusDetail;
    
      if (
        (conf === "High" || conf === "MediumHigh") &&
        gran === "Premise" &&
        mailable
      ) {
        return "accept";
      }
      if (
        conf === "Low" ||
        gran === "Locality" ||
        !mailable ||
        (numberStatus === "Unconfirmed" && numberDetail === "NotFound")
      ) {
        return "reject";
      }
      return "review";
    }
    ```
    
    ## Listing and Canceling Jobs
    
    - **`ListJobs`** - Enumerate your jobs and their statuses (supports filtering and pagination).
    - **`CancelJob`** - Cancel a job that is `Pending` or `Running`; it transitions through `Cancelling` to `Cancelled`.
    
    ```javascript
    import { ListJobsCommand, CancelJobCommand } from "@aws-sdk/client-location";
    
    const { Entries } = await client.send(new ListJobsCommand({}));
    Entries.forEach((j) => console.log(j.JobId, j.Status, j.CreatedAt));
    
    await client.send(new CancelJobCommand({ JobId: jobId }));
    ```
    
    ## Error Handling
    
    - **Job-submission errors** (`StartJob`): `ValidationException` (bad request / input constraints, including the 10 GB per-file and 1 GB per-row-group limits), `AccessDeniedException` (caller or execution role lacks permission), `ThrottlingException` (retry with backoff; `StartJob` is rate-limited), `InternalServerException`.
    - **Job-lookup errors** (`GetJob`): `ResourceNotFoundException` if the `JobId` does not exist.
    - **Failed jobs**: a job can reach `Status: Failed` after starting successfully. Call `GetJob` and read `Error.Code` and `Error.Messages` for the cause.
    - **Per-record errors**: individual records that could not be processed carry `ErrorType`/`ErrorMessage` in the output file while the rest of the job succeeds. Always scan output for these.
    - **Common setup mistakes** (each makes the job go `Pending` then `Failed`, not error at `StartJob`): the `ExecutionRoleArn` must (a) trust `geo.amazonaws.com` for `sts:AssumeRole` in its trust policy, (b) grant `s3:GetObject`/`GetObjectVersion`/`ListBucket`/`GetBucketVersioning` on the input bucket and `s3:PutObject`/`AbortMultipartUpload` on the output bucket, and (c) target buckets that have **versioning enabled**. See [Starting a Validation Job](#starting-a-validation-job) for the full trust and permission policies.
    
    ## Pricing
    
    Address validation is billed as a Jobs API operation, priced per record processed. The optional `Position` feature incurs additional cost and is available only in the US, Canada, and Australia. Review the [Amazon Location Service pricing page](https://aws.amazon.com/location/pricing/) and the Jobs pricing section of the developer guide before running large jobs.
    
    ## Best Practices
    
    ### Choosing the right tool
    
    - **Use the Jobs API for a postal-deliverability verdict or bulk standardization**: `StartJob` with Action `ValidateAddress` is the API that returns `ValidationGranularity`, `Mailable`/`Locatable`, and per-component `StatusDetail` against postal-authority data. `SearchText`/`SearchPlaceIndexForText` return places, not a validation verdict, and are not substitutes.
    - **Use Geocode for a single ad-hoc resolve-and-score**: to check whether one typed address resolves and how well it matched, Geocode's synchronous call (with `MatchScores`) is the right tool — do not stand up a job for it. It is also the available option outside the four Jobs-API countries.
    - **Use Autocomplete + GetPlace for interactive entry**: for a live form, help users pick a real address as they type (see address-input) rather than running a job per submission.
    
    ### Input and jobs
    
    - **Batch generously**: the Jobs API is built for bulk — process thousands to millions of addresses per job rather than many tiny jobs.
    - **Respect file limits**: 10 GB per Parquet file, 1 GB per row-group; split larger datasets across files.
    - **Keep `Id` on every record**: it comes back as `Input_Id`, which is how you correlate output to input.
    - **Set `Name`**: name jobs meaningfully so `ListJobs` and audits stay readable.
    
    ### Results and data quality
    
    - **Store the standardized components**: prefer `Output_*` values over raw input for accepted records.
    - **Record the verdict**: persist `MatchConfidence`, `MatchConfidenceScore`, and `ValidationGranularity` alongside the address for auditability and downstream triage.
    - **Handle partial matches explicitly**: use per-component `Status`/`StatusDetail` to accept, review, or reject — don't treat every completed record as valid.
    - **Request only the features you need**: `Position` and `CountrySpecificAttributes` add cost; request them only when used.
    
    ### Security and operations
    
    - **Least-privilege execution role**: scope the `ExecutionRoleArn` to only the specific input/output buckets and prefixes — while still including the required `GetObjectVersion`/`ListBucket`/`GetBucketVersioning` actions on input, `PutObject`/`AbortMultipartUpload` on output, the `geo.amazonaws.com` trust relationship, and versioning-enabled buckets (see [Starting a Validation Job](#starting-a-validation-job)).
    - **Prefer EventBridge over tight polling**: for long-running jobs, subscribe to status changes instead of polling `GetJob` aggressively.
    - **Retry throttling with backoff**: `StartJob` is rate-limited; use exponential backoff on `ThrottlingException`.
    
  • plugins/amazon-location-service/skills/amazon-location-service/references/calculate-routes.md42 KBbf55f3c5c15dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • plugins/amazon-location-service/skills/amazon-location-service/references/device-tracking.md13 KB9572e0d1ccdcupstream ↗
    # Device Tracking
    
    > **Audience Note**: Keywords MUST, SHOULD, MAY in this document indicate requirements for agent recommendations to users, following RFC 2119.
    
    Track device locations in real time and query position history. This is the core tracking pattern — applicable to fleet dashboards, delivery tracking UIs, asset monitoring, and any scenario where you need to know where devices are or where they've been. For triggering actions when devices enter or exit geographic zones, trackers can be linked to geofence collections — see the **zone-alerts** reference.
    
    > **Language note**: Code examples below use JavaScript (`@aws-sdk/client-location`). When the user's project uses a different language, translate the API calls to the equivalent AWS SDK — the operation names, parameters, and response shapes are identical across SDKs.
    
    ## Table of Contents
    
    - [Step 1: Create a Tracker](#step-1-create-a-tracker)
    - [Step 2: Send Position Updates](#step-2-send-position-updates)
    - [Step 3: Query Device Positions](#step-3-query-device-positions)
    - [Step 4: Display on a Map](#step-4-display-on-a-map)
    - [Error Handling](#error-handling)
    - [Cost Considerations](#cost-considerations)
    - [Best Practices](#best-practices)
    - [Position Integrity](#position-integrity)
    
    ## Step 1: Create a Tracker
    
    A tracker stores position updates for a collection of devices. Choose a position filtering mode to control cost and reduce GPS jitter.
    
    ```javascript
    import { CreateTrackerCommand } from "@aws-sdk/client-location";
    
    await client.send(
      new CreateTrackerCommand({
        TrackerName: "my-fleet-tracker",
        PositionFiltering: "AccuracyBased", // or "DistanceBased" | "TimeBased"
      }),
    );
    ```
    
    ### Position Filtering Modes
    
    | Mode                    | Behavior                                                                                                         | Best For                                           |
    | ----------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
    | **AccuracyBased**       | Ignores updates where movement < measured accuracy. Example: accuracy of 5m and 10m → ignored if movement < 15m. | Devices that report accuracy (recommended)         |
    | **DistanceBased**       | Ignores updates where device moved < 30m.                                                                        | Devices without accuracy data, reducing GPS jitter |
    | **TimeBased** (default) | Evaluates all updates against geofences but stores only one per 30 seconds per device.                           | High-frequency updates (>1 per 30 seconds)         |
    
    **IMPORTANT**: Filtering affects what gets **stored** and **evaluated against geofences**. AccuracyBased and DistanceBased filtering reduce both storage costs and geofence evaluation costs. TimeBased evaluates every update against geofences but limits storage.
    
    ## Step 2: Send Position Updates
    
    Use `BatchUpdateDevicePosition` to send location data from devices. Each call accepts up to 10 device updates.
    
    ```javascript
    import { BatchUpdateDevicePositionCommand } from "@aws-sdk/client-location";
    
    await client.send(
      new BatchUpdateDevicePositionCommand({
        TrackerName: "my-fleet-tracker",
        Updates: [
          {
            DeviceId: "truck-01",
            Position: [-122.3394, 47.6159], // [longitude, latitude]
            SampleTime: new Date().toISOString(),
            Accuracy: { Horizontal: 10.0 }, // meters, optional but recommended
            PositionProperties: {
              // up to 4 key-value pairs
              VehicleType: "Truck",
              DriverId: "D-1234",
            },
          },
          {
            DeviceId: "truck-02",
            Position: [-122.351, 47.6205],
            SampleTime: new Date().toISOString(),
            Accuracy: { Horizontal: 8.0 },
            PositionProperties: { VehicleType: "Van" },
          },
        ],
      }),
    );
    ```
    
    ### MQTT Ingestion (IoT Devices)
    
    For IoT devices, position updates can be sent via MQTT through AWS IoT Core, avoiding the need to use the AWS SDK directly on constrained devices. Configure an AWS IoT rule with a [Location action](https://docs.aws.amazon.com/iot/latest/developerguide/location-rule-action.html) to forward messages to `BatchUpdateDevicePosition`. This is the preferred path for high-volume IoT fleets. See the [AWS IoT Core docs](https://docs.aws.amazon.com/location/latest/developerguide/tracking-using-mqtt.html) for rule creation steps and message payload format.
    
    ### Update Frequency Guidance
    
    | Scenario                        | Suggested Frequency | Filtering Mode |
    | ------------------------------- | ------------------- | -------------- |
    | Real-time fleet dashboard       | 5–15 seconds        | TimeBased      |
    | Delivery ETA tracking           | 30–60 seconds       | AccuracyBased  |
    | Asset monitoring (low movement) | 1–5 minutes         | DistanceBased  |
    | Periodic check-in               | 15–60 minutes       | DistanceBased  |
    
    ## Step 3: Query Device Positions
    
    ### Current Position — Single Device
    
    ```javascript
    import { GetDevicePositionCommand } from "@aws-sdk/client-location";
    
    const response = await client.send(
      new GetDevicePositionCommand({
        TrackerName: "my-fleet-tracker",
        DeviceId: "truck-01",
      }),
    );
    // response.Position → [-122.3394, 47.6159]
    // response.SampleTime → "2024-01-15T12:00:00Z"
    // response.Accuracy → { Horizontal: 10.0 }
    // response.PositionProperties → { VehicleType: "Truck", DriverId: "D-1234" }
    ```
    
    ### Current Position — Multiple Devices
    
    ```javascript
    import { BatchGetDevicePositionCommand } from "@aws-sdk/client-location";
    
    const response = await client.send(
      new BatchGetDevicePositionCommand({
        TrackerName: "my-fleet-tracker",
        DeviceIds: ["truck-01", "truck-02", "truck-03"],
      }),
    );
    // response.DevicePositions → array of position objects
    // response.Errors → array of devices that failed (check this!)
    ```
    
    ### All Devices (Fleet View)
    
    ```javascript
    import { ListDevicePositionsCommand } from "@aws-sdk/client-location";
    
    const response = await client.send(
      new ListDevicePositionsCommand({
        TrackerName: "my-fleet-tracker",
        MaxResults: 100,
      }),
    );
    // response.Entries → array of { DeviceId, Position, SampleTime, ... }
    // response.NextToken → use for pagination if more devices exist
    ```
    
    ### Position History
    
    Retrieve historical positions for a device within a time range. Useful for route playback, dwell time analysis, and audit trails.
    
    ```javascript
    import { GetDevicePositionHistoryCommand } from "@aws-sdk/client-location";
    
    const response = await client.send(
      new GetDevicePositionHistoryCommand({
        TrackerName: "my-fleet-tracker",
        DeviceId: "truck-01",
        StartTimeInclusive: new Date("2024-01-15T00:00:00Z"),
        EndTimeExclusive: new Date("2024-01-15T23:59:59Z"),
        MaxResults: 100,
      }),
    );
    // response.DevicePositions → array of historical positions, ordered by SampleTime
    // response.NextToken → use for pagination
    ```
    
    **Note**: Position history retention depends on the tracker's position filtering mode. TimeBased filtering stores at most one position per 30 seconds. AccuracyBased and DistanceBased only store positions that pass the filter.
    
    ## Step 4: Display on a Map
    
    Combine tracking data with MapLibre to show devices on an interactive map. See the **dynamic-map** reference for full MapLibre setup.
    
    ```javascript
    // After map loads, add device markers
    map.on("load", async () => {
      const response = await client.send(
        new ListDevicePositionsCommand({
          TrackerName: "my-fleet-tracker",
        }),
      );
    
      response.Entries.forEach((device) => {
        const content = document.createElement("div");
        const title = document.createElement("h4");
        title.textContent = device.DeviceId;
        const lastSeen = document.createElement("p");
        lastSeen.textContent = `Last seen: ${new Date(device.SampleTime).toLocaleString()}`;
        content.append(title, lastSeen);
    
        new maplibregl.Marker({ color: "#FF0000" })
          .setLngLat(device.Position)
          .setPopup(new maplibregl.Popup().setDOMContent(content))
          .addTo(map);
      });
    });
    ```
    
    ### Real-Time Updates
    
    For live tracking, poll for position updates on an interval:
    
    ```javascript
    setInterval(async () => {
      const response = await client.send(
        new ListDevicePositionsCommand({
          TrackerName: "my-fleet-tracker",
        }),
      );
      // Update marker positions on the map
      updateMarkers(response.Entries);
    }, 15000); // every 15 seconds
    ```
    
    **Note**: If markers are **draggable** (e.g., for interactive dashboards), polling will fight with drag by calling `setLngLat()` mid-drag. Pause polling on `dragstart` and resume on `dragend`.
    
    ### Historical Path Visualization
    
    Display a device's historical route as a line on the map. The [`amazon-location-utilities-datatypes-js`](https://github.com/aws-geospatial/amazon-location-utilities-datatypes-js) library provides `devicePositionsToFeatureCollection()` to convert tracking responses into GeoJSON FeatureCollections of Point features — useful for plotting individual position markers. For drawing a connected route line, extract coordinates directly as shown below.
    
    ```javascript
    const history = await client.send(
      new GetDevicePositionHistoryCommand({
        TrackerName: "my-fleet-tracker",
        DeviceId: "truck-01",
        StartTimeInclusive: new Date("2024-01-15T08:00:00Z"),
        EndTimeExclusive: new Date("2024-01-15T17:00:00Z"),
      }),
    );
    
    const coordinates = history.DevicePositions.map((p) => p.Position);
    
    map.addSource("route", {
      type: "geojson",
      data: {
        type: "Feature",
        geometry: { type: "LineString", coordinates },
      },
    });
    
    map.addLayer({
      id: "route-line",
      type: "line",
      source: "route",
      paint: {
        "line-color": "#3b82f6",
        "line-width": 3,
      },
    });
    ```
    
    ## Error Handling
    
    ### Common Errors
    
    | Error                       | HTTP Status | Cause                                                          |
    | --------------------------- | ----------- | -------------------------------------------------------------- |
    | `ResourceNotFoundException` | 404         | Tracker name doesn't exist, or device has never sent an update |
    | `ValidationException`       | 400         | Invalid parameters (coordinate order, missing fields)          |
    | `ThrottlingException`       | 429         | Request rate exceeded — implement exponential backoff          |
    | `AccessDeniedException`     | 403         | IAM or Cognito permissions missing                             |
    
    ### Batch Operation Errors
    
    `BatchUpdateDevicePosition` and `BatchGetDevicePosition` return partial success. Always check the `Errors` array:
    
    ```javascript
    const response = await client.send(
      new BatchUpdateDevicePositionCommand({/* ... */}),
    );
    
    if (response.Errors?.length > 0) {
      response.Errors.forEach((error) => {
        console.error(`Failed device ${error.DeviceId}: ${error.Error.Message}`);
      });
    }
    ```
    
    ### Device Not Found
    
    `GetDevicePosition` throws `ResourceNotFoundException` if the device has never sent a position update, or if all positions have been deleted. Handle this gracefully in fleet dashboards — a missing device is not necessarily an error.
    
    ## Cost Considerations
    
    - Billed per **position update received** and per **position query request**
    - If linked to geofence collections, also billed per **geofence collection evaluation** per update
    - Example: TimeBased filtering with 2 linked collections at 5-second update frequency = 720 update requests + 1,440 geofence evaluations **per device per hour**
    - Use AccuracyBased or DistanceBased filtering to drop unnecessary updates and reduce costs
    - Adjust update frequency to match your use case — not all applications need sub-minute updates
    
    ## Best Practices
    
    - Set `Accuracy.Horizontal` on every update when available — it improves position filtering and geofence evaluation precision
    - Use `PositionProperties` (max 4 key-value pairs) for device metadata that should travel with position data (vehicle type, driver ID, cargo status)
    - Paginate `ListDevicePositions` and `GetDevicePositionHistory` — don't assume all results fit in one response
    - Match update frequency to your use case — over-reporting wastes cost, under-reporting misses events
    - For fleet dashboards, poll `ListDevicePositions` at a slower rate than devices report (e.g., poll every 15s even if devices report every 5s)
    - Link trackers to geofence collections to automatically trigger zone-based alerts — see the **zone-alerts** reference
    - Use `BatchDeleteDevicePositionHistory` to clean up test data or comply with data retention policies
    
    ## Position Integrity
    
    This section covers optional position validation — separate from the core track→query→display flow above. Use `VerifyDevicePosition` to detect GPS spoofing or proxy usage by comparing a device's reported position against an inferred position derived from IP address, Wi-Fi signals, and cell tower data.
    
    ```javascript
    import { VerifyDevicePositionCommand } from "@aws-sdk/client-location";
    
    const response = await client.send(
      new VerifyDevicePositionCommand({
        TrackerName: "my-fleet-tracker",
        DeviceState: {
          DeviceId: "truck-01",
          SampleTime: new Date().toISOString(),
          Position: [-122.3394, 47.6159],
          Accuracy: { Horizontal: 10.0 },
          Ipv4Address: "203.0.113.25",
          WiFiAccessPoints: [{ MacAddress: "AA:BB:CC:DD:EE:FF", Rss: -65 }],
          CellSignals: {
            LteCellDetails: [
              {
                CellId: 1234567,
                Mcc: 310,
                Mnc: 410,
                LocalId: { Earfcn: 5230, Pci: 123 },
              },
            ],
          },
        },
      }),
    );
    ```
    
  • plugins/amazon-location-service/skills/amazon-location-service/references/dynamic-map.md13 KBa158921d0fb4upstream ↗
    # Dynamic Map Rendering
    
    > **Audience Note**: Keywords MUST, SHOULD, MAY in this document indicate requirements for agent recommendations to users, following RFC 2119.
    
    Render interactive maps using MapLibre GL JS with Amazon Location Service.
    
    ## Table of Contents
    
    - [Basic Setup](#basic-setup)
    - [Complete Examples](#complete-examples)
    - [Map Styles](#map-styles)
    - [MapLibre Gotchas](#maplibre-gotchas)
    - [Advanced Features](#advanced-features)
    - [Error Handling](#error-handling)
    - [Best Practices](#best-practices)
    
    ## Basic Setup
    
    ### HTML Structure
    
    ```html
    <!DOCTYPE html>
    <html>
      <head>
        <link
          href="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.css"
          rel="stylesheet"
        />
        <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5"></script>
        <style>
          #map {
            height: 500px;
            width: 100%;
          }
        </style>
      </head>
      <body>
        <div id="map"></div>
        <script src="app.js"></script>
      </body>
    </html>
    ```
    
    ### Minimal Map Initialization
    
    ```javascript
    const API_KEY = "your-api-key";
    const REGION = "us-west-2";
    
    // Direct URL method - REQUIRED
    const styleUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Standard/descriptor?key=${API_KEY}`;
    
    const map = new maplibregl.Map({
      container: "map",
      style: styleUrl,
      center: [-97.7723, 30.2672], // [longitude, latitude] - Zilker Park, Austin
      zoom: 10,
      validateStyle: false, // MUST set to false for faster loading
    });
    ```
    
    ### validateStyle Parameter
    
    **Always set `validateStyle: false`**
    
    - **With false**: Map loads faster, skips unnecessary validation of Amazon's trusted styles
    - **With true** (default): MapLibre validates every style property, adding ~500ms+ load time
    - **Trade-off**: Validation helps catch errors in custom styles, but Amazon styles are pre-validated
    
    ## Complete Examples
    
    ### Map with Markers and Popups
    
    ```javascript
    const API_KEY = "your-api-key";
    const REGION = "us-west-2";
    
    const styleUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Standard/descriptor?key=${API_KEY}`;
    
    const map = new maplibregl.Map({
      container: "map",
      style: styleUrl,
      center: [-97.7723, 30.2672], // Zilker Park, Austin TX
      zoom: 12,
      validateStyle: false,
    });
    
    // Wait for map to load before adding markers
    map.on("load", () => {
      console.log("Map loaded successfully");
    
      // Add marker with popup
      const marker = new maplibregl.Marker({ color: "#FF0000" })
        .setLngLat([-97.7723, 30.2672])
        .setPopup(
          new maplibregl.Popup({ offset: 25 }).setHTML(
            "<h3>Zilker Park</h3><p>Austin, Texas</p>",
          ),
        )
        .addTo(map);
    
      // Add multiple markers from data
      const locations = [
        { name: "Barton Springs Pool", coords: [-97.7708, 30.2639] },
        { name: "Zilker Botanical Garden", coords: [-97.7716, 30.2707] },
      ];
    
      locations.forEach((loc) => {
        new maplibregl.Marker()
          .setLngLat(loc.coords)
          .setPopup(new maplibregl.Popup().setHTML(`<h4>${loc.name}</h4>`))
          .addTo(map);
      });
    });
    
    // Handle errors
    map.on("error", (e) => {
      console.error("Map error:", e);
      // Show user-friendly error message
    });
    ```
    
    ## Map Styles
    
    ### Available Styles
    
    Amazon Location provides four map styles:
    
    - **Standard** (default) - General purpose map
    - **Monochrome** - Simplified single-color palette
    - **Hybrid** - Satellite imagery with labels
    - **Satellite** - Satellite imagery only
    
    ```javascript
    // Standard style (default)
    const styleUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Standard/descriptor?key=${API_KEY}`;
    
    // Other styles
    const monochromeUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Monochrome/descriptor?key=${API_KEY}`;
    const hybridUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Hybrid/descriptor?key=${API_KEY}`;
    const satelliteUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Satellite/descriptor?key=${API_KEY}`;
    ```
    
    ### Common Customizations
    
    **Dark mode:**
    
    ```javascript
    const styleUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Standard/descriptor?key=${API_KEY}&color-scheme=Dark`;
    ```
    
    **3D buildings:**
    
    ```javascript
    const styleUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Standard/descriptor?key=${API_KEY}&buildings=Buildings3D`;
    ```
    
    **Traffic overlay:**
    
    ```javascript
    const styleUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Standard/descriptor?key=${API_KEY}&traffic=All`;
    ```
    
    **Combined customizations:**
    
    ```javascript
    const styleUrl = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/Standard/descriptor?key=${API_KEY}&color-scheme=Dark&buildings=Buildings3D&traffic=All`;
    ```
    
    For all customization options (terrain, political views, travel modes, etc.), see the [GetStyleDescriptor API Reference](https://docs.aws.amazon.com/location/latest/APIReference/API_geomaps_GetStyleDescriptor.html).
    
    ### Feature Compatibility by Map Style
    
    Not all features are available on every map style. Applying an unsupported feature parameter to an incompatible style will have no effect.
    
    | Feature                      | Standard | Monochrome | Hybrid | Satellite |
    | ---------------------------- | -------- | ---------- | ------ | --------- |
    | Color Scheme (Light/Dark)    | Yes      | Yes        | No     | No        |
    | Terrain (Hillshade)          | Yes      | Yes        | No     | No        |
    | Terrain (Terrain3D)          | Yes      | Yes        | Yes    | Yes       |
    | Contour Density              | Yes      | Yes        | Yes    | No        |
    | Traffic                      | Yes      | No         | No     | No        |
    | Buildings (3D)               | Yes      | Yes        | No     | No        |
    | Travel Modes (Transit/Truck) | Yes      | No         | No     | No        |
    | Language                     | Yes      | Yes        | Yes    | No        |
    | Political View               | Yes      | Yes        | Yes    | No        |
    
    > **Note**: Traffic and Travel Modes are only supported on the Standard map style. If you need real-time traffic visualization or transit/truck overlays, you must use Standard. See [Map concepts](https://docs.aws.amazon.com/location/latest/developerguide/maps-concepts.html) for the full compatibility matrix.
    
    ### Style Change Persistence
    
    Calling `map.setStyle()` completely replaces the map's style object. This destroys all custom sources and layers added via `map.addSource()` / `map.addLayer()` — route lines, geofence polygons, heatmaps, cluster layers, etc. DOM-based elements like `maplibregl.Marker` survive because they exist outside the style.
    
    Any code that switches map styles MUST re-add custom layers after the new style loads. The recommended pattern is:
    
    1. Store the data needed to recreate custom layers (coordinates, paint options, etc.)
    2. Listen for `style.load` after calling `setStyle()` and re-add the layers
    3. Clear stored data only when layers are intentionally removed
    
    ```javascript
    // Track data for any custom layers that need to survive style changes
    let customLayerData = null;
    
    function addCustomLayer(sourceId, layerId, geojsonData, paintOptions) {
      customLayerData = { sourceId, layerId, geojsonData, paintOptions };
    
      map.addSource(sourceId, { type: "geojson", data: geojsonData });
      map.addLayer({
        id: layerId,
        type: "line",
        source: sourceId,
        paint: paintOptions,
      });
    }
    
    function removeCustomLayer() {
      if (map.getLayer(customLayerData?.layerId))
        map.removeLayer(customLayerData.layerId);
      if (map.getSource(customLayerData?.sourceId))
        map.removeSource(customLayerData.sourceId);
      customLayerData = null;
    }
    
    function setMapStyle(styleName) {
      const url = `https://maps.geo.${REGION}.amazonaws.com/v2/styles/${styleName}/descriptor?key=${API_KEY}`;
      map.setStyle(url);
    
      map.once("style.load", () => {
        if (customLayerData) {
          addCustomLayer(
            customLayerData.sourceId,
            customLayerData.layerId,
            customLayerData.geojsonData,
            customLayerData.paintOptions,
          );
        }
      });
    }
    ```
    
    ## MapLibre Gotchas
    
    ### `map.loaded()` goes false after `addSource` — causing hangs
    
    Calling `map.addSource()` or `map.addLayer()` inside a `"load"` callback sets internal dirty flags, making `loaded()` temporarily return `false`. The `"load"` event will **not** re-fire because the map tracks that it already fired once ([`map.ts#L4326`](https://github.com/maplibre/maplibre-gl-js/blob/v6.4.1/src/ui/map.ts#L4326)).
    
    Any code that runs after an async delay and gates on `map.loaded()` can hang forever:
    
    ```javascript
    // In a "load" callback: add a source
    map.once("load", () => {
      map.addSource("zones", { type: "geojson", data: geojson });
      // map.loaded() is now FALSE (dirty flags set by addSource)
    });
    
    // Later, after an async API call:
    if (!map.loaded()) {
      // BUG: loaded() is false, but "load" already fired and won't re-fire → hangs
      await new Promise((resolve) => map.on("load", resolve));
    }
    ```
    
    **Correct patterns:**
    
    - Do all source/layer work inside a single `map.on("load", async () => { ... })` callback — async work inside the callback is fine
    - If you need to wait for sources to settle after load, use `map.once("idle", callback)` which re-fires whenever everything is loaded and stable ([`map.ts#L4350`](https://github.com/maplibre/maplibre-gl-js/blob/v6.4.1/src/ui/map.ts#L4350))
    - Markers (DOM-based) can be added at any time — they do not need `"load"` or `"idle"`
    
    ### Draggable Markers
    
    Use MapLibre's **default marker** with `draggable: true` for reliable drag behavior. Custom HTML element markers (`{ element: el, draggable: true }`) do not handle drag events reliably in MapLibre v5.
    
    ```javascript
    // Reliable — default marker with drag
    const marker = new maplibregl.Marker({ color: "#3b82f6", draggable: true })
      .setLngLat([-122.34, 47.62])
      .addTo(map);
    
    marker.on("dragend", () => {
      const lngLat = marker.getLngLat();
      console.log("Dropped at:", lngLat.lng, lngLat.lat);
    });
    ```
    
    ## Advanced Features
    
    ### Navigation Controls
    
    ```javascript
    map.on("load", () => {
      // Add zoom and rotation controls
      map.addControl(new maplibregl.NavigationControl(), "top-right");
    
      // Add geolocation control
      map.addControl(
        new maplibregl.GeolocateControl({
          positionOptions: { enableHighAccuracy: true },
          trackUserLocation: true,
        }),
        "top-right",
      );
    
      // Add scale control
      map.addControl(new maplibregl.ScaleControl(), "bottom-left");
    });
    ```
    
    ### Custom Markers with HTML
    
    ```javascript
    // Create custom marker element
    const el = document.createElement("div");
    el.className = "custom-marker";
    el.style.width = "30px";
    el.style.height = "30px";
    el.style.backgroundImage = "url(marker-icon.png)";
    
    new maplibregl.Marker({ element: el })
      .setLngLat([-122.4194, 37.7749])
      .addTo(map);
    ```
    
    ### Map Event Handling
    
    ```javascript
    // Click event
    map.on("click", (e) => {
      console.log("Clicked at:", e.lngLat);
      new maplibregl.Marker().setLngLat(e.lngLat).addTo(map);
    });
    
    // Move event
    map.on("move", () => {
      console.log("Center:", map.getCenter());
      console.log("Zoom:", map.getZoom());
    });
    ```
    
    ## Error Handling
    
    ### Common Errors
    
    ```javascript
    map.on("error", (e) => {
      console.error("Map error:", e.error);
    
      if (e.error.status === 401) {
        // Invalid API key
        showError("Authentication failed. Check your API key.");
      } else if (e.error.status === 403) {
        // API key lacks permissions
        showError("API key does not have permission to access maps.");
      } else if (e.error.message.includes("Failed to fetch")) {
        // Network error
        showError("Network error. Please check your connection.");
      } else {
        showError("Failed to load map. Please try again.");
      }
    });
    
    function showError(message) {
      document.getElementById("map").innerHTML =
        `<div style="padding: 20px; color: red;">${message}</div>`;
    }
    ```
    
    ## Best Practices
    
    ### Performance
    
    - **Set validateStyle: false**: Saves 500ms+ on initial load
    - **Lazy load MapLibre**: Only load map library when user navigates to map view
    - **Limit markers**: Use clustering for 100+ markers (maplibre-gl-cluster)
    
    ### Security
    
    - **Restrict API key**: Use API key permissions to limit to specific operations
    - **Domain restrictions**: Configure API key to only work from your domains
    - **Never expose in public repos**: Use environment variables for API keys
    
    ### User Experience
    
    - **Show loading state**: Display spinner while map initializes
    - **Handle errors gracefully**: Show user-friendly error messages, not console errors
    - **Responsive sizing**: Ensure map container has explicit height
    - **Touch support**: MapLibre automatically handles touch events on mobile
    
    ### Debugging
    
    - **Check browser console**: Map errors appear in console
    - **Verify API key**: Test with simple example first
    - **Check network tab**: Verify style descriptor and tile requests succeed
    - **Test validateStyle: true**: During development only, to catch custom style issues
    
  • plugins/amazon-location-service/skills/amazon-location-service/references/google-migration-android.md25 KBd1897b8aef6aupstream ↗
    # 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](#migration-overview)
    - [Setup and Dependencies](#setup-and-dependencies)
    - [Authentication](#authentication)
    - [API Mappings Reference](#api-mappings-reference)
    - [Helper and Math Libraries](#helper-and-math-libraries)
    - [Migration Patterns](#migration-patterns)
    - [Migration Guide](#migration-guide)
    
    ## Migration Overview
    
    **Key differences from Google Maps:**
    
    | Aspect             | Google Maps SDK               | Amazon Location Service               |
    | ------------------ | ----------------------------- | ------------------------------------- |
    | **Drop-in SDK**    | ❌ Not available              | Direct AWS SDK migration required     |
    | **Map rendering**  | Google Maps renderer          | MapLibre Native Android               |
    | **API style**      | Callback/listener-based       | Kotlin coroutines / suspend functions |
    | **Coordinates**    | `LatLng(lat, lng)`            | `listOf(lng, lat)` - GeoJSON order    |
    | **Authentication** | API Key in manifest           | AWS API Key or Cognito credentials    |
    | **SDK packages**   | `com.google.android.gms.maps` | `aws.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`:**
    
    ```kotlin
    // 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:**
    
    ```kotlin
    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:**
    
    ```kotlin
    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:**
    
    ```xml
    <!-- Remove this -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="YOUR_GOOGLE_API_KEY"/>
    ```
    
    **Add permissions (if not already present):**
    
    ```xml
    <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.
    
    ### API Key Authentication (Recommended for Maps, Places, Routes)
    
    **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).
    
    ```kotlin
    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:**
    
    ```kotlin
    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)
    
    ```kotlin
    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 Android                          | Amazon Location Android | Migration Notes                       |
    | -------------------------------------------- | ----------------------- | ------------------------------------- |
    | `PlacesClient.findCurrentPlace()`            | `SearchNearbyCommand`   | Use device location with SearchNearby |
    | `PlacesClient.fetchPlace()`                  | `GetPlaceCommand`       | Fetch place details by PlaceId        |
    | `PlacesClient.findAutocompletePredictions()` | `AutocompleteCommand`   | Address autocomplete                  |
    | N/A (use Autocomplete widget)                | `SuggestCommand`        | Place name suggestions                |
    
    **Example - Place Search:**
    
    ```kotlin
    // 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 Android              | Amazon Location Android | Migration Notes                           |
    | -------------------------------- | ----------------------- | ----------------------------------------- |
    | `Geocoder.getFromLocationName()` | `GeocodeCommand`        | Forward geocoding (address → coordinates) |
    | `Geocoder.getFromLocation()`     | `ReverseGeocodeCommand` | Reverse geocoding (coordinates → address) |
    
    **Example - Geocoding:**
    
    ```kotlin
    // 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 Android              | Amazon Location Android       | Migration Notes        |
    | -------------------------------- | ----------------------------- | ---------------------- |
    | `DirectionsApi.newRequest()`     | `CalculateRoutesCommand`      | Route calculation      |
    | `DistanceMatrixApi.newRequest()` | `CalculateRouteMatrixCommand` | Many-to-many distances |
    
    **Example - Directions:**
    
    ```kotlin
    // 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 Android       | Amazon Location Android    | Migration Notes            |
    | ------------------------- | -------------------------- | -------------------------- |
    | `MapFragment` / `MapView` | `MapView` (MapLibre)       | Different rendering engine |
    | `GoogleMap.addMarker()`   | `SymbolManager.create()`   | MapLibre marker API        |
    | `GoogleMap.addPolyline()` | Add LineLayer              | GeoJSON-based rendering    |
    | `GoogleMap.moveCamera()`  | `MapLibreMap.moveCamera()` | Similar camera API         |
    
    **Example - Display Map:**
    
    ```kotlin
    // 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 Android | Amazon Location Alternative          | Package                                                                 |
    | ------------------- | ------------------------------------ | ----------------------------------------------------------------------- |
    | `PolyUtil.encode()` | `Polyline.encodeFromLngLatArray`     | [`aws-geospatial/polyline`](https://github.com/aws-geospatial/polyline) |
    | `PolyUtil.decode()` | `Polyline.decodeToLineStringFeature` | [`aws-geospatial/polyline`](https://github.com/aws-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`](https://github.com/aws-geospatial/polyline) library, which decodes FlexiblePolyline directly into MapLibre-ready GeoJSON.
    
    Add the dependency: `implementation("software.amazon.location:polyline:0.1.0")`.
    
    ```kotlin
    // 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 Android                      | Amazon Location Alternative    | Approach                 |
    | ---------------------------------------- | ------------------------------ | ------------------------ |
    | `SphericalUtil.computeDistanceBetween()` | Use Haversine formula          | Implement or use library |
    | `PolyUtil.containsLocation()`            | Use point-in-polygon algorithm | Implement or use library |
    | `PolyUtil.isLocationOnPath()`            | Use point-to-line distance     | Implement or use library |
    
    **Example - Distance Calculation:**
    
    ```kotlin
    // 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](https://github.com/mapbox/mapbox-java) - 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).
    
    ```kotlin
    // 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:**
    
    ```kotlin
    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:**
    
    ```kotlin
    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:**
    
    ```kotlin
    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:**
    
    ```kotlin
    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:**
    
    ```kotlin
    import com.google.android.gms.maps.model.PolylineOptions
    
    val polylineOptions = PolylineOptions()
        .addAll(decodedPath)
        .color(Color.BLUE)
        .width(5f)
    
    googleMap.addPolyline(polylineOptions)
    ```
    
    **Amazon Location:**
    
    ```kotlin
    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
    
    - **[Android Application Migration Guide](https://location.aws.com/migrate-an-android-app)** - Step-by-step guide for Android apps
    
    ### AWS SDK Documentation
    
    - **[AWS SDK for Kotlin](https://aws.amazon.com/sdk-for-kotlin/)** - Official SDK documentation
    - **[Amazon Location Service Developer Guide](https://docs.aws.amazon.com/location/)** - Service documentation
    - **[API Reference](https://docs.aws.amazon.com/location/latest/APIReference/)** - Complete API reference
    
    ### MapLibre Documentation
    
    - **[MapLibre Native Android](https://maplibre.org/maplibre-native/android/)** - Map rendering documentation
    - **[MapLibre Android Examples](https://github.com/maplibre/maplibre-native/tree/main/platform/android)** - Code examples
    
    ## 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
    
    ```kotlin
    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
    
    ```kotlin
    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
    
    - **AWS SDK Issues:** [GitHub - AWS SDK Kotlin](https://github.com/awslabs/aws-sdk-kotlin)
    - **MapLibre Issues:** [GitHub - MapLibre Native](https://github.com/maplibre/maplibre-native)
    - **Amazon Location:** [AWS Forums](https://forums.aws.amazon.com/forum.jspa?forumID=356)
    
  • plugins/amazon-location-service/skills/amazon-location-service/references/google-migration-ios.md27 KBb728f1fae27eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • plugins/amazon-location-service/skills/amazon-location-service/references/google-migration-web.md31 KB31db5004e006upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • plugins/amazon-location-service/skills/amazon-location-service/references/places-search.md18 KB0d7ae91f54e0upstream ↗
    # Places Search
    
    > **Audience Note**: Keywords MUST, SHOULD, MAY in this document indicate requirements for agent recommendations to users, following RFC 2119.
    
    Search for places, points of interest, businesses, and addresses using Amazon Location Service Places APIs.
    
    ## Table of Contents
    
    - [Overview](#overview)
    - [API Selection Guide](#api-selection-guide)
    - [Additional Features](#additional-features)
    - [SearchText Examples](#searchtext-examples)
    - [SearchNearby Examples](#searchnearby-examples)
    - [Suggest Examples](#suggest-examples)
    - [Response Handling](#response-handling)
    - [Error Handling](#error-handling)
    - [Best Practices](#best-practices)
    
    ## Overview
    
    Amazon Location provides three main search APIs:
    
    - **SearchText** - General text-based search ("tacos in Austin")
    - **SearchNearby** - Location-proximity search (find restaurants within 5km)
    - **Suggest** - Predictive search with partial/misspelled input
    - **GetPlace** - Fetch complete details by PlaceId
    
    ## API Selection Guide
    
    | Use Case                                   | API          | Example                                           |
    | ------------------------------------------ | ------------ | ------------------------------------------------- |
    | User searches for business/POI by name     | SearchText   | "Starbucks near downtown"                         |
    | User searches by category                  | SearchText   | "restaurants in Vancouver"                        |
    | Find places near a point on map            | SearchNearby | Find gas stations within 10km of current location |
    | Type-ahead for place names (not addresses) | Suggest      | "star" → Starbucks, Starwood Hotel                |
    | Type-ahead for addresses                   | Autocomplete | Use address-input reference instead               |
    | Get full details after search              | GetPlace     | Fetch hours, contact info by PlaceId              |
    
    ## Additional Features
    
    Places APIs support an `AdditionalFeatures` parameter that returns extra details beyond the default response. Request them by adding `AdditionalFeatures: ["Contact", "TimeZone", ...]` to your API call.
    
    > **Pricing note**: Requesting additional features moves the request into the **Advanced** pricing bucket, which is priced higher than the default **Core** bucket. Review [Places pricing](https://docs.aws.amazon.com/location/latest/developerguide/places-pricing.html) before enabling them in production.
    
    | Feature       | GetPlace | SearchText | SearchNearby | Suggest |
    | ------------- | -------- | ---------- | ------------ | ------- |
    | Contact       | Yes      | Yes        | Yes          | No      |
    | Opening Hours | Yes      | Yes        | Yes          | No      |
    | Time Zone     | Yes      | Yes        | Yes          | Yes     |
    | Phonemes      | Yes      | Yes        | Yes          | Yes     |
    | Access Points | Yes      | Yes        | Yes          | Yes     |
    
    For the full feature-by-API matrix (including Geocode, ReverseGeocode, and Autocomplete), see [Additional features](https://docs.aws.amazon.com/location/latest/developerguide/additional-features.html).
    
    ### Contacts and Opening Hours
    
    Contact and opening hours data is available on GetPlace, SearchText, and SearchNearby. Request both by including `"Contact"` in the `AdditionalFeatures` array. The valid `AdditionalFeatures` enum values are `TimeZone`, `Phonemes`, `Access`, and `Contact` (GetPlace also supports `SecondaryAddresses`). There is no separate `"OpeningHours"` enum value — requesting `"Contact"` returns both contact details and opening hours.
    
    Contacts can include:
    
    - **Phone number** — primary contact number, may include international dialing codes
    - **Email address** — primary contact email from the public listing
    - **Website** — link to the official site
    
    Opening hours can include:
    
    - **Regular hours** — standard weekly schedule (e.g., Mon–Fri 9 AM–5 PM)
    - **Special hours** — holiday or event overrides to the regular schedule
    - **Open now** — whether the location is currently open based on local time
    
    ```javascript
    // Request contacts and opening hours
    const command = new amazonLocationClient.places.SearchTextCommand({
      QueryText: "coffee shops in Austin",
      AdditionalFeatures: ["Contact"],
      MaxResults: 5,
    });
    
    const response = await client.send(command);
    
    response.ResultItems.forEach((place) => {
      console.log(place.Title);
      console.log("Phone:", place.Contacts?.Phones?.[0]?.Value);
      console.log("Website:", place.Contacts?.Websites?.[0]?.Value);
      console.log("Hours:", place.OpeningHours);
    });
    ```
    
    For more details, see [Contacts and opening hours](https://docs.aws.amazon.com/location/latest/developerguide/contacts-opening-hours.html).
    
    ## SearchText Examples
    
    For exact request parameters and response structure, see the [SearchText API Reference](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_SearchText.html).
    
    ### Basic Text Search
    
    ```javascript
    const authHelper = amazonLocationClient.withAPIKey(API_KEY, REGION);
    const client = new amazonLocationClient.GeoPlacesClient(
      authHelper.getClientConfig(),
    );
    
    async function searchPlaces(query) {
      try {
        const command = new amazonLocationClient.places.SearchTextCommand({
          QueryText: query,
          MaxResults: 10,
        });
    
        const response = await client.send(command);
    
        // Display results
        response.ResultItems.forEach((place) => {
          console.log(place.Title); // "Starbucks"
          console.log(place.Address?.Label); // "123 Main St, Austin, TX"
          console.log(place.Position); // [lon, lat]
          // Categories are objects: { Id: string, Name: string, LocalizedName?: string, Primary?: boolean }
          console.log(place.Categories); // [{ Id: "9000", Name: "Coffee Shop" }, { Id: "5814", Name: "Café" }]
          console.log(place.PlaceId); // For fetching details
        });
    
        return response.ResultItems;
      } catch (error) {
        console.error("Search error:", error);
        return [];
      }
    }
    
    // Usage
    searchPlaces("coffee shops in Austin");
    ```
    
    ### Search with Geographic Bias
    
    ```javascript
    // Bias results toward a specific location
    async function searchNear(query, biasPosition) {
      const command = new amazonLocationClient.places.SearchTextCommand({
        QueryText: query,
        BiasPosition: biasPosition, // [lon, lat] - prefer results near here
        MaxResults: 10,
      });
    
      const response = await client.send(command);
      return response.ResultItems;
    }
    
    // Usage - find tacos near Austin
    searchNear("tacos", [-97.7431, 30.2747]);
    ```
    
    ### Search with Category Filter
    
    **Important:** Amazon Location uses specific Category IDs for filtering. Common examples include `restaurant`, `coffee_shop`, `grocery`, `hotel`, `bank`, `fueling_station`, `pharmacy`, and `hospital`. See the complete list in the [Place Categories Documentation](https://docs.aws.amazon.com/location/latest/developerguide/places-filtering.html#place-categories).
    
    **Note:** Category filtering (`IncludeCategories`) is only supported by `SearchNearby`, not `SearchText` — `SearchText` silently ignores it. To filter by category, use `SearchNearbyCommand` with a `QueryPosition`.
    
    ```javascript
    async function searchByCategory(position, categories) {
      const command = new amazonLocationClient.places.SearchNearbyCommand({
        QueryPosition: position, // [lon, lat]
        Filter: {
          IncludeCategories: categories, // Filter by valid category IDs
        },
        MaxResults: 20,
      });
    
      const response = await client.send(command);
      return response.ResultItems;
    }
    
    // Usage - find only restaurants and coffee shops near a location
    searchByCategory([-97.7431, 30.2747], ["restaurant", "coffee_shop"]);
    ```
    
    ### Search with Bounding Box
    
    ```javascript
    // Restrict search to specific geographic area
    async function searchInBounds(query, boundingBox) {
      const command = new amazonLocationClient.places.SearchTextCommand({
        QueryText: query,
        Filter: {
          BoundingBox: boundingBox, // [west, south, east, north]
        },
        MaxResults: 10,
      });
    
      const response = await client.send(command);
      return response.ResultItems;
    }
    
    // Usage - find hotels in downtown Austin area
    const austinDowntown = [-97.7535, 30.2586, -97.7327, 30.2747];
    searchInBounds("hotels", austinDowntown);
    ```
    
    ## SearchNearby Examples
    
    For exact request parameters and response structure, see the [SearchNearby API Reference](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_SearchNearby.html).
    
    ### Basic Proximity Search
    
    ```javascript
    async function searchNearby(position, radius, categories = null) {
      const params = {
        QueryPosition: position, // [lon, lat]
        MaxResults: 20,
      };
    
      // Optional: filter by categories
      if (categories) {
        params.Filter = { IncludeCategories: categories };
      }
    
      // Optional: specify radius (default is context-dependent)
      if (radius) {
        params.QueryRadius = radius; // in meters
      }
    
      const command = new amazonLocationClient.places.SearchNearbyCommand(params);
    
      try {
        const response = await client.send(command);
    
        // Results are already sorted by distance
        response.ResultItems.forEach((place) => {
          console.log(place.Title);
          console.log(place.Distance, "meters away");
          console.log(place.Position);
        });
    
        return response.ResultItems;
      } catch (error) {
        console.error("Nearby search error:", error);
        return [];
      }
    }
    
    // Usage - find restaurants within 5km
    const userLocation = [-97.7431, 30.2747];
    searchNearby(userLocation, 5000, ["restaurant"]);
    ```
    
    ### Find Nearest of Type
    
    ```javascript
    // Find single nearest place of a specific type
    async function findNearest(position, category) {
      const command = new amazonLocationClient.places.SearchNearbyCommand({
        QueryPosition: position,
        Filter: { IncludeCategories: [category] },
        MaxResults: 1, // Just the nearest
      });
    
      const response = await client.send(command);
    
      if (response.ResultItems.length === 0) {
        return null;
      }
    
      return response.ResultItems[0];
    }
    
    // Usage - find nearest fueling station
    const nearest = await findNearest([-97.7431, 30.2747], "fueling_station");
    if (nearest) {
      console.log(`Nearest: ${nearest.Title}, ${nearest.Distance}m away`);
    }
    ```
    
    ### Search with Map Integration
    
    ```javascript
    // Display nearby search results on map
    async function showNearbyOnMap(map, position, category) {
      const results = await searchNearby(position, 2000, [category]);
    
      // Clear existing markers
      document.querySelectorAll(".nearby-marker").forEach((el) => el.remove());
    
      // Add markers for each result
      results.forEach((place, index) => {
        const marker = new maplibregl.Marker({ color: "#FF0000" })
          .setLngLat(place.Position)
          .setPopup(
            new maplibregl.Popup().setHTML(`
              <h4>${place.Title}</h4>
              <p>${place.Address?.Label || ""}</p>
              <p>${Math.round(place.Distance)}m away</p>
            `),
          )
          .addTo(map);
    
        marker.getElement().classList.add("nearby-marker");
      });
    
      // Fit map to show all results
      if (results.length > 0) {
        const bounds = new maplibregl.LngLatBounds();
        results.forEach((place) => bounds.extend(place.Position));
        bounds.extend(position); // Include search center
        map.fitBounds(bounds, { padding: 50 });
      }
    }
    ```
    
    ## Suggest Examples
    
    For exact request parameters and response structure, see the [Suggest API Reference](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_Suggest.html).
    
    ### Suggest Response Structure
    
    Suggest returns items with a `SuggestResultItemType` that can be `"Place"` or `"Query"`:
    
    - **Place results**: Have `item.Place.PlaceId`, `item.Place.Position`, `item.Place.Address` — use `PlaceId` with `GetPlace` for full details
    - **Query results**: Have `item.Query.QueryText` — these are search refinement suggestions, not actual places
    
    Always check `item.Place?.PlaceId` before attempting to call `GetPlace`.
    
    ### Predictive Place Search
    
    ```javascript
    // Like Autocomplete but for places/POIs (not just addresses)
    async function suggestPlaces(partialQuery, biasPosition = null) {
      const params = {
        QueryText: partialQuery,
        MaxResults: 5,
      };
    
      if (biasPosition) {
        params.BiasPosition = biasPosition;
      }
    
      const command = new amazonLocationClient.places.SuggestCommand(params);
    
      try {
        const response = await client.send(command);
    
        response.ResultItems.forEach((item) => {
          console.log(item.Title); // "Starbucks"
          console.log(item.Place?.PlaceId); // For fetching full details
          console.log(item.SuggestResultItemType); // "Place" or "Query"
        });
    
        return response.ResultItems;
      } catch (error) {
        console.error("Suggest error:", error);
        return [];
      }
    }
    
    // Usage - type-ahead for place search
    document.getElementById("place-search").addEventListener("input", async (e) => {
      const query = e.target.value;
    
      if (query.length < 3) return;
    
      const suggestions = await suggestPlaces(query);
    
      // Display suggestions (similar to autocomplete)
      displaySuggestions(suggestions);
    });
    ```
    
    ## Response Handling
    
    For exact request parameters and response structure for fetching place details, see the [GetPlace API Reference](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_GetPlace.html).
    
    ### Parse Place Details
    
    ```javascript
    function parsePlaceResult(place) {
      return {
        id: place.PlaceId,
        name: place.Title,
        address: place.Address?.Label || "Address not available",
        coordinates: {
          lat: place.Position[1],
          lon: place.Position[0],
        },
        categories: (place.Categories || []).map((c) => c.Name), // Category is { Id, Name, LocalizedName?, Primary? }
        primaryCategory: place.Categories?.find((c) => c.Primary)?.Name,
        distance: place.Distance, // Only in SearchNearby results
    
        // Optional fields - check before using
        phone: place.Contacts?.Phones?.[0]?.Value,
        website: place.Contacts?.Websites?.[0]?.Value,
    
        // Use GetPlace for more details
        hasMoreDetails: !!place.PlaceId,
      };
    }
    
    // Usage
    const results = await searchPlaces("coffee");
    const parsed = results.map(parsePlaceResult);
    ```
    
    ### Fetch Complete Details
    
    ```javascript
    // Get full details including hours, contact info
    async function getPlaceDetails(placeId) {
      const command = new amazonLocationClient.places.GetPlaceCommand({
        PlaceId: placeId,
      });
    
      try {
        const response = await client.send(command);
    
        return {
          name: response.Title,
          address: response.Address,
          position: response.Position,
          categories: response.Categories,
          contacts: {
            phones: response.Contacts?.Phones || [],
            websites: response.Contacts?.Websites || [],
            emails: response.Contacts?.Emails || [],
          },
          openingHours: response.OpeningHours || [],
          accessPoints: response.AccessPoints || [], // Entrances
          timeZone: response.TimeZone,
        };
      } catch (error) {
        console.error("GetPlace error:", error);
        return null;
      }
    }
    
    // Usage - user clicks on search result to see details
    async function showPlaceDetails(placeId) {
      const details = await getPlaceDetails(placeId);
    
      if (details) {
        console.log("Phone:", details.contacts.phones[0]?.Value);
        console.log("Hours:", details.openingHours);
      }
    }
    ```
    
    ## Error Handling
    
    ### Common Errors
    
    ```javascript
    async function searchWithErrorHandling(query) {
      try {
        const command = new amazonLocationClient.places.SearchTextCommand({
          QueryText: query,
          MaxResults: 10,
        });
    
        const response = await client.send(command);
    
        if (response.ResultItems.length === 0) {
          // No results found
          showMessage("No places found. Try a different search.");
          return [];
        }
    
        return response.ResultItems;
      } catch (error) {
        // API errors
        if (error.name === "ValidationException") {
          showMessage("Invalid search query. Please check your input.");
        } else if (error.name === "AccessDeniedException") {
          showMessage("API key lacks permission for place search.");
        } else if (error.name === "ThrottlingException") {
          showMessage("Too many requests. Please wait and try again.");
        } else {
          showMessage("Search failed. Please try again.");
        }
    
        console.error("Search error:", error);
        return [];
      }
    }
    ```
    
    ### Retry with Fallback
    
    ```javascript
    // Try nearby search, fall back to text search if no results
    async function searchWithFallback(query, position) {
      // Try nearby search first
      let results = await searchNearby(position, 5000);
    
      if (results.length === 0) {
        console.log("No nearby results, trying text search...");
        // Fall back to text search with position bias
        results = await searchNear(query, position);
      }
    
      return results;
    }
    ```
    
    ## Best Practices
    
    ### Performance
    
    - **Debounce search input**: Wait 300ms after user stops typing
    - **Consider pricing for caching**: If storing results beyond temporary session caching, review [Places API Stored Pricing](https://docs.aws.amazon.com/location/latest/developerguide/places-pricing.html#stored-pricing) and use `IntendedUse: "Storage"` parameter.
    - **Limit MaxResults**: Request only what you'll display (10-20 typically)
    - **Cancel in-flight requests**: Cancel previous search when user types new query
    
    ### User Experience
    
    - **Show loading state**: Spinner or skeleton UI during search
    - **Display distance**: Show distance for SearchNearby results
    - **Group by category**: Organize results by Categories
    - **Pagination**: Load more results as user scrolls
    - **Empty states**: Helpful message when no results ("Try different keywords")
    
    ### Data Quality
    
    - **Validate coordinates**: Ensure Position is valid [lon, lat]
    - **Handle missing fields**: Not all places have phone/website/hours
    - **Use PlaceId**: Store PlaceId for future GetPlace calls, not full details
    - **Respect Categories**: Use Categories array for filtering and display
    
    ### Search Optimization
    
    - **Use BiasPosition**: Improves relevance for location-aware searches
    - **Combine filters**: Use Categories + BoundingBox for precise results
    - **Choose right API**: SearchText for queries, SearchNearby for proximity
    - **Prefer SearchNearby**: For "near me" features (faster, more relevant)
    
    ### Error Handling
    
    - **Handle no results**: Suggest alternative searches or expand radius
    - **Show partial results**: Display what you have even if some fail
    - **Retry on network errors**: Retry once after brief delay
    - **Log for debugging**: Log errors with search parameters for troubleshooting
    
  • plugins/amazon-location-service/skills/amazon-location-service/references/web-javascript.md15 KB36bc6996c160upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • plugins/amazon-location-service/skills/amazon-location-service/references/zone-alerts.md13 KB139941bbc979upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/awslabs-agent-plugins-plugins-amazon-location-service-skills-amazon-location-ser.md

// REPO STATS

943 stars
15 open issues
Last commit: 5d ago