Getting started overview

The Hong Kong GeoData Store offers a suite of publicly available geospatial services, with its Geocoding API being a primary component for developers needing to work with Hong Kong-specific location data. This API allows for the conversion of Hong Kong addresses into geographical coordinates (latitude and longitude) and vice-versa, a process known as geocoding and reverse geocoding, respectively. The service is provided by the Hong Kong government and is free for both non-commercial and commercial use, subject to its terms and conditions.

To begin using the Hong Kong GeoData Store's Geocoding API, developers typically follow a three-step process:

  1. Account Registration & Key Generation: Sign up on the official GeoData Store portal to obtain the necessary API credentials.
  2. API Request Construction: Formulate an HTTP GET request to the Geocoding API endpoint, including the obtained API key and the address or coordinates to process.
  3. Response Handling: Parse the JSON response, which will contain the geocoded information or an error message.

This guide will walk through these steps to ensure a successful first interaction with the API.

Quick Reference Table

Step What to Do Where
1. Register for Account Create a user account. Hong Kong GeoData Store homepage
2. Obtain API Key Locate and copy your unique API key from your account dashboard. Account dashboard on GeoData Store portal
3. Review API Docs Understand endpoint, parameters, and response format. Geocoding API Specification
4. Make First Request Send an HTTP GET request with your API key and query. Your preferred development environment (e.g., cURL, Postman, browser)
5. Parse Response Extract relevant geocoding data from the JSON output. Your application code

Create an account and get keys

Access to the Hong Kong GeoData Store Geocoding API requires an API key for authentication. This key identifies your application and ensures compliance with the service's terms of use. The process for obtaining an API key involves registering on the official GeoData Store portal.

  1. Navigate to the GeoData Store Portal: Open your web browser and go to the official Hong Kong GeoData Store website.
  2. Locate Registration: Look for a 'Register' or 'Sign Up' option, typically found in the header or footer of the page.
  3. Complete Registration Form: Provide the required information, which may include your name, email address, organization details, and agreement to the terms and conditions. Ensure all mandatory fields are filled accurately.
  4. Verify Email: After submitting the registration form, you may receive an email verification link. Click this link to activate your account.
  5. Log In and Access Dashboard: Once your account is active, log in to the GeoData Store portal using your newly created credentials.
  6. Retrieve API Key: Within your user dashboard or profile settings, there should be a section dedicated to 'API Keys' or 'Developer Settings'. Generate a new API key if one is not already provided, and copy it. This key will be a unique string of characters that you will include in your API requests. Keep this key confidential and secure, as it grants access to the API on your behalf.

The API key is a critical credential, and its security is important. As a general best practice for API key management, developers should avoid hardcoding keys directly into client-side code and instead use environment variables or secure server-side storage, as recommended by security guidelines for API usage (e.g., Google Maps API security best practices).

Your first request

Once you have obtained your API key, you can make your first request to the Hong Kong GeoData Store Geocoding API. The API uses a RESTful architecture, meaning requests are made via standard HTTP methods (primarily GET) to specific URLs, and responses are typically in JSON format. The Geocoding API Specification provides comprehensive details on the available endpoints and parameters.

Geocoding an Address

To geocode an address (convert an address string into coordinates), you will use the geocoding endpoint. A typical request will include your API key and the address you wish to query.

Example using cURL:

Replace YOUR_API_KEY with your actual API key and adjust the address as needed.

curl -X GET "https://www.geodata.gov.hk/gs/api/v1.0.0/geocode?q=Queen%27s%20Road%20Central&accept-language=en&apikey=YOUR_API_KEY"

In this example:

  • https://www.geodata.gov.hk/gs/api/v1.0.0/geocode is the base URL for the geocoding service.
  • q=Queen%27s%20Road%20Central is the query parameter specifying the address to geocode. URL encoding is applied to spaces and special characters.
  • accept-language=en specifies the preferred response language.
  • apikey=YOUR_API_KEY is your unique API key for authentication.

