Stores List

Get all stores recursively. Synchronise the store list with the map display using map bounds and contains method

  1. Example
  2. Running the Sample Locally

Example

Stores List
        let map: woosmap.map.Map;
let activeLocation: woosmap.map.Marker | null = null;
let storesOverlay: woosmap.map.StoresOverlay;
let storesService: woosmap.map.StoresService;
let localitiesService: woosmap.map.LocalitiesService;
let visibleStores: woosmap.map.stores.StoreResponse[] = [];
let allStores: woosmap.map.stores.StoreResponse[] = [];

const storesStyle: woosmap.map.Style = {
  breakPoint: 14,
  rules: [],
  default: {
    color: "#55baa6",
    size: 10,
    minSize: 3,
    icon: {
      url: "https://images.woosmap.com/marker-green.svg",
    },
    selectedIcon: {
      url: "https://images.woosmap.com/marker-red.svg",
    },
  },
};

const mapOptions: woosmap.map.MapOptions = {
  zoom: 5,
  center: {
    lat: 46.5,
    lng: 1.4,
  },
  styles: [{ featureType: "all", stylers: [{ saturation: -100 }] }],
};

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 to filter stores based on map bounds
function filterStoresByBounds(
  stores: woosmap.map.stores.StoreResponse[],
  bounds: woosmap.map.LatLngBounds | null,
): woosmap.map.stores.StoreResponse[] {
  return stores.filter((store: woosmap.map.stores.StoreResponse) =>
    bounds
      ? bounds.contains({
          lat: store.geometry.coordinates[1],
          lng: store.geometry.coordinates[0],
        })
      : false,
  );
}

// Function to get all Stores recursively using query.page parameter
function getAllStores() {
  const allStores: woosmap.map.stores.StoreResponse[] = [];
  const query: woosmap.map.stores.StoresSearchRequest = { storesByPage: 300 };

  function getStores(storePage?: number) {
    if (storePage) {
      query.page = storePage;
    }
    return storesService
      .search(query)
      .then((response) => {
        allStores.push(...response.features);
        if (query.page === response.pagination.pageCount) {
          return allStores;
        }
        return getStores(response.pagination.page + 1);
      })
      .catch((err) => {
        console.error(err);
        throw new Error("Error getting all stores");
      });
  }

  return getStores();
}

function displayListStores(stores: woosmap.map.stores.StoreResponse[]) {
  const storeTemplates = stores.map(createStoreTemplate);
  const storeList = document.querySelector(".stores-list");
  if (storeList) {
    storeList.innerHTML = `<p style="padding: 0 0.8rem; font-size: 17px">Results: <strong>${stores.length}</strong> stores in bounds</p>`;
    storeList.innerHTML += storeTemplates.join("");
  }
  addClickListenerToStoreCards(stores);
}

function createStoreTemplate(
  store: woosmap.map.stores.StoreResponse,
  indexStore: number,
) {
  const { name, address, contact } = store.properties;
  const phoneHtml = contact.phone
    ? `<div class='store-contact'><a href='tel:${contact.phone}'>${contact.phone}</a></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} data-store-id="${store.properties.store_id}">
      <div>
        <div><strong>${name}</strong></div>
        <div>
          <div class='store-address'>${
            (address && address.lines && address.lines.join(", ")) ||
            "Address not available"
          }</div>
          ${phoneHtml}
          ${websiteHtml}
        </div>
      </div>
    </div>`;
}

function addClickListenerToStoreCards(
  stores: woosmap.map.stores.StoreResponse[],
) {
  document.querySelectorAll(".summary-store-card").forEach((storeCard) => {
    storeCard.addEventListener("click", () => {
      storesOverlay.setSelection(stores[storeCard["dataset"].index]);
      const storeList = document.querySelector(".stores-list");
      if (storeList) {
        Array.from(storeList.children).forEach((child) =>
          child.classList.remove("active"),
        );
        storeCard.classList.add("active");
      }
    });
  });
}

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

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 && handleSearchResults(location);
}

