Localities API - Shape

This sample demonstrates how to display the shape returned from a supported feature using the Localities API. It retrieves GeoJSON Geometry from the Details endpoint of the Localities API and displays it using the map’s Data layer.

  1. Example
  2. Running the Sample Locally

Example

Localities API - Shape
        const componentsRestriction: woosmap.map.localities.LocalitiesComponentRestrictions =
  { country: [] };
const woosmap_key = "YOUR_API_KEY";
let debouncedAutocomplete: (
  ...args: any[]
) => Promise<woosmap.map.localities.LocalitiesAutocompleteResponse>;
let inputElement: HTMLInputElement;
let suggestionsList: HTMLUListElement;
let clearSearchBtn: HTMLButtonElement;
let map: woosmap.map.Map;
let markerAddress: woosmap.map.Marker;
let detailsHTML: HTMLElement;
let addressDetailsContainer: HTMLElement;
let hasShape = false;

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" }],
      },
    ],
  });
  init();
  manageCountrySelector();
}

function createShape(result: woosmap.map.localities.LocalitiesDetailsResult) {
  // @ts-ignore TypeDef to be updated
  if (result?.geometry?.shape) {
    hasShape = true;
    // @ts-ignore TypeDef to be updated
    map.data.addGeoJson({ type: "Feature", geometry: result.geometry.shape });
    if (result.geometry.viewport) {
      const bounds = {
        east: result.geometry.viewport.northeast.lng,
        south: result.geometry.viewport.southwest.lat,
        north: result.geometry.viewport.northeast.lat,
        west: result.geometry.viewport.southwest.lng,
      };
      map.fitBounds(bounds, { top: 60, left: 60, bottom: 60, right: 60 });
    }
  }
}

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

    // Pan the map to the marker's location
    if (!hasShape) {
      panMap(addressDetail);
    } else {
      hasShape = false;
    }
  }
}

function displaySection(section: HTMLElement, mode = "block"): void {
  section.style.display = mode;
}

function fillAddressDetails(
  addressDetails: woosmap.map.localities.LocalitiesDetailsResult,
) {
  const details: string[] = [];
  detailsHTML.innerHTML = "";
  detailsHTML.style.display = "block";
  if (addressDetails.formatted_address) {
    details.push(
      `<p class='option-detail'><span class='option-detail-label'>Formatted_address :</span><span class='bold'>${addressDetails.formatted_address}</span></p>`,
    );
  }
  if (addressDetails.types && addressDetails.types[0]) {
    details.push(
      `<p class='option-detail'><span class='option-detail-label'>Type : </span><span class='bold'>${addressDetails.types[0].replace("_", " ")}</span></p>`,
    );
  }
  if (addressDetails.geometry) {
    const location_type_string = addressDetails.geometry.accuracy;
    if (location_type_string) {
      details.push(
        `<div class='option-detail'><div><span class='option-detail-label'>Location type :</span><span class='bold'>${location_type_string
          .replace("_", " ")
          .toLowerCase()}</span></div></div>`,
      );
    }
    details.push(
      `<div class='option-detail'><div><span class='option-detail-label'>Latitude :</span> <span class='bold'>${addressDetails.geometry.location.lat.toString()}</span></div><div><span class='option-detail-label'>Longitude : </span><span class='bold'>${addressDetails.geometry.location.lng.toString()}</span></div></div>`,
    );
    if (addressDetails.address_components) {
      const compoHtml = addressDetails.address_components
        .map(
          (compo) =>
            `<p class='option-detail'><span class='option-detail-label'>${compo.types[0]}:</span> <span class='bold'>${compo.long_name}</span></p>`,
        )
        .join("");
      details.push(
        `<div class='address-components'><div class='title'>Address components</div><div>${compoHtml}</div>`,
      );
    }
  }
  detailsHTML.innerHTML = details.join("");
}