Expected JSON Response Structure:

A successful response will return a JSON object containing an array of results, each with location details, including latitude and longitude.

{
  "results": [
    {
      "address": {
        "buildingName": "",
        "streetName": "Queen's Road Central",
        "district": "Central",
        "region": "Hong Kong Island"
      },
      "location": {
        "latitude": 22.280,
        "longitude": 114.156
      },
      "accuracy": "Street"
    }
  ],
  "status": "OK"
}

The specific fields in the address and location objects may vary slightly based on the query and the level of detail available for the geocoded location. The status field indicates the success or failure of the request.

Reverse Geocoding Coordinates

To perform reverse geocoding (convert coordinates into an address), you would use a similar endpoint, providing latitude and longitude parameters.

Example using cURL:

curl -X GET "https://www.geodata.gov.hk/gs/api/v1.0.0/reverse-geocode?lat=22.280&lon=114.156&accept-language=en&apikey=YOUR_API_KEY"

In this example:

  • lat=22.280 specifies the latitude.
  • lon=114.156 specifies the longitude.

Expected JSON Response Structure for Reverse Geocoding:

{
  "results": [
    {
      "address": {
        "buildingName": "",
        "streetName": "Queen's Road Central",
        "district": "Central",
        "region": "Hong Kong Island"
      },
      "location": {
        "latitude": 22.280,
        "longitude": 114.156
      },
      "accuracy": "Street"
    }
  ],
  "status": "OK"
}

Common next steps

After successfully making your first few requests to the Hong Kong GeoData Store Geocoding API, consider these common next steps to further integrate the service into your applications:

  • Explore Advanced Query Parameters: Review the API specification for additional parameters that can refine your geocoding results, such as bounding box filters or result limits.
  • Implement Error Handling: Develop robust error handling in your application to gracefully manage scenarios like invalid API keys, rate limit exceedances, or no results found. The API returns specific HTTP status codes and JSON error messages that can be parsed.
  • Integrate with Mapping Libraries: Combine the geocoded data with popular mapping libraries like Leaflet or OpenLayers to visualize locations on an interactive map. While the GeoData Store provides its own Map API, external mapping libraries offer broader customization and feature sets.
  • Monitor API Usage: While the service is free, understanding your usage patterns can help in optimizing requests and identifying potential issues. Check your account dashboard for any usage statistics or limits, if provided.
  • Stay Updated: Regularly check the official Hong Kong GeoData Store website for announcements, updates to the API, or changes in terms of service.

Troubleshooting the first call

Encountering issues during your initial API calls is common. Here are some troubleshooting steps for the Hong Kong GeoData Store Geocoding API:

  • Invalid API Key: Double-check that you have copied the API key correctly and included it as the apikey parameter in your request. An incorrect key will typically result in an authentication error.
  • URL Encoding: Ensure that all parameters, especially the query string for addresses (q), are properly URL-encoded. Spaces and special characters must be converted to their %xx equivalents.
  • Incorrect Endpoint: Verify that you are using the correct base URL for the geocoding or reverse geocoding service, as specified in the official documentation.
  • Network Issues: Check your internet connection. If using cURL or a similar tool, ensure there are no firewall rules blocking outbound HTTP requests.
  • HTTP Status Codes: Pay attention to the HTTP status code returned in the API response. Common codes include:
    • 200 OK: Success. The request was processed successfully.
    • 400 Bad Request: Often due to missing or invalid parameters. Check your query string.
    • 401 Unauthorized: Indicates an issue with the API key or authentication.
    • 403 Forbidden: Your API key might not have the necessary permissions, or usage limits have been exceeded.
    • 500 Internal Server Error: An issue on the API provider's side. If this persists, check the GeoData Store's status page or contact support.
  • Consult Documentation: The Hong Kong GeoData Store Geocoding API Specification is the authoritative source for all API details, including error codes and expected parameter formats. Reference it for specific error messages or unexpected behavior.