MultiSearch Map Advanced

This example shows how to use the MultiSearch JS API and Map JS API to create a simple map with a search box. Parameters allows to limit the search to a specific country and to always search in stores attributes

Example

MultiSearch Map Advanced
        const searchOptions = {
  apiOrder: ["store", "localities", "places"],
  debounceTime: 100,
  localities: {
    key: "YOUR_API_KEY",
    fallbackBreakpoint: 0.4,
    params: {
      components: {
        country: ["gb", "fr", "de"],
      },
      language: "en",
      types: ["locality", "postal_code", "address"],
    },
  },
  store: {
    key: "YOUR_API_KEY",
    fallbackBreakpoint: false,
    params: {
      query: "type:bose_store",
    },
  },
  places: {
    key: "YOUR_GOOGLE_API_KEY",
    fallbackBreakpoint: 1,
    minInputLength: 10,
    params: {
      components: {
        country: ["gb", "fr", "de"],
      },
    },
  },
};
// The MultiSearch JS API ships no typings: describe the parts this sample uses.
interface MultiSearchPrediction {
  id: string;
  api: string;
  description?: string;
  highlight: string;
}

interface MultiSearch {
  autocompleteMulti(input: string): Promise<MultiSearchPrediction[]>;
  detailsMulti(request: { id: string; api: string }): Promise<unknown>;
}

interface MultiSearchGlobal {
  multisearch(options: object): MultiSearch;
}

let multiSearch: MultiSearch;
let inputElement: HTMLInputElement;
let suggestionsList: HTMLUListElement;
let clearSearchBtn: HTMLButtonElement;
let map: woosmap.map.Map;
let marker: woosmap.map.marker.AdvancedMarkerElement;
let infoWindow: woosmap.map.InfoWindow;

function initSearch(): void {
  inputElement = document.getElementById(
    "autocomplete-input",
  ) as HTMLInputElement;
  suggestionsList = document.getElementById(
    "suggestions-list",
  ) as HTMLUListElement;
  clearSearchBtn = document.getElementsByClassName(
    "clear-searchButton",
  )[0] as HTMLButtonElement;
  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";
    if (marker) {
      marker.setMap(null);
    }
    if (infoWindow) {
      infoWindow.close();
    }
    inputElement.focus();
  });

  multiSearch = (woosmap as unknown as MultiSearchGlobal).multisearch(searchOptions);
}

async function initMap(): Promise<void> {
  await woosmap.map.importLibrary("maps");
  await woosmap.map.importLibrary("marker");

  map = (document.getElementById("map") as woosmap.map.MapElement).innerMap;
  map.moveCamera({
      center: { lat: 51.50940214, lng: -0.133012 },
      zoom: 4,
    });
  infoWindow = new woosmap.map.InfoWindow({});
  initSearch();
}

function handleAutocomplete(): void {
  if (inputElement && suggestionsList) {
    const input = inputElement.value;
    input.replace('"', '\\"').replace(/^\s+|\s+$/g, "");
    if (input !== "") {
      multiSearch.autocompleteMulti(input).then(
        (results) => displaySuggestions(results),
        (error) => console.error(`Error autocomplete localities: ${error}`),
      );
    } else {
      suggestionsList.style.display = "none";
      clearSearchBtn.style.display = "none";
    }
  }
}

function handleNoResults(): void {
  const li = document.createElement("li");
  li.innerHTML = "<div class='prediction no-result'>No results found...</div>";
  suggestionsList.appendChild(li);
  suggestionsList.className = "";
  suggestionsList.style.display = "block";
}

function displaySuggestions(results) {
  if (inputElement && suggestionsList) {
    suggestionsList.innerHTML = "";
    if (results.length > 0) {
      results.forEach((result) => {
        const li = document.createElement("li");
        li.className = `${result.api}-api`;
        li.innerHTML = formatPredictionList(result) ?? "";
        li.addEventListener("click", () => {
          inputElement.value = result.description ?? "";
          suggestionsList.style.display = "none";
          multiSearch
            .detailsMulti({ id: result.id, api: result.api })
            .then((details) => {
              displayLocality(details, result.api);
            });
        });
        suggestionsList.appendChild(li);
      });
      suggestionsList.className = results[0].api;
      suggestionsList.style.display = "block";
      clearSearchBtn.style.display = "block";
    } else {
      handleNoResults();
    }
  }
}

function formatPredictionList(result): string {
  const predictionClass = "no-viewpoint";
  const formatted_name = result.highlight;
  let html = "";
  html += `<div class="api-icon"></div><div class="prediction ${predictionClass}">${formatted_name}</div>`;
  return html;
}

function createMarker(result) {
  const { PinElement } = woosmap.map.marker;
  const pin = new PinElement({
    background: "#5588FF",
    borderColor: "#3D6FE0",
    glyphColor: "#FFFFFF",
  });

  return new woosmap.map.marker.AdvancedMarkerElement({
    position: result.geometry.location,
    content: pin.element,
    gmpClickable: true,
  });
}

function createInfoWindowHTML(result, apiName: string) {
  let addressComponentsHTML = "";
  if (result.address_components) {
    result.address_components.forEach((component) => {
      addressComponentsHTML += `<p>${component.long_name} (${component.short_name})</p>`;
    });
  }
  return `<div class="info-content">${apiName ? `<div>api: <strong>${apiName}</strong></div>` : ""}
      ${result.name ? `<p>${result.name}</p>` : ""}
      ${result.formatted_address ? `<p>${result.formatted_address}</p>` : ""}
      ${addressComponentsHTML}</div>`;
}

function displayLocality(result, apiName: string) {
  if (marker) {
    marker.setMap(null);
  }
  if (infoWindow) {
    infoWindow.close();
  }
  if (result?.geometry) {
    marker = createMarker(result);
    marker.setMap(map);
    const infoWindowHTML = createInfoWindowHTML(result, apiName);
    infoWindow.setContent(infoWindowHTML);
    marker.addListener("click", () => {
      infoWindow.open({map, anchor: marker});
    });
    map.setCenter(result.geometry.location, { top: 150 });
    map.setZoom(14);
    woosmap.map.event.addListenerOnce(map, "idle", () => {
      infoWindow.open({map, anchor: marker});
    });
  }
}

document.addEventListener("click", (event) => {
  const targetElement = event.target as Element;
  const isClickInsideAutocomplete = targetElement.closest(
    "#autocomplete-container",
  );

  if (!isClickInsideAutocomplete && suggestionsList) {
    suggestionsList.style.display = "none";
  }
});

initMap();

    
        const searchOptions = {
  apiOrder: ["store", "localities", "places"],
  debounceTime: 100,
  localities: {
    key: "YOUR_API_KEY",
    fallbackBreakpoint: 0.4,
    params: {
      components: {
        country: ["gb", "fr", "de"],
      },
      language: "en",
      types: ["locality", "postal_code", "address"],
    },
  },
  store: {
    key: "YOUR_API_KEY",
    fallbackBreakpoint: false,
    params: {
      query: "type:bose_store",
    },
  },
  places: {
    key: "YOUR_GOOGLE_API_KEY",
    fallbackBreakpoint: 1,
    minInputLength: 10,
    params: {
      components: {
        country: ["gb", "fr", "de"],
      },
    },
  },
};
let multiSearch;
let inputElement;
let suggestionsList;
let clearSearchBtn;
let map;
let marker;
let infoWindow;

function initSearch() {
  inputElement = document.getElementById("autocomplete-input");
  suggestionsList = document.getElementById("suggestions-list");
  clearSearchBtn = document.getElementsByClassName("clear-searchButton")[0];
  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";
    if (marker) {
      marker.setMap(null);
    }

    if (infoWindow) {
      infoWindow.close();
    }

    inputElement.focus();
  });
  multiSearch = woosmap.multisearch(searchOptions);
}

async function initMap() {
  await woosmap.map.importLibrary("maps");
  await woosmap.map.importLibrary("marker");
  map = document.getElementById("map").innerMap;
  map.moveCamera({
    center: { lat: 51.50940214, lng: -0.133012 },
    zoom: 4,
  });
  infoWindow = new woosmap.map.InfoWindow({});
  initSearch();
}

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

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

function handleNoResults() {
  const li = document.createElement("li");

  li.innerHTML = "<div class='prediction no-result'>No results found...</div>";
  suggestionsList.appendChild(li);
  suggestionsList.className = "";
  suggestionsList.style.display = "block";
}

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

        li.className = `${result.api}-api`;
        li.innerHTML = formatPredictionList(result) ?? "";
        li.addEventListener("click", () => {
          inputElement.value = result.description ?? "";
          suggestionsList.style.display = "none";
          multiSearch
            .detailsMulti({ id: result.id, api: result.api })
            .then((details) => {
              displayLocality(details, result.api);
            });
        });
        suggestionsList.appendChild(li);
      });
      suggestionsList.className = results[0].api;
      suggestionsList.style.display = "block";
      clearSearchBtn.style.display = "block";
    } else {
      handleNoResults();
    }
  }
}

function formatPredictionList(result) {
  const predictionClass = "no-viewpoint";
  const formatted_name = result.highlight;
  let html = "";

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

function createMarker(result) {
  const { PinElement } = woosmap.map.marker;
  const pin = new PinElement({
    background: "#5588FF",
    borderColor: "#3D6FE0",
    glyphColor: "#FFFFFF",
  });
  return new woosmap.map.marker.AdvancedMarkerElement({
    position: result.geometry.location,
    content: pin.element,
    gmpClickable: true,
  });
}

function createInfoWindowHTML(result, apiName) {
  let addressComponentsHTML = "";

  if (result.address_components) {
    result.address_components.forEach((component) => {
      addressComponentsHTML += `<p>${component.long_name} (${component.short_name})</p>`;
    });
  }
  return `<div class="info-content">${apiName ? `<div>api: <strong>${apiName}</strong></div>` : ""}
      ${result.name ? `<p>${result.name}</p>` : ""}
      ${result.formatted_address ? `<p>${result.formatted_address}</p>` : ""}
      ${addressComponentsHTML}</div>`;
}

function displayLocality(result, apiName) {
  if (marker) {
    marker.setMap(null);
  }

  if (infoWindow) {
    infoWindow.close();
  }

  if (result?.geometry) {
    marker = createMarker(result);
    marker.setMap(map);

    const infoWindowHTML = createInfoWindowHTML(result, apiName);

    infoWindow.setContent(infoWindowHTML);
    marker.addListener("click", () => {
      infoWindow.open({ map, anchor: marker });
    });
    map.setCenter(result.geometry.location, { top: 150 });
    map.setZoom(14);
    woosmap.map.event.addListenerOnce(map, "idle", () => {
      infoWindow.open({ map, anchor: marker });
    });
  }
}

document.addEventListener("click", (event) => {
  const targetElement = event.target;
  const isClickInsideAutocomplete = targetElement.closest(
    "#autocomplete-container",
  );

  if (!isClickInsideAutocomplete && suggestionsList) {
    suggestionsList.style.display = "none";
  }
});
initMap();

    
        /*
 * Always set the map height explicitly to define the size of the element
 * that contains the map. `display: block` is required for <wmp-map>/<gmp-map>,
 * which default to inline like any other custom element outside a flex/grid
 * container (no-op for a plain <div>).
 */
#map {
  display: block;
  width: 100%;
  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%;
}

#suggestions-list li {
  display: flex;
  align-items: center;
}
#suggestions-list li .api-icon {
  height: 20px;
  width: 20px;
  background-repeat: no-repeat;
  background-size: contain;
  padding-right: 7px;
}
#suggestions-list li.store-api .api-icon {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' viewBox='0 0 24 24' width='24'%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3Cpath d='M20 4H4v2h16V4zm1 10v-2l-1-5H4l-1 5v2h1v6h10v-6h4v6h2v-6h1zm-9 4H6v-4h6v4z' fill='%23b2b2b2' /%3E%3C/svg%3E");
}
#suggestions-list li.localities-api .api-icon, #suggestions-list li.places-api .api-icon {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' viewBox='0 0 24 24' width='24'%3E%3Cpath d='M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z' fill='%23b2b2b2' /%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3C/svg%3E");
}
#suggestions-list li .no-result {
  opacity: 0.6;
}
#suggestions-list:after {
  content: "";
  box-sizing: border-box;
  text-align: right;
  display: block;
  background-position: right;
  background-repeat: no-repeat;
  background-size: contain;
}
#suggestions-list.places:after {
  padding: 1px 1px 1px 0;
  height: 18px;
  background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white3_hdpi.png);
  background-size: 120px 14px;
}
#suggestions-list.localities:after, #suggestions-list.store:after {
  margin: 0 6px 3px;
  height: 16px;
  background-image: url(https://developers.woosmap.com/assets/images/woosmap-logo.svg);
}

.info-content {
  max-width: 300px;
  height: 100%;
}
.info-content p {
  margin: 3px 0;
}
.info-content code {
  margin-bottom: 10px;
  display: block;
}


    
        <html>
  <head>
    <title>MultiSearch Map Advanced</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8" />

    <script src="https://sdk.woosmap.com/multisearch/multisearch.js"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="app">
      <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 Localities fallback Places..."
          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>
      <wmp-map id="map"></wmp-map>
    </div>

    <script>
      (g=>{var p,w=window,d=document,l="importLibrary",q="__ib__",e="The Woosmap Maps JavaScript API",o=w.woosmap||(w.woosmap={}),m=o.map||(o.map={}),r=new Set(String(g.libraries||"").split(",").filter(Boolean)),s=new URLSearchParams,u=()=>p||(p=new Promise((f,n)=>{var a=d.createElement("script");s.set("libraries",[...r]+"");for(var k in g)k!="libraries"&&g[k]&&s.set(k,g[k]);s.set("callback","woosmap.map."+q);a.src="https://sdk.woosmap.com/map/map.js?"+s;m[q]=f;a.onerror=()=>n(Error(e+" could not load."));a.nonce=d.querySelector("script[nonce]")?.nonce||"";d.head.append(a)}));m[l]?console.warn(e+" only loads once. Ignoring:",g):m[l]=(f,...n)=>r.add(f)&&u().then(()=>m[l](f,...n))})({
        key: "woos-e1e5490b-19d1-34f8-9955-fd5cfc8c880f",
        libraries: "marker",
      });
    </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/multisearch-map-advanced 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 helpful?