Stores Search

Using the StoresService to search and autocomplete on stores.

  1. Example
  2. Running the Sample Locally

Example

Stores Search
        let map: woosmap.map.Map;
let activeLocation: woosmap.map.Marker | null = null;
let storesOverlay: woosmap.map.StoresOverlay;
const gestureMode: woosmap.map.GestureHandlingMode = "greedy";
let storesService: woosmap.map.StoresService;
let localitiesService: woosmap.map.LocalitiesService;

const storesStyle: woosmap.map.Style = {
  breakPoint: 21,
  rules: [],
  default: {
    color: "#008a2f",
    size: 8,
    minSize: 1,
    icon: {
      url: "https://images.woosmap.com/starbucks-marker.svg",
      scaledSize: {
        height: 40,
        width: 34,
      },
    },
    selectedIcon: {
      url: "https://images.woosmap.com/starbucks-marker-selected.svg",
      scaledSize: {
        height: 50,
        width: 43,
      },
    },
  },
};

const mapOptions: woosmap.map.MapOptions = {
  center: { lat: 51.50940214, lng: -0.133012 },
  zoom: 12,
  styles: [
    {
      featureType: "poi.business",
      elementType: "labels",
      stylers: [
        {
          visibility: "off",
        },
      ],
    },
  ],
  gestureHandling: gestureMode,
};

const inputElement = document.getElementById(
  "autocomplete-input",
) as HTMLInputElement;
const submitButton = document.getElementById(
  "submit-button",
) as HTMLButtonElement;

if (inputElement && submitButton) {
  inputElement.addEventListener("keydown", handleKeyPress);
  submitButton.addEventListener("click", handleGeocodeFromSubmit);
}

function handleKeyPress(event: KeyboardEvent) {
  if (event.key === "Enter") {
    handleGeocode(null);
  }
}

function handleGeocodeFromSubmit() {
  handleGeocode(null);
}

function displayListStores(stores: woosmap.map.stores.StoreResponse[]) {
  const storeTemplates = stores.map(createStoreTemplate);
  const storeList = document.querySelector(".stores-list");
  if (storeList) {
    storeList.innerHTML = storeTemplates.join("");
  }
  addClickListenerToStoreCards(stores);
}

function createStoreTemplate(
  store: woosmap.map.stores.StoreResponse,
  indexStore: number,
) {
  const { name, address, contact, distance } = store.properties;
  const phoneHtml = contact.phone
    ? `<div class='store-contact'><a href='tel:${contact.phone}'>${contact.phone}</a></div>`
    : "";
  const distanceHtml = distance
    ? `<div class='store-distance'>${distance}</div>`
    : "";
  const websiteHtml = contact.website
    ? `<div class='store-website'><a href='${contact.website}' target="_blank">go to website</a></div>`
    : "";

  return `
    <div class='controls summary-store-card' data-index=${indexStore}>
      <div>
        <div><strong>${name} - ${address.city}</strong></div>
        <div>
          <div class='store-address'>${
            (address && address.lines && address.lines.join(", ")) ||
            "Address not available"
          }</div>
          ${phoneHtml}
          ${websiteHtml}
          ${distanceHtml}
        </div>
      </div>
    </div>`;
}

function addClickListenerToStoreCards(
  stores: woosmap.map.stores.StoreResponse[],
) {
  document.querySelectorAll(".summary-store-card").forEach((storeCard) => {
    storeCard.addEventListener("click", () => {
      console.log(stores[storeCard["dataset"].index]);
    });
  });
}

function createLocalitiesRequest(
  latlng: woosmap.map.LatLng | null,
): woosmap.map.localities.LocalitiesGeocodeRequest | null {
  return inputElement
    ? latlng
      ? { latLng: latlng }
      : { address: inputElement.value }
    : null;
}

function handleGeocode(latlng: woosmap.map.LatLng | null) {
  const localitiesRequest = createLocalitiesRequest(latlng);

  if (localitiesRequest) {
    localitiesService
      .geocode(localitiesRequest)
      .then((localities) => handleGeocodeResults(localities))
      .catch(handleError);
  }
}

function handleGeocodeResults(
  localities: woosmap.map.localities.LocalitiesGeocodeResponse,
) {
  const location = localities.results[0]?.geometry?.location;
  location && handleStoresSearch(location);
}

function handleStoresSearch(latlng: woosmap.map.LatLngLiteral) {
  const searchRequest = {
    storesByPage: 15,
    latLng: latlng,
  };

  storesService
    .search(searchRequest)
    .then((stores) => handleSearchResults(stores, latlng))
    .catch(handleError);
}

function handleSearchResults(
  stores: woosmap.map.stores.StoresSearchResponse,
  originalLatLng: woosmap.map.LatLngLiteral,
) {
  if (stores.features.length > 0) {
    displayListStores(stores.features);
    displayStoresAndLocation(stores.features, originalLatLng);
    clearAndAddGeoJsonToMap(stores);
  }
}

function clearAndAddGeoJsonToMap(
  stores: woosmap.map.stores.StoresSearchResponse,
) {
  map.data.forEach((feature) => map.data.remove(feature));
  map.data.addGeoJson(stores);
}

function calculateLatLngBounds(
  stores: woosmap.map.stores.StoreResponse[],
): woosmap.map.LatLngBounds {
  const bounds = new woosmap.map.LatLngBounds();
  stores.forEach((store: woosmap.map.stores.StoreResponse) => {
    bounds.extend(
      new woosmap.map.LatLng(
        store.geometry.coordinates[1],
        store.geometry.coordinates[0],
      ),
    );
  });
  return bounds;
}

function displayStoresAndLocation(
  stores: woosmap.map.stores.StoreResponse[],
  latlng: woosmap.map.LatLngLiteral,
) {
  if (activeLocation) {
    activeLocation.setMap(null);
  }

  if (stores && latlng) {
    activeLocation = new woosmap.map.Marker({
      position: latlng,
      icon: {
        url: "https://images.woosmap.com/marker.png",
        scaledSize: {
          height: 50,
          width: 32,
        },
      },
    });

    const bounds = calculateLatLngBounds(stores);
    bounds.extend(latlng);
    activeLocation.setMap(map);
    map.fitBounds(bounds, {}, true);
  }
}

function initMap() {
  map = new window.woosmap.map.Map(
    document.getElementById("map") as HTMLElement,
    mapOptions,
  );
  storesOverlay = new woosmap.map.StoresOverlay(storesStyle);
  storesOverlay.setMap(map);

  map.data.setStyle((feature: woosmap.map.data.Feature) => {
    const iconPint = feature.getProperty("highlighted")
      ? "https://images.woosmap.com/starbucks-marker-selected.svg"
      : "https://images.woosmap.com/starbucks-marker.svg";
    return { icon: iconPint };
  });

  map.addListener("click", (e) => {
    e.latlng && handleGeocode(e.latlng);
  });

  storesService = new woosmap.map.StoresService();
  localitiesService = new woosmap.map.LocalitiesService();
}

function handleError(error: woosmap.map.errors.APIError) {
  console.error("Error:", error);
}

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

    
        let map;
let activeLocation = null;
let storesOverlay;
const gestureMode = "greedy";
let storesService;
let localitiesService;
const storesStyle = {
  breakPoint: 21,
  rules: [],
  default: {
    color: "#008a2f",
    size: 8,
    minSize: 1,
    icon: {
      url: "https://images.woosmap.com/starbucks-marker.svg",
      scaledSize: {
        height: 40,
        width: 34,
      },
    },
    selectedIcon: {
      url: "https://images.woosmap.com/starbucks-marker-selected.svg",
      scaledSize: {
        height: 50,
        width: 43,
      },
    },
  },
};
const mapOptions = {
  center: { lat: 51.50940214, lng: -0.133012 },
  zoom: 12,
  styles: [
    {
      featureType: "poi.business",
      elementType: "labels",
      stylers: [
        {
          visibility: "off",
        },
      ],
    },
  ],
  gestureHandling: gestureMode,
};
const inputElement = document.getElementById("autocomplete-input");
const submitButton = document.getElementById("submit-button");

if (inputElement && submitButton) {
  inputElement.addEventListener("keydown", handleKeyPress);
  submitButton.addEventListener("click", handleGeocodeFromSubmit);
}

function handleKeyPress(event) {
  if (event.key === "Enter") {
    handleGeocode(null);
  }
}

function handleGeocodeFromSubmit() {
  handleGeocode(null);
}

function displayListStores(stores) {
  const storeTemplates = stores.map(createStoreTemplate);
  const storeList = document.querySelector(".stores-list");

  if (storeList) {
    storeList.innerHTML = storeTemplates.join("");
  }

  addClickListenerToStoreCards(stores);
}

function createStoreTemplate(store, indexStore) {
  const { name, address, contact, distance } = store.properties;
  const phoneHtml = contact.phone
    ? `<div class='store-contact'><a href='tel:${contact.phone}'>${contact.phone}</a></div>`
    : "";
  const distanceHtml = distance
    ? `<div class='store-distance'>${distance}</div>`
    : "";
  const websiteHtml = contact.website
    ? `<div class='store-website'><a href='${contact.website}' target="_blank">go to website</a></div>`
    : "";
  return `
    <div class='controls summary-store-card' data-index=${indexStore}>
      <div>
        <div><strong>${name} - ${address.city}</strong></div>
        <div>
          <div class='store-address'>${
            (address && address.lines && address.lines.join(", ")) ||
            "Address not available"
          }</div>
          ${phoneHtml}
          ${websiteHtml}
          ${distanceHtml}
        </div>
      </div>
    </div>`;
}

function addClickListenerToStoreCards(stores) {
  document.querySelectorAll(".summary-store-card").forEach((storeCard) => {
    storeCard.addEventListener("click", () => {
      console.log(stores[storeCard["dataset"].index]);
    });
  });
}

function createLocalitiesRequest(latlng) {
  return inputElement
    ? latlng
      ? { latLng: latlng }
      : { address: inputElement.value }
    : null;
}

function handleGeocode(latlng) {
  const localitiesRequest = createLocalitiesRequest(latlng);

  if (localitiesRequest) {
    localitiesService
      .geocode(localitiesRequest)
      .then((localities) => handleGeocodeResults(localities))
      .catch(handleError);
  }
}

function handleGeocodeResults(localities) {
  const location = localities.results[0]?.geometry?.location;

  location && handleStoresSearch(location);
}

function handleStoresSearch(latlng) {
  const searchRequest = {
    storesByPage: 15,
    latLng: latlng,
  };

  storesService
    .search(searchRequest)
    .then((stores) => handleSearchResults(stores, latlng))
    .catch(handleError);
}

function handleSearchResults(stores, originalLatLng) {
  if (stores.features.length > 0) {
    displayListStores(stores.features);
    displayStoresAndLocation(stores.features, originalLatLng);
    clearAndAddGeoJsonToMap(stores);
  }
}

function clearAndAddGeoJsonToMap(stores) {
  map.data.forEach((feature) => map.data.remove(feature));
  map.data.addGeoJson(stores);
}

function calculateLatLngBounds(stores) {
  const bounds = new woosmap.map.LatLngBounds();

  stores.forEach((store) => {
    bounds.extend(
      new woosmap.map.LatLng(
        store.geometry.coordinates[1],
        store.geometry.coordinates[0],
      ),
    );
  });
  return bounds;
}

function displayStoresAndLocation(stores, latlng) {
  if (activeLocation) {
    activeLocation.setMap(null);
  }

  if (stores && latlng) {
    activeLocation = new woosmap.map.Marker({
      position: latlng,
      icon: {
        url: "https://images.woosmap.com/marker.png",
        scaledSize: {
          height: 50,
          width: 32,
        },
      },
    });

    const bounds = calculateLatLngBounds(stores);

    bounds.extend(latlng);
    activeLocation.setMap(map);
    map.fitBounds(bounds, {}, true);
  }
}

function initMap() {
  map = new window.woosmap.map.Map(document.getElementById("map"), mapOptions);
  storesOverlay = new woosmap.map.StoresOverlay(storesStyle);
  storesOverlay.setMap(map);
  map.data.setStyle((feature) => {
    const iconPint = feature.getProperty("highlighted")
      ? "https://images.woosmap.com/starbucks-marker-selected.svg"
      : "https://images.woosmap.com/starbucks-marker.svg";
    return { icon: iconPint };
  });
  map.addListener("click", (e) => {
    e.latlng && handleGeocode(e.latlng);
  });
  storesService = new woosmap.map.StoresService();
  localitiesService = new woosmap.map.LocalitiesService();
}

function handleError(error) {
  console.error("Error:", error);
}

window.initMap = initMap;

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

#container {
  height: 100%;
  display: flex;
}

#sidebar {
  flex-basis: 12rem;
  flex-grow: 1;
  max-width: 30rem;
  height: 100%;
  box-sizing: border-box;
  overflow: auto;
}

#map {
  flex-basis: 70vw;
  flex-grow: 5;
  height: 100%;
}

.btn {
  background: #3d5afe;
  border: 0;
  border-radius: 4px;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);
  -webkit-transition: background 0.3s, color 0.3s;
  transition: background 0.3s, color 0.3s;
  box-sizing: border-box;
  font-size: 14px;
  color: #202124;
  cursor: pointer;
  display: inline;
  font-weight: 600;
  height: 40px;
  padding: 0 15px;
  position: relative;
  align-items: center;
}
.btn:hover {
  background: #0a2ffe;
}

.btnText {
  color: #fff;
  cursor: pointer;
  font-size: 0.875rem;
  font-weight: 500;
  letter-spacing: 0;
  line-height: 1.25rem;
}
.btnText:hover {
  text-decoration: none;
}

#sidebar {
  flex-basis: 25rem;
  box-shadow: 0 -2px 4px 0 rgba(0, 0, 0, 0.12);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 1;
}

#stores-panel {
  overflow: hidden;
  background: #fff;
  overflow-y: auto;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
#stores-panel h3 {
  padding: 2rem 1.3rem 1.3rem;
  margin-bottom: 0;
  outline: 0;
}
#stores-panel ul {
  margin: 0 !important;
  padding: 0;
  list-style: none;
}
#stores-panel button {
  border: none;
}

#search-container {
  padding: 1rem 0.5rem;
  background: rgb(250, 251, 252);
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}
#search-container #search-input-container {
  display: flex;
  justify-content: space-between;
}
#search-container h3 {
  margin-top: 0;
}

input {
  padding: 0.6em;
  border: 1px solid #ccc;
  box-shadow: inset 0 1px 3px #ddd;
  border-radius: 4px;
  vertical-align: middle;
  font-weight: normal;
  letter-spacing: 0.01em;
  font-size: 1em;
  display: inline-block;
  box-sizing: border-box;
  width: 100%;
  margin-right: 5px;
}
input[type=text]:focus {
  outline: 0;
  border-color: #03a9f4;
}

.summary-store-card {
  display: flex;
  padding: 0.8rem 0.8rem;
  vertical-align: middle;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
  justify-content: space-between;
}
.summary-store-card:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.store-address {
  line-height: 1.6rem;
}

.store-contact a,
.store-website a {
  padding: 0.2em 0;
  margin-left: 20px;
  color: #1d1d1d;
}
.store-contact a::before,
.store-website a::before {
  content: "";
  background-size: 16px 16px;
  background-repeat: no-repeat;
  padding-right: 20px;
  vertical-align: middle;
  margin-left: -20px;
}

.store-contact a::before {
  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 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M6.54 5c.06.89.21 1.76.45 2.59l-1.2 1.2c-.41-1.2-.67-2.47-.76-3.79h1.51m9.86 12.02c.85.24 1.72.39 2.6.45v1.49c-1.32-.09-2.59-.35-3.8-.75l1.2-1.19M7.5 3H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.49c0-.55-.45-1-1-1-1.24 0-2.45-.2-3.57-.57-.1-.04-.21-.05-.31-.05-.26 0-.51.1-.71.29l-2.2 2.2c-2.83-1.45-5.15-3.76-6.59-6.59l2.2-2.2c.28-.28.36-.67.25-1.02C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1z'/%3E%3C/svg%3E");
}

.store-website a::before {
  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 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M17 7h-4v2h4c1.65 0 3 1.35 3 3s-1.35 3-3 3h-4v2h4c2.76 0 5-2.24 5-5s-2.24-5-5-5zm-6 8H7c-1.65 0-3-1.35-3-3s1.35-3 3-3h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-2zm-3-4h8v2H8z'/%3E%3C/svg%3E");
}


    
        <html>
  <head>
    <title>Stores Search</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="container">
      <div class="search-panel" id="sidebar">
        <div id="search-container">
          <h3>Search Stores Nearby</h3>
          <div id="search-input-container">
            <input
              type="text"
              name="autocomplete"
              id="autocomplete-input"
              placeholder="Search an Address..."
              autocomplete="off"
            />
            <button class="btn" type="submit" id="submit-button">
              <span class="btnText" tabindex="-1">Search</span>
            </button>
          </div>
        </div>
        <div id="stores-panel">
          <div class="stores-list">
            <p style="padding: 0 0.8rem; font-size: 17px">
              Enter an address to geocode and search stores nearby or click on
              the map to reverse geocode and search around this location.
            </p>
          </div>
        </div>
      </div>
      <div id="map"></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/stores-search 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