function init(): void {
  inputElement = document.getElementById(
    "autocomplete-input",
  ) as HTMLInputElement;
  suggestionsList = document.getElementById(
    "suggestions-list",
  ) as HTMLUListElement;
  clearSearchBtn = document.getElementsByClassName(
    "clear-searchButton",
  )[0] as HTMLButtonElement;
  addressDetailsContainer = document.querySelector(
    ".addressDetails",
  ) as HTMLElement;
  detailsHTML = document.querySelector(
    ".addressDetails .addressOptions",
  ) as HTMLElement;
  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";
    detailsHTML.style.display = "none";
    inputElement.focus();
    markerAddress.setMap(null);
  });

  debouncedAutocomplete = debouncePromise(autocompleteAddress, 0);
}

function handleAutocomplete(): void {
  if (inputElement && suggestionsList) {
    let input = inputElement.value;
    input = input.replace('"', '\\"').replace(/^\s+|\s+$/g, "");
    const componentsArgs: string = (componentsRestriction.country as string[])
      .map((country) => `country:${country}`)
      .join("|");
    if (input !== "") {
      debouncedAutocomplete(input, componentsArgs, woosmap_key)
        .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): string {
  const prediction = locality;
  const predictionClass = "no-viewpoint";
  const matched_substrings = prediction.matched_substrings;
  let formatted_name = "";
  if (
    prediction.matched_substrings &&
    prediction.matched_substrings.description
  ) {
    formatted_name = bold_matched_substring(
      prediction["description"],
      matched_substrings.description,
    );
  } else {
    formatted_name = prediction["description"];
  }

  let html = "";
  html += `<div class="prediction ${predictionClass}">${formatted_name}</div>`;

  return html;
}

function bold_matched_substring(string: string, matched_substrings: string[]) {
  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,
  components: string,
): Promise<woosmap.map.localities.LocalitiesAutocompleteResponse> {
  const args = {
    key: woosmap_key,
    input,
    no_deprecated_fields: "true",
    types: "locality",
    components,
  };
  if (components !== "") {
    if (args["components"]) {
      args["components"] = components;
    }
  }
  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("&");
}

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 manageCountrySelector() {
  const countryElements = document.querySelectorAll(".country");
  countryElements.forEach((countryElement: Element) => {
    countryElement.addEventListener("click", () => {
      toggleCountry(countryElement);
    });
    if (countryElement.classList.contains("active")) {
      const countryCode = (countryElement as HTMLElement).dataset
        .countrycode as string;
      componentsRestriction.country = [
        ...(componentsRestriction.country as string[]),
        countryCode,
      ];
    }
  });

  const dropdownButtons = document.querySelectorAll(
    ".dropdown .dropdown-button",
  );
  dropdownButtons.forEach((button: Element) =>
    button.addEventListener("click", toggleDropdown),
  );

  // Hide dropdowns when clicking outside
  const dropdowns = document.querySelectorAll(".dropdown");
  document.addEventListener("click", (event: Event) => {
    dropdowns.forEach((dropdown: Element) => {
      if (!dropdown.contains(event.target as Node)) {
        hideDropdown(dropdown);
      }
    });
  });
}

function toggleDropdown(event: Event) {
  event.stopPropagation();
  const dropdown = (event.target as Element).closest(".dropdown");
  if (dropdown) {
    if (dropdown.classList.contains("active")) {
      hideDropdown(dropdown);
    } else {
      showDropdown(dropdown);
    }
  }
}

function hideDropdown(dropdown: Element) {
  const dropdownContent = dropdown.querySelector(
    ".dropdown-content",
  ) as HTMLElement;
  dropdownContent?.classList.remove("visible");
  dropdown.classList.remove("active");
}

function showDropdown(dropdown: Element) {
  const dropdownContent = dropdown.querySelector(
    ".dropdown-content",
  ) as HTMLElement;
  dropdownContent?.classList.add("visible");
  dropdown.classList.add("active");
}

function toggleCountry(country: Element) {
  const isActive = country.classList.toggle("active");
  const countryCode = (country as HTMLElement).dataset.countrycode;

  if (countryCode) {
    if (isActive) {
      componentsRestriction.country = [
        ...(componentsRestriction.country as string[]),
        countryCode,
      ];
    } else {
      componentsRestriction.country = (
        componentsRestriction.country as string[]
      ).filter((code) => code !== countryCode);
    }
    updateCountrySelectorText();
    handleAutocomplete();
  }
}

function updateCountrySelectorText() {
  const dropdownText = document.querySelector(
    ".dropdown-button span",
  ) as HTMLElement;
  if (componentsRestriction.country.length > 0) {
    dropdownText.innerHTML = `Selected countries: <strong>${(componentsRestriction.country as string[]).join("</strong>, <strong>")}</strong>`;
  } else {
    dropdownText.textContent = "Select countries";
  }
}

const requestDetailsAddress = (public_id) => {
  getLocalitiesDetails(public_id).then((addressDetails) => {
    if (addressDetails) {
      fillAddressDetails(addressDetails.result);
      displaySection(addressDetailsContainer);
      createShape(addressDetails.result);
      createAddressMarker(addressDetails.result);
    }
  });
};

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, { top: 100, left: 100, bottom: 100, right: 100 });
    map.panTo(addressDetail.geometry.location);
  } else {
    let zoom = 17;
    if (addressDetail.types[0] === "address") {
      zoom = 18;
    }
    map.setZoom(zoom);
    map.panTo(geometry.location);
  }
}

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

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


    
        const componentsRestriction = { country: [] };
const woosmap_key = "YOUR_API_KEY";
let debouncedAutocomplete;
let inputElement;
let suggestionsList;
let clearSearchBtn;
let map;
let markerAddress;
let detailsHTML;
let addressDetailsContainer;
let hasShape = false;

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" }],
      },
    ],
  });
  init();
  manageCountrySelector();
}

function createShape(result) {
  // @ts-ignore TypeDef to be updated
  if (result?.geometry?.shape) {
    hasShape = true;
    // @ts-ignore TypeDef to be updated
    map.data.addGeoJson({ type: "Feature", geometry: result.geometry.shape });
    if (result.geometry.viewport) {
      const bounds = {
        east: result.geometry.viewport.northeast.lng,
        south: result.geometry.viewport.southwest.lat,
        north: result.geometry.viewport.northeast.lat,
        west: result.geometry.viewport.southwest.lng,
      };

      map.fitBounds(bounds, { top: 60, left: 60, bottom: 60, right: 60 });
    }
  }
}

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

  if (addressDetail?.geometry) {
    const position = addressDetail.geometry.location;

    markerAddress = new woosmap.map.Marker({
      position: position,
      icon: {
        url: "https://images.woosmap.com/marker.png",
        scaledSize: {
          height: 59,
          width: 37,
        },
      },
    });
    markerAddress.setMap(map);
    // Pan the map to the marker's location
    if (!hasShape) {
      panMap(addressDetail);
    } else {
      hasShape = false;
    }
  }
}

function displaySection(section, mode = "block") {
  section.style.display = mode;
}

function fillAddressDetails(addressDetails) {
  const details = [];

  detailsHTML.innerHTML = "";
  detailsHTML.style.display = "block";
  if (addressDetails.formatted_address) {
    details.push(
      `<p class='option-detail'><span class='option-detail-label'>Formatted_address :</span><span class='bold'>${addressDetails.formatted_address}</span></p>`,
    );
  }

  if (addressDetails.types && addressDetails.types[0]) {
    details.push(
      `<p class='option-detail'><span class='option-detail-label'>Type : </span><span class='bold'>${addressDetails.types[0].replace("_", " ")}</span></p>`,
    );
  }

  if (addressDetails.geometry) {
    const location_type_string = addressDetails.geometry.accuracy;

    if (location_type_string) {
      details.push(
        `<div class='option-detail'><div><span class='option-detail-label'>Location type :</span><span class='bold'>${location_type_string
          .replace("_", " ")
          .toLowerCase()}</span></div></div>`,
      );
    }

    details.push(
      `<div class='option-detail'><div><span class='option-detail-label'>Latitude :</span> <span class='bold'>${addressDetails.geometry.location.lat.toString()}</span></div><div><span class='option-detail-label'>Longitude : </span><span class='bold'>${addressDetails.geometry.location.lng.toString()}</span></div></div>`,
    );
    if (addressDetails.address_components) {
      const compoHtml = addressDetails.address_components
        .map(
          (compo) =>
            `<p class='option-detail'><span class='option-detail-label'>${compo.types[0]}:</span> <span class='bold'>${compo.long_name}</span></p>`,
        )
        .join("");

      details.push(
        `<div class='address-components'><div class='title'>Address components</div><div>${compoHtml}</div>`,
      );
    }
  }

  detailsHTML.innerHTML = details.join("");
}

function init() {
  inputElement = document.getElementById("autocomplete-input");
  suggestionsList = document.getElementById("suggestions-list");
  clearSearchBtn = document.getElementsByClassName("clear-searchButton")[0];
  addressDetailsContainer = document.querySelector(".addressDetails");
  detailsHTML = document.querySelector(".addressDetails .addressOptions");
  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";
    detailsHTML.style.display = "none";
    inputElement.focus();
    markerAddress.setMap(null);
  });
  debouncedAutocomplete = debouncePromise(autocompleteAddress, 0);
}

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

    input = input.replace('"', '\\"').replace(/^\s+|\s+$/g, "");

    const componentsArgs = componentsRestriction.country
      .map((country) => `country:${country}`)
      .join("|");

    if (input !== "") {
      debouncedAutocomplete(input, componentsArgs, woosmap_key)
        .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 prediction = locality;
  const predictionClass = "no-viewpoint";
  const matched_substrings = prediction.matched_substrings;
  let formatted_name = "";

  if (
    prediction.matched_substrings &&
    prediction.matched_substrings.description
  ) {
    formatted_name = bold_matched_substring(
      prediction["description"],
      matched_substrings.description,
    );
  } else {
    formatted_name = prediction["description"];
  }

  let html = "";

  html += `<div class="prediction ${predictionClass}">${formatted_name}</div>`;
  return html;
}

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, components) {
  const args = {
    key: woosmap_key,
    input,
    no_deprecated_fields: "true",
    types: "locality",
    components,
  };

  if (components !== "") {
    if (args["components"]) {
      args["components"] = components;
    }
  }
  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 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);
    });
  };
}

function manageCountrySelector() {
  const countryElements = document.querySelectorAll(".country");

  countryElements.forEach((countryElement) => {
    countryElement.addEventListener("click", () => {
      toggleCountry(countryElement);
    });
    if (countryElement.classList.contains("active")) {
      const countryCode = countryElement.dataset.countrycode;

      componentsRestriction.country = [
        ...componentsRestriction.country,
        countryCode,
      ];
    }
  });

  const dropdownButtons = document.querySelectorAll(
    ".dropdown .dropdown-button",
  );

  dropdownButtons.forEach((button) =>
    button.addEventListener("click", toggleDropdown),
  );

  // Hide dropdowns when clicking outside
  const dropdowns = document.querySelectorAll(".dropdown");

  document.addEventListener("click", (event) => {
    dropdowns.forEach((dropdown) => {
      if (!dropdown.contains(event.target)) {
        hideDropdown(dropdown);
      }
    });
  });
}

function toggleDropdown(event) {
  event.stopPropagation();

  const dropdown = event.target.closest(".dropdown");

  if (dropdown) {
    if (dropdown.classList.contains("active")) {
      hideDropdown(dropdown);
    } else {
      showDropdown(dropdown);
    }
  }
}

function hideDropdown(dropdown) {
  const dropdownContent = dropdown.querySelector(".dropdown-content");

  dropdownContent?.classList.remove("visible");
  dropdown.classList.remove("active");
}

function showDropdown(dropdown) {
  const dropdownContent = dropdown.querySelector(".dropdown-content");

  dropdownContent?.classList.add("visible");
  dropdown.classList.add("active");
}

function toggleCountry(country) {
  const isActive = country.classList.toggle("active");
  const countryCode = country.dataset.countrycode;

  if (countryCode) {
    if (isActive) {
      componentsRestriction.country = [
        ...componentsRestriction.country,
        countryCode,
      ];
    } else {
      componentsRestriction.country = componentsRestriction.country.filter(
        (code) => code !== countryCode,
      );
    }

    updateCountrySelectorText();
    handleAutocomplete();
  }
}

function updateCountrySelectorText() {
  const dropdownText = document.querySelector(".dropdown-button span");

  if (componentsRestriction.country.length > 0) {
    dropdownText.innerHTML = `Selected countries: <strong>${componentsRestriction.country.join("</strong>, <strong>")}</strong>`;
  } else {
    dropdownText.textContent = "Select countries";
  }
}

const requestDetailsAddress = (public_id) => {
  getLocalitiesDetails(public_id).then((addressDetails) => {
    if (addressDetails) {
      fillAddressDetails(addressDetails.result);
      displaySection(addressDetailsContainer);
      createShape(addressDetails.result);
      createAddressMarker(addressDetails.result);
    }
  });
};

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, { top: 100, left: 100, bottom: 100, right: 100 });
    map.panTo(addressDetail.geometry.location);
  } else {
    let zoom = 17;

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

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

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

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

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown ul {
  display: block;
  list-style: none;
  margin: 0 !important;
  padding: 0 !important;
}

.dropdown.active .dropdown-button {
  background-color: #e8ebee;
  border: 1px solid #e8ebee;
}

.dropdown.active .dropdown-button svg {
  transform: matrix(-1, 0, 0, -1, 0, 0);
}

.dropdown .dropdown-button {
  cursor: pointer;
  border: 1px solid #f9fbfd;
  background-color: #f9fbfd;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 -1px rgba(0, 0, 0, 0.0196078431);
  font-weight: 400;
  height: 42px;
  padding: 0 9px;
  font-size: 14px;
  border-radius: 12px;
}

.dropdown .dropdown-button:hover {
  background-color: #e8ebee;
  border: 1px solid #e8ebee;
}

.dropdown .dropdown-button strong {
  font-size: 0.9em;
  opacity: 0.9;
}

.dropdown .dropdown-button svg {
  height: 0.75rem;
  width: 0.75rem;
  margin-left: 0.5rem;
  margin-top: -0.125rem;
  transition-duration: 0.1s;
  transition-property: transform;
  vertical-align: middle;
  transition-timing-function: cubic-bezier(0.07, 0.49, 0, 1.05);
  fill: #1D1D1D;
  display: inline;
  padding-top: 0;
}

.dropdown .dropdown-menuitem {
  color: #1D1D1D;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding: 0.5rem 1rem;
  position: relative;
  white-space: nowrap;
  text-decoration: none;
  cursor: pointer;
}

.dropdown .dropdown-menuitem:hover {
  background-color: #e8ebee;
}

.dropdown .dropdown-menuitem.divider {
  border-top: 1px solid #e8ebee;
}

.dropdown .dropdown-content {
  display: none;
  opacity: 0;
  visibility: hidden;
  position: absolute;
  min-width: 160px;
  overflow: hidden;
  top: 100%;
  z-index: 999;
}

.dropdown .dropdown-content.visible {
  display: block;
  opacity: 1;
  visibility: visible;
}

.dropdown .dropdown-menu {
  background-clip: padding-box;
  background-color: #FFF;
  color: #1D1D1D;
  border-radius: 12px;
  box-shadow: rgba(0, 0, 0, 0) 0 0 0 0, rgba(0, 0, 0, 0) 0 0 0 0, rgba(6, 11, 16, 0.2) 0 16px 24px 0, rgba(6, 11, 16, 0.3) 0 6px 30px 0, rgba(6, 11, 16, 0.4) 0 8px 10px 0;
  left: 0;
  margin-top: 1px;
  min-width: 13rem;
  -webkit-font-smoothing: subpixel-antialiased;
  -moz-osx-font-smoothing: auto;
}

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

body {
  background-color: #eee;
  overflow-y: hidden;
}

.bold {
  font-weight: 700;
}

#countrySelector {
  position: absolute;
  top: 10px;
  left: 335px;
}

.country .country-name {
  display: flex;
  flex-grow: 1;
}
.country .flag-icon {
  height: 20px;
  width: 20px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  margin-right: 8px;
}
.country .flag-icon-fr {
  background-image: url(https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.5.0/flags/4x3/fr.svg);
}
.country .flag-icon-gb {
  background-image: url(https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.5.0/flags/4x3/gb.svg);
}
.country .flag-icon-de {
  background-image: url(https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.5.0/flags/4x3/de.svg);
}
.country .flag-icon-es {
  background-image: url(https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.5.0/flags/4x3/es.svg);
}
.country .active-icon-wrapper {
  display: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M6.054 8.958 3.65 6.555A2.112 2.112 0 1 0 .663 9.543l3.86 3.86a2.11 2.11 0 0 0 2.054.543c.38-.084.74-.274 1.033-.568l7.77-7.77a2.114 2.114 0 0 0-2.987-2.99l-6.34 6.34z'%3E%3C/path%3E%3C/svg%3E");
  height: 10px;
  width: 10px;
  background-position: 50%;
  background-size: contain;
}
.country.active .active-icon-wrapper {
  display: flex;
}

.addressDetails {
  display: none;
  position: absolute;
  right: 10px;
  bottom: 25px;
  border-radius: 6px;
  max-width: 240px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 -1px 0px rgba(0, 0, 0, 0.02);
  z-index: 1;
  overflow: hidden;
}
.addressDetails .info {
  padding: 12px 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  background-color: #fff;
}
.addressDetails .addressOptions {
  overflow-y: auto;
  max-height: 240px;
  font-size: 12px;
  padding-top: 12px;
  background-color: #fff;
}
.addressDetails .addressOptions .option-detail {
  display: flex;
  flex-wrap: wrap;
  padding: 0 12px 8px 12px;
  margin: 0;
}
.addressDetails .addressOptions .option-detail-label {
  color: rgba(0, 0, 0, 0.5);
  margin-right: 4px;
}

.address-components {
  padding: 0 0 18px 0;
  background-color: rgba(0, 0, 0, 0.03);
}

.address-components .title {
  color: rgba(0, 0, 0, 0.5);
  font-size: 10px;
  text-transform: uppercase;
  letter-spacing: 1px;
  padding: 16px 12px 10px 12px;
}


    
        <html>
  <head>
    <title>Localities API - Shape</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 class="addressDetails">
        <div class="addressOptions"></div>
      </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="Search an Address..."
          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 id="countrySelector" class="dropdown">
        <button class="dropdown-button">
          <span> Select countries </span>
          <svg
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 16 16"
            aria-hidden="true"
          >
            <path
              d="m4 4 3.4 3.4c.3.4.9.4 1.2 0L11.9 4 14 6.2l-5.4 5.6c-.3.3-.9.3-1.2 0L2 6.2z"
            ></path>
          </svg>
        </button>
        <div id="countryDropdown" class="dropdown-content dropdown-menu">
          <div>
            <ul role="listbox">
              <li
                class="country"
                data-countrycode="FR"
                data-countryname="France"
              >
                <div class="dropdown-menuitem">
                  <span class="flag-icon flag-icon-fr"></span>
                  <div class="country-name">France</div>
                  <div class="active-icon-wrapper"></div>
                </div>
              </li>

              <li
                class="country"
                data-countrycode="GB"
                data-countryname="United Kingdom"
              >
                <div class="dropdown-menuitem">
                  <span class="flag-icon flag-icon-gb"></span>
                  <div class="country-name">United Kingdom</div>
                  <div class="active-icon-wrapper"></div>
                </div>
              </li>

              <li
                class="country"
                data-countrycode="DE"
                data-countryname="Germany"
              >
                <div class="dropdown-menuitem">
                  <span class="flag-icon flag-icon-de"></span>
                  <div class="country-name">Germany</div>
                  <div class="active-icon-wrapper"></div>
                </div>
              </li>

              <li
                class="country"
                data-countrycode="ES"
                data-countryname="Spain"
              >
                <div class="dropdown-menuitem">
                  <span class="flag-icon flag-icon-es"></span>
                  <div class="country-name">Spain</div>
                  <div class="active-icon-wrapper"></div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </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-shape 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