Work with Localities

Use the LocalitiesService to autocomplete and get details of localities, postal codes or addresses.

  1. Overview
  2. Getting started
  3. Localities Autocomplete
  4. Localities Details
  5. Debouncing Autocomplete Promise

Overview

The LocalitiesService class provides methods for using the Localities API through Woosmap Map JavaScript API. It supports modern usage patterns such as Promises.

This guide focus on the following supported operations from Localities:

Review the example below to understand how to use autocomplete and get addresses details from Localities API using through Woosmap Map JS API:

Getting started

Before using the Localities service in the Map JavaScript API, it is required to have a secure and valid Woosmap API key and enable the Localities API for it.

Next, you must load the Map JS API library by including a script tag in your HTML page as follows:

HTML
        <script async
        src="https://sdk.woosmap.com/map/map.js?key=YOUR_API_KEY&callback=initMap">
</script>

    

See the Get Started with Map JS API guide for more information.

Localities Autocomplete

You can call this endpoint by first creating a new instance of the woosmap.map.LocalitiesService class and then call the dedicated method.

Localities Autocomplete Request

To initiate a request to Localities Autocomplete in the Woosmap Map JS API, create an object of type woosmap.map.LocalitiesService and call LocalitiesService.autocomplete(),passing it a LocalitiesAutocompleteRequest object literal.

The LocalitiesAutocompletesRequest object literal contains the following fields:

Type definition for LocalitiesAutocompletesRequest
        {
    input: string,
    components ? : woosmap.map.localities.LocalitiesComponentRestrictions,
    customDescription ? : string,
    data ? : woosmap.map.localities.LocalitiesRequestData,
    extended ? : string,
    language ? : string,
    location ? : woosmap.map.LatLng | woosmap.map.LatLngLiteral,
    radius ? : number,
    types ? : string | string[],
}

    

The fields are:

Below is a sample LocalitiesAutocompletesRequest:

JavaScript
        const autocompleteRequest = {
    input: "10 downing street",
    types: ["locality", "address"],
    language: "EN",
    components: {country: ["GB"]},
    customDescription: "name,admin_1,admin_0",
    radius: 500000,
    location: {lat: 51.5007, lng: -0.1246},
};

    

The LocalitiesService’s autocomplete() method is asynchronous and returns a Promise object that is either fulfilled with an array of LocalitiesPredictions objects or rejected with an APIError object. You can attach handlers to this Promise object to process results upon operation success or failure.

JavaScript
        const localitiesService = new woosmap.map.LocalitiesService();
localitiesService
    .autocomplete(autocompleteRequest)
    .then((response) => {
        console.log(response.result);
    })
    .catch((error) => {
        console.log(error);
    })
    .finally(() => {
        console.log("done");
    });

    

Localities Autocomplete Response

A successful autocomplete() call returns a LocalitiesAutocompleteResponse object with a localities[] field, which is an array of LocalitiesPredictions objects.

Each LocalitiesPredictions object may contain the following fields:

Type definition for LocalitiesAutocompleteResponse
        {
    localities[]: {
      description: string,
      public_id: string,
      type?: string,
      matched_substrings[]?: {
        description[]:{
          offset: number, 
          length: number
        }
      },
      has_addresses?: boolean,
    }
}

    

Localities Details

Localities Details Request

The getDetails() method from woosmap.map.LocalitiesService is used to get details of a selected locality. It also returns a Promise object that resolves to a LocalitiesDetailsResponse object.

The LocalitiesDetailsRequest object literal contains the following fields:

Type definition for LocalitiesDetailsRequest
        {
    publicId: string,
    language?: string,
    fields?: string,
    countryCodeFormat?: string,
}

    

Below is a sample call to LocalitiesServices.getDetails() method passing the resulted publicId from the above call to LocalitiesServices.autocomplete() (“10 Downing Street”).

