Localities Api - Details (Autocomplete on postal codes with addresses)

Get details of localities using autocomplete on postal codes only. (only available in the UK).

  1. Example
  2. Running the Sample Locally

Example

Localities Api - Details (Autocomplete on postal codes with addresses)
        const woosmap_key = "YOUR_API_KEY";
const countryRestrictions = ["GB", "JE", "IM", "GG"];
const types = ["postal_code"];
let map: woosmap.map.Map;
let debouncedAutocomplete: (
  ...args: any[]
) => Promise<woosmap.map.localities.LocalitiesAutocompleteResponse>;
let inputElement: HTMLInputElement;
let suggestionsList: HTMLUListElement;
let clearSearchBtn: HTMLButtonElement;
let markerAddress: woosmap.map.Marker;

function init(): void {
  if (inputElement && suggestionsList) {
    inputElement.addEventListener("input", handleAutocomplete);
    inputElement.addEventListener("keydown", (event) => {
      if (event.key === "Enter") {
        const firstLi = suggestionsList.querySelector("li");
        if (firstLi) {
          firstLi.click();
        }
      }
    });
  }
  clearSearchBtn.addEventListener("click", () => {
    inputElement.value = "";
    suggestionsList.style.display = "none";
    clearSearchBtn.style.display = "none";
    inputElement.focus();
    markerAddress.setMap(null);
  });

  debouncedAutocomplete = debouncePromise(autocompleteAddress, 0);
}

function initMap(): void {
  map = new woosmap.map.Map(document.getElementById("map") as HTMLElement, {
    center: {
      lat: 48.8534,
      lng: 2.3488,
    },
    disableDefaultUI: true,
    gestureHandling: "greedy",
    zoom: 5,
    styles: [
      {
        featureType: "poi",
        stylers: [{ visibility: "off" }],
      },
    ],
  });
}

function handleAutocomplete(): void {
  if (inputElement && suggestionsList) {
    const input = inputElement.value;
    input.replace('"', '\\"').replace(/^\s+|\s+$/g, "");

    if (input !== "") {
      debouncedAutocomplete(input)
        .then(({ localities }) => displaySuggestions(localities))
        .catch((error) =>
          console.error("Error autocomplete localities:", error),
        );
    } else {
      suggestionsList.style.display = "none";
      clearSearchBtn.style.display = "none";
    }
  }
}

function displaySuggestions(
  localitiesPredictions: woosmap.map.localities.LocalitiesPredictions[],
) {
  if (inputElement && suggestionsList) {
    suggestionsList.innerHTML = "";
    if (localitiesPredictions.length > 0) {
      localitiesPredictions.forEach((locality) => {
        const li = document.createElement("li");
        li.innerHTML = formatPredictionList(locality) ?? "";
        li.addEventListener("click", () => {
          inputElement.value = locality.description ?? "";
          requestDetailsAddress(locality.public_id);
          suggestionsList.style.display = "none";
        });
        suggestionsList.appendChild(li);
      });
      suggestionsList.style.display = "block";
      clearSearchBtn.style.display = "block";
    } else {
      suggestionsList.style.display = "none";
    }
  }
}

function formatPredictionList(
  locality: woosmap.map.localities.LocalitiesPredictions,
): string {
  const formattedName =
    locality.matched_substrings && locality.matched_substrings.description
      ? bold_matched_substring(
          locality.description as string,
          locality.matched_substrings.description,
        )
      : locality.description;

  const addresses = locality.has_addresses
    ? `<span class='light'>- view addresses</span>`
    : "";
  const predictionClass = locality.has_addresses
    ? `prediction-expandable`
    : "no-viewpoint";

  return `<div class="prediction ${predictionClass}">${formattedName} ${addresses}</div>`;
}

function bold_matched_substring(
  string: string,
  matched_substrings: woosmap.map.AutocompleteMatchedSubstring[],
) {
  matched_substrings = matched_substrings.reverse();
  for (const substring of matched_substrings) {
    const char = string.substring(
      substring["offset"],
      substring["offset"] + substring["length"],
    );
    string = `${string.substring(
      0,
      substring["offset"],
    )}<span class='bold'>${char}</span>${string.substring(
      substring["offset"] + substring["length"],
    )}`;
  }
  return string;
}