function handleSearchResults(originalLatLng: woosmap.map.LatLngLiteral) {
  if (activeLocation) {
    activeLocation.setMap(null);
  }

  if (originalLatLng) {
    activeLocation = new woosmap.map.Marker({
      position: originalLatLng,
      icon: {
        url: "https://images.woosmap.com/marker.png",
        scaledSize: {
          height: 50,
          width: 32,
        },
      },
    });
    activeLocation.setMap(map);
    map.setCenter(originalLatLng);
    map.setZoom(8);
  }
}

function selectStoreOnList(storeId?: string) {
  const storeList = document.querySelector(".stores-list");
  if (storeList) {
    if (storeId) {
      const storeElement = Array.from(storeList.children).find(
        (child) => child.getAttribute("data-store-id") == storeId,
      );
      if (storeElement) {
        Array.from(storeList.children).forEach((child) =>
          child.classList.remove("active"),
        );
        storeElement.scrollIntoView({ block: "nearest" });
        storeElement.classList.add("active");
      }
    } else {
      Array.from(storeList.children).forEach((child) =>
        child.classList.remove("active"),
      );
    }
  }
}

// Debounce function
function debounce(func: (...args: any[]) => void, wait: number) {
  let timeout: NodeJS.Timeout;
  return (...args: any[]) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
}

function initMap() {
  map = new window.woosmap.map.Map(
    document.getElementById("map") as HTMLElement,
    mapOptions,
  );
  storesOverlay = new woosmap.map.StoresOverlay(storesStyle);
  storesOverlay.setMap(map);
  map.addListener(
    "bounds_changed",
    debounce(() => {
      const bounds = map.getBounds();
      visibleStores = filterStoresByBounds(allStores, bounds);
      displayListStores(visibleStores);
    }, 50),
  );
  window.woosmap.map.event.addListener(
    map,
    "store_selected",
    (store: woosmap.map.stores.StoreResponse) => {
      selectStoreOnList(store.properties.store_id);
    },
  );
  window.woosmap.map.event.addListener(map, "store_unselected", () => {
    selectStoreOnList();
  });

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

  getAllStores().then((stores: woosmap.map.stores.StoreResponse[]) => {
    allStores = stores;
    displayListStores(stores);
  });
}

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;
let storesService;
let localitiesService;
let visibleStores = [];
let allStores = [];
const storesStyle = {
  breakPoint: 14,
  rules: [],
  default: {
    color: "#55baa6",
    size: 10,
    minSize: 3,
    icon: {
      url: "https://images.woosmap.com/marker-green.svg",
    },
    selectedIcon: {
      url: "https://images.woosmap.com/marker-red.svg",
    },
  },
};
const mapOptions = {
  zoom: 5,
  center: {
    lat: 46.5,
    lng: 1.4,
  },
  styles: [{ featureType: "all", stylers: [{ saturation: -100 }] }],
};
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 to filter stores based on map bounds
function filterStoresByBounds(stores, bounds) {
  return stores.filter((store) =>
    bounds
      ? bounds.contains({
          lat: store.geometry.coordinates[1],
          lng: store.geometry.coordinates[0],
        })
      : false,
  );
}

// Function to get all Stores recursively using query.page parameter
function getAllStores() {
  const allStores = [];
  const query = { storesByPage: 300 };

  function getStores(storePage) {
    if (storePage) {
      query.page = storePage;
    }
    return storesService
      .search(query)
      .then((response) => {
        allStores.push(...response.features);
        if (query.page === response.pagination.pageCount) {
          return allStores;
        }
        return getStores(response.pagination.page + 1);
      })
      .catch((err) => {
        console.error(err);
        throw new Error("Error getting all stores");
      });
  }
  return getStores();
}

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

  if (storeList) {
    storeList.innerHTML = `<p style="padding: 0 0.8rem; font-size: 17px">Results: <strong>${stores.length}</strong> stores in bounds</p>`;
    storeList.innerHTML += storeTemplates.join("");
  }

  addClickListenerToStoreCards(stores);
}