JavaScript
        const detailsRequest = {
    publicId: "aGVyZTphZjpzdHJlZXRzZWN0aW9uOlpWN1NSWDhMUlNlRVpWU3hQMUhFREQ6Q2dnSUJDRHd5c25UQWhBQkdnSXhNQQ",
    language: "fr",
};
const localitiesService = new woosmap.map.LocalitiesService();
localitiesService
    .getDetails(detailsRequest)
    .then((response) => {
        console.log(response.result);
    })
    .catch((error) => {
        console.log(error);
    })
    .finally(() => {
        console.log("done");
    });

    

Localities Details Response

A successful getDetails() call returns a LocalitiesDetailsResponse object with a result field, which may contain the following fields:

Type definition for LocalitiesAutocompleteResponse
        {
    result: {
      formatted_address: string,
      public_id: string,
      types[]:  woosmap.map.localities.LocalitiesTypes,
      geometry[]?: {
        accuracy: woosmap.map.localities.LocalitiesDetailsAccuracy, 
        location: woosmap.map.LatLngLiteral,
        viewport: woosmap.map.LatLngBoundsLiteral,
      },
      name?: string,
      status?: string,
      address_components[]?: {
        long_name: string,
        short_name: string,
        types[]: string,
      },
    }
}

    

Debouncing Autocomplete Promise

Autocomplete is designed to support real-time, as-you-type search, processing requests for each keystroke to deliver instantaneous feedback. However, there are situations where the continuous as-you-type functionality may lead to unwanted behaviors.

To handle this, you can debounce your promise and implement a mechanism to ignore the results of all previous promises when a new one is created.

Autocomplete Debounce Promise
        
type DebouncePromiseFunction<T, Args extends any[]> = (
  ...args: Args
) => Promise<T>;

function debouncePromise<T, Args extends any[]>(
  fn: (...args: Args) => Promise<T>,
  delay: number,
): DebouncePromiseFunction<T, Args> {
  let timeoutId: ReturnType<typeof setTimeout> | null = null;
  let latestResolve: ((value: T | PromiseLike<T>) => void) | null = null;
  let latestReject: ((reason?: any) => void) | null = null;

  return function (...args: Args): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      if (timeoutId !== null) {
        clearTimeout(timeoutId);
      }
      latestResolve = resolve;
      latestReject = reject;
      timeoutId = setTimeout(() => {
        fn(...args)
          .then((result) => {
            if (latestResolve === resolve && latestReject === reject) {
              resolve(result);
            }
          })
          .catch((error) => {
            if (latestResolve === resolve && latestReject === reject) {
              reject(error);
            }
          });
      }, delay);
    });
  };
}


    
        function debouncePromise(fn, delay) {
  let timeoutId = null;
  let latestResolve = null;
  let latestReject = null;

  return function (...args) {
    return new Promise((resolve, reject) => {
      if (timeoutId !== null) {
        clearTimeout(timeoutId);
      }

      latestResolve = resolve;
      latestReject = reject;
      timeoutId = setTimeout(() => {
        fn(...args)
          .then((result) => {
            if (latestResolve === resolve && latestReject === reject) {
              resolve(result);
            }
          })
          .catch((error) => {
            if (latestResolve === resolve && latestReject === reject) {
              reject(error);
            }
          });
      }, delay);
    });
  };
}


    

Finally, you can use this debouncePromise() function to debounce autocomplete request as follows:

JavaScript
        const localitiesService = new woosmap.map.LocalitiesService();
// Debounce autocomplete request for 10ms
const debouncedLocalitiesAutocomplete = debouncePromise(localitiesService.autocomplete, 10);
debouncedLocalitiesAutocomplete(autocompleteRequest)
        .then((response) => {
          console.log(response.result);
        })
        .catch((error) => {
          console.log(error);
        })
        .finally(() => {
          console.log("done");
        });

    
Was this article helpful?
Have more questions? Submit a request