function autocompleteAddress(
  input: string,
): Promise<woosmap.map.localities.LocalitiesAutocompleteResponse> {
  const args = {
    key: woosmap_key,
    input,
  };
  args["components"] = countryRestrictions
    .map((country) => `country:${country}`)
    .join("|");
  args["types"] = types.join("|");
  return fetch(
    `https://api.woosmap.com/localities/autocomplete/?${buildQueryString(args)}`,
  ).then((response) => response.json());
}

function buildQueryString(params: object) {
  const queryStringParts = [];

  for (const key in params) {
    if (params[key]) {
      const value = params[key];
      queryStringParts.push(
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}` as never,
      );
    }
  }
  return queryStringParts.join("&");
}

function createAddressMarker(
  addressDetail: woosmap.map.localities.LocalitiesDetailsResult,
) {
  if (markerAddress) {
    markerAddress.setMap(null);
  }
  if (addressDetail && addressDetail.geometry) {
    markerAddress = new woosmap.map.Marker({
      position: addressDetail.geometry.location,
      icon: {
        url: "https://images.woosmap.com/marker.png",
        scaledSize: {
          height: 59,
          width: 37,
        },
      },
    });
    markerAddress.setMap(map);
    panMap(addressDetail);
  }
}

function panMap(addressDetail: woosmap.map.localities.LocalitiesDetailsResult) {
  let geometry;
  if (addressDetail && addressDetail.geometry) {
    geometry = addressDetail.geometry;
  }
  if (
    addressDetail &&
    addressDetail.geometry &&
    addressDetail.geometry.viewport
  ) {
    const { viewport } = geometry;
    const bounds = {
      east: viewport.northeast.lng,
      south: viewport.southwest.lat,
      north: viewport.northeast.lat,
      west: viewport.southwest.lng,
    };
    map.fitBounds(bounds);
    map.panTo(addressDetail.geometry.location);
  } else {
    let zoom = 17;
    if (addressDetail.types[0] === "address") {
      zoom = 18;
    }
    map.setZoom(zoom);
    map.panTo(geometry.location);
  }
}

function requestDetailsAddress(public_id: string) {
  getLocalitiesDetails(public_id).then(
    (addressDetails: woosmap.map.localities.LocalitiesDetailsResponse) => {
      if (addressDetails.result["addresses"]) {
        populateAddressList(addressDetails.result["addresses"]);
      }
      if (addressDetails) {
        createAddressMarker(addressDetails.result);
      }
    },
  );
}

function populateAddressList(addresses) {
  if (inputElement && suggestionsList) {
    suggestionsList.innerHTML = "";
    if (addresses["list"].length > 0) {
      addresses["list"].forEach((address) => {
        const li = document.createElement("li");
        li.innerHTML = formatPredictionList(address) ?? "";
        li.addEventListener("click", () => {
          inputElement.value = address.description ?? "";
          requestDetailsAddress(address.public_id);
        });
        suggestionsList.appendChild(li);
      });
      suggestionsList.style.display = "block";
      clearSearchBtn.style.display = "block";
    }
  }
}

function getLocalitiesDetails(
  publicId: string,
): Promise<woosmap.map.localities.LocalitiesDetailsResponse> {
  const args = {
    public_id: publicId,
    key: woosmap_key,
  };
  return fetch(
    `https://api.woosmap.com/localities/details/?${buildQueryString(args)}`,
  ).then((response) => response.json());
}

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);
    });
  };
}

document.addEventListener("DOMContentLoaded", () => {
  inputElement = document.getElementById(
    "autocomplete-input",
  ) as HTMLInputElement;
  suggestionsList = document.getElementById(
    "suggestions-list",
  ) as HTMLUListElement;
  clearSearchBtn = document.getElementsByClassName(
    "clear-searchButton",
  )[0] as HTMLButtonElement;
  init();
});

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

    
        const woosmap_key = "YOUR_API_KEY";
const countryRestrictions = ["GB", "JE", "IM", "GG"];
const types = ["postal_code"];
let map;
let debouncedAutocomplete;
let inputElement;
let suggestionsList;
let clearSearchBtn;
let markerAddress;