function createStoreTemplate(store, indexStore) {
  const { name, address, contact } = store.properties;
  const phoneHtml = contact.phone
    ? `<div class='store-contact'><a href='tel:${contact.phone}'>${contact.phone}</a></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} data-store-id="${store.properties.store_id}">
      <div>
        <div><strong>${name}</strong></div>
        <div>
          <div class='store-address'>${
            (address && address.lines && address.lines.join(", ")) ||
            "Address not available"
          }</div>
          ${phoneHtml}
          ${websiteHtml}
        </div>
      </div>
    </div>`;
}

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

      const storeList = document.querySelector(".stores-list");

      if (storeList) {
        Array.from(storeList.children).forEach((child) =>
          child.classList.remove("active"),
        );
        storeCard.classList.add("active");
      }
    });
  });
}

function createLocalitiesRequest(latlng) {
  if (!inputElement) {
    return null;
  }

  if (latlng) {
    return { latLng: latlng };
  }
  return { address: inputElement.value };
}

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

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

function handleGeocodeResults(localities) {
  let _a, _b;
  const location =
    (_b =
      (_a = localities.results[0]) === null || _a === void 0
        ? void 0
        : _a.geometry) === null || _b === void 0
      ? void 0
      : _b.location;

  location && handleSearchResults(location);
}

function handleSearchResults(originalLatLng) {
  if (activeLocation) {
    activeLocation.setMap(null);
  }

  if (originalLatLng) {
    activeLocation = new woosmap.map.Marker({
      position: originalLatLng,
      icon: {
        url: "https://images.woosmap.com/marker.png",
        scaledSize: {
          height: 50,
          width: 32,
        },
      },
    });
    activeLocation.setMap(map);
    map.setCenter(originalLatLng);
    map.setZoom(8);
  }
}

function selectStoreOnList(storeId) {
  const storeList = document.querySelector(".stores-list");

  if (storeList) {
    if (storeId) {
      const storeElement = Array.from(storeList.children).find(
        (child) => child.getAttribute("data-store-id") == storeId,
      );

      if (storeElement) {
        Array.from(storeList.children).forEach((child) =>
          child.classList.remove("active"),
        );
        storeElement.scrollIntoView({ block: "nearest" });
        storeElement.classList.add("active");
      }
    } else {
      Array.from(storeList.children).forEach((child) =>
        child.classList.remove("active"),
      );
    }
  }
}

// Debounce function
function debounce(func, wait) {
  let timeout;

  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
}

function initMap() {
  map = new window.woosmap.map.Map(document.getElementById("map"), mapOptions);
  storesOverlay = new woosmap.map.StoresOverlay(storesStyle);
  storesOverlay.setMap(map);
  map.addListener(
    "bounds_changed",
    debounce(() => {
      const bounds = map.getBounds();

      visibleStores = filterStoresByBounds(allStores, bounds);
      displayListStores(visibleStores);
    }, 50),
  );
  window.woosmap.map.event.addListener(map, "store_selected", (store) => {
    selectStoreOnList(store.properties.store_id);
  });
  window.woosmap.map.event.addListener(map, "store_unselected", () => {
    selectStoreOnList();
  });
  storesService = new woosmap.map.StoresService();
  localitiesService = new woosmap.map.LocalitiesService();
  getAllStores().then((stores) => {
    allStores = stores;
    displayListStores(stores);
  });
}

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;
  scroll-behavior: smooth;
}
#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;
  cursor: pointer;
}
.summary-store-card:hover {
  background-color: rgba(0, 0, 0, 0.04);
}
.summary-store-card.active {
  background-color: rgba(0, 0, 0, 0.08);
}

.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 List</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"></div>
        </div>
      </div>
      <div id="map"></div>
    </div>

    <script
      src="https://sdk.woosmap.com/map/map.js?key=woos-5b16337d-8364-303a-854d-86f87b480aa5&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-list-sync-map 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