function init() {
  if (inputElement && suggestionsList) {
    inputElement.addEventListener("input", handleAutocomplete);
    inputElement.addEventListener("keydown", (event) => {
      if (event.key === "Enter") {
        const firstLi = suggestionsList.querySelector("li");

        if (firstLi) {
          firstLi.click();
        }
      }
    });
  }

  clearSearchBtn.addEventListener("click", () => {
    inputElement.value = "";
    suggestionsList.style.display = "none";
    clearSearchBtn.style.display = "none";
    inputElement.focus();
    markerAddress.setMap(null);
  });
  debouncedAutocomplete = debouncePromise(autocompleteAddress, 0);
}

function initMap() {
  map = new woosmap.map.Map(document.getElementById("map"), {
    center: {
      lat: 48.8534,
      lng: 2.3488,
    },
    disableDefaultUI: true,
    gestureHandling: "greedy",
    zoom: 5,
    styles: [
      {
        featureType: "poi",
        stylers: [{ visibility: "off" }],
      },
    ],
  });
}

function handleAutocomplete() {
  if (inputElement && suggestionsList) {
    const input = inputElement.value;

    input.replace('"', '\\"').replace(/^\s+|\s+$/g, "");
    if (input !== "") {
      debouncedAutocomplete(input)
        .then(({ localities }) => displaySuggestions(localities))
        .catch((error) =>
          console.error("Error autocomplete localities:", error),
        );
    } else {
      suggestionsList.style.display = "none";
      clearSearchBtn.style.display = "none";
    }
  }
}

function displaySuggestions(localitiesPredictions) {
  if (inputElement && suggestionsList) {
    suggestionsList.innerHTML = "";
    if (localitiesPredictions.length > 0) {
      localitiesPredictions.forEach((locality) => {
        const li = document.createElement("li");

        li.innerHTML = formatPredictionList(locality) ?? "";
        li.addEventListener("click", () => {
          inputElement.value = locality.description ?? "";
          requestDetailsAddress(locality.public_id);
          suggestionsList.style.display = "none";
        });
        suggestionsList.appendChild(li);
      });
      suggestionsList.style.display = "block";
      clearSearchBtn.style.display = "block";
    } else {
      suggestionsList.style.display = "none";
    }
  }
}

function formatPredictionList(locality) {
  const formattedName =
    locality.matched_substrings && locality.matched_substrings.description
      ? bold_matched_substring(
          locality.description,
          locality.matched_substrings.description,
        )
      : locality.description;
  const addresses = locality.has_addresses
    ? `<span class='light'>- view addresses</span>`
    : "";
  const predictionClass = locality.has_addresses
    ? `prediction-expandable`
    : "no-viewpoint";
  return `<div class="prediction ${predictionClass}">${formattedName} ${addresses}</div>`;
}

function bold_matched_substring(string, matched_substrings) {
  matched_substrings = matched_substrings.reverse();

  for (const substring of matched_substrings) {
    const char = string.substring(
      substring["offset"],
      substring["offset"] + substring["length"],
    );

    string = `${string.substring(0, substring["offset"])}<span class='bold'>${char}</span>${string.substring(substring["offset"] + substring["length"])}`;
  }
  return string;
}

function autocompleteAddress(input) {
  const args = {
    key: woosmap_key,
    input,
  };

  args["components"] = countryRestrictions
    .map((country) => `country:${country}`)
    .join("|");
  args["types"] = types.join("|");
  return fetch(
    `https://api.woosmap.com/localities/autocomplete/?${buildQueryString(args)}`,
  ).then((response) => response.json());
}

function buildQueryString(params) {
  const queryStringParts = [];

  for (const key in params) {
    if (params[key]) {
      const value = params[key];

      queryStringParts.push(
        `${encodeURIComponent(key)}=${encodeURIComponent(value)}`,
      );
    }
  }
  return queryStringParts.join("&");
}

function createAddressMarker(addressDetail) {
  if (markerAddress) {
    markerAddress.setMap(null);
  }

  if (addressDetail && addressDetail.geometry) {
    markerAddress = new woosmap.map.Marker({
      position: addressDetail.geometry.location,
      icon: {
        url: "https://images.woosmap.com/marker.png",
        scaledSize: {
          height: 59,
          width: 37,
        },
      },
    });
    markerAddress.setMap(map);
    panMap(addressDetail);
  }
}

function panMap(addressDetail) {
  let geometry;

  if (addressDetail && addressDetail.geometry) {
    geometry = addressDetail.geometry;
  }

  if (
    addressDetail &&
    addressDetail.geometry &&
    addressDetail.geometry.viewport
  ) {
    const { viewport } = geometry;
    const bounds = {
      east: viewport.northeast.lng,
      south: viewport.southwest.lat,
      north: viewport.northeast.lat,
      west: viewport.southwest.lng,
    };

    map.fitBounds(bounds);
    map.panTo(addressDetail.geometry.location);
  } else {
    let zoom = 17;

    if (addressDetail.types[0] === "address") {
      zoom = 18;
    }

    map.setZoom(zoom);
    map.panTo(geometry.location);
  }
}

function requestDetailsAddress(public_id) {
  getLocalitiesDetails(public_id).then((addressDetails) => {
    if (addressDetails.result["addresses"]) {
      populateAddressList(addressDetails.result["addresses"]);
    }

    if (addressDetails) {
      createAddressMarker(addressDetails.result);
    }
  });
}

function populateAddressList(addresses) {
  if (inputElement && suggestionsList) {
    suggestionsList.innerHTML = "";
    if (addresses["list"].length > 0) {
      addresses["list"].forEach((address) => {
        const li = document.createElement("li");

        li.innerHTML = formatPredictionList(address) ?? "";
        li.addEventListener("click", () => {
          inputElement.value = address.description ?? "";
          requestDetailsAddress(address.public_id);
        });
        suggestionsList.appendChild(li);
      });
      suggestionsList.style.display = "block";
      clearSearchBtn.style.display = "block";
    }
  }
}

function getLocalitiesDetails(publicId) {
  const args = {
    public_id: publicId,
    key: woosmap_key,
  };
  return fetch(
    `https://api.woosmap.com/localities/details/?${buildQueryString(args)}`,
  ).then((response) => response.json());
}

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);
    });
  };
}

document.addEventListener("DOMContentLoaded", () => {
  inputElement = document.getElementById("autocomplete-input");
  suggestionsList = document.getElementById("suggestions-list");
  clearSearchBtn = document.getElementsByClassName("clear-searchButton")[0];
  init();
});
window.initMap = initMap;

    
        /*
 * Always set the map height explicitly to define the size of the div element
 * that contains the map.
 */
#map {
  height: 100%;
}

/*
 * Optional: Makes the sample page fill the window.
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}

#autocomplete-container {
  display: flex;
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 -1px 0px rgba(0, 0, 0, 0.02);
  background: #fff;
  border-radius: 12px;
  padding: 0 12px;
  max-width: 320px;
  width: 100%;
  height: 42px;
  border: none;
  box-sizing: border-box;
  align-items: center;
  cursor: text;
  font-size: 15px;
}

#autocomplete-container .search-icon, #autocomplete-container .clear-icon {
  color: inherit;
  flex-shrink: 0;
  height: 16px;
  width: 16px;
}

#autocomplete-container .clear-icon {
  transform: scale(1.3);
}

#autocomplete-input {
  box-sizing: border-box;
  padding: 0;
  height: 40px;
  line-height: 24px;
  vertical-align: top;
  transition-property: color;
  transition-duration: 0.3s;
  width: 100%;
  text-overflow: ellipsis;
  background: transparent;
  border-radius: 0;
  border: 0;
  margin: 0 8px;
  outline: 0;
  overflow: visible;
  appearance: textfield;
  font-size: 100%;
}

.clear-searchButton {
  display: none;
  height: 18px;
  width: 22px;
  background: none;
  border: none;
  vertical-align: middle;
  pointer-events: all;
  cursor: pointer;
}

#suggestions-list {
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 -1px 0px rgba(0, 0, 0, 0.02);
  box-sizing: border-box;
  position: absolute;
  max-width: 320px;
  width: 100%;
  top: 100%;
  left: 0;
  z-index: 1;
  list-style: none;
  max-height: 80vh;
  margin: 5px 0 0;
  padding: 0;
  display: none;
  overflow-y: auto;
  background-color: #fff;
}

#suggestions-list.visible {
  display: block;
}

#suggestions-list li {
  padding: 12px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

#suggestions-list li:hover {
  background-color: #f2f2f2;
}

#app {
  height: 100%;
  font-size: 13px;
}

.bold {
  font-weight: 700;
}

.light {
  font-size: 12px;
  color: #3d5afe;
  font-weight: 600;
}

.prediction-expandable {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='5' height='9' viewBox='0 0 5 9'%3E%3Cg fill='%23737373'%3E%3Cpath d='M0.714285714,8.57142857 C0.5,8.57142857 0.357142857,8.5 0.214285714,8.35714286 C-0.0714285714,8.07142857 -0.0714285714,7.64285714 0.214285714,7.35714286 L3.78571429,3.78571429 C4.07142857,3.5 4.5,3.5 4.78571429,3.78571429 C5.07142857,4.07142857 5.07142857,4.5 4.78571429,4.78571429 L1.21428571,8.35714286 C1.07142857,8.5 0.928571429,8.57142857 0.714285714,8.57142857 L0.714285714,8.57142857 Z'/%3E%3Cpath d='M4.28571429,5 C4.07142857,5 3.92857143,4.92857143 3.78571429,4.78571429 L0.214285714,1.21428571 C-0.0714285714,0.928571429 -0.0714285714,0.5 0.214285714,0.214285714 C0.5,-0.0714285714 0.928571429,-0.0714285714 1.21428571,0.214285714 L4.78571429,3.78571429 C5.07142857,4.07142857 5.07142857,4.5 4.78571429,4.78571429 C4.64285714,4.92857143 4.5,5 4.28571429,5 L4.28571429,5 Z'/%3E%3C/g%3E%3C/svg%3E%0A");
  background-repeat: no-repeat;
  background-position: right 5px center;
  padding-right: 18px;
}

#suggestions-list {
  font-size: 13px;
}


    
        <html>
  <head>
    <title>
      Localities Api - Details (Autocomplete on postal codes with addresses)
    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8" />

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="app">
      <div id="map"></div>
      <div id="autocomplete-container">
        <svg class="search-icon" viewBox="0 0 16 16">
          <path
            d="M3.617 7.083a4.338 4.338 0 1 1 8.676 0 4.338 4.338 0 0 1-8.676 0m4.338-5.838a5.838 5.838 0 1 0 2.162 11.262l2.278 2.279a1 1 0 0 0 1.415-1.414l-1.95-1.95A5.838 5.838 0 0 0 7.955 1.245"
            fill-rule="evenodd"
            clip-rule="evenodd"
          ></path>
        </svg>

        <input
          type="text"
          id="autocomplete-input"
          placeholder="Type in a UK postal code..."
          autocomplete="off"
        />
        <button aria-label="Clear" class="clear-searchButton" type="button">
          <svg class="clear-icon" viewBox="0 0 24 24">
            <path
              d="M7.074 5.754a.933.933 0 1 0-1.32 1.317L10.693 12l-4.937 4.929a.931.931 0 1 0 1.319 1.317l4.938-4.93 4.937 4.93a.933.933 0 0 0 1.581-.662.93.93 0 0 0-.262-.655L13.331 12l4.937-4.929a.93.93 0 0 0-.663-1.578.93.93 0 0 0-.656.261l-4.938 4.93z"
            ></path>
          </svg>
        </button>
        <ul id="suggestions-list"></ul>
      </div>
    </div>

    <script
      src="https://sdk.woosmap.com/map/map.js?key=woos-48c80350-88aa-333e-835a-07f4b658a9a4&callback=initMap"
      defer
    ></script>
  </body>
</html>

    

Running the Sample Locally

Before you can run this sample on your local machine, you need to have Git and Node.js installed. If they’re not already installed, follow these instructions to get them set up.

Once you have Git and Node.js installed, you can run the sample by following these steps:

  1. Clone the repository and navigate to the directory of the sample.

  2. Install the necessary dependencies.

  3. Start running the sample.

Here are the commands you can use in your terminal to do this:

Shell
        git clone -b sample/localities-api-details-postalcodes https://github.com/woosmap/js-samples.git
cd js-samples
npm i
npm start

    

You can experiment with other samples by switching to any branch that starts with the pattern sample/SAMPLE_NAME.

Shell
        git checkout sample/SAMPLE_NAME
npm i
npm start

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