Dynamic map center

As per the documentation, we need to set the longitude and latitude for the map center. Is it possible that the map center can be determined dynamically based on the store positions?
For example, we have many stores in different countries so I want to set the map center with the given country.

Thanks for the help.

Hi @usman.qureshi
Yes, you can do it in several ways. It depends on the SDK you’re using.
If you use the Store Locator Widget, you can simply set the fitBounds paramater to true. see this section on the devdoc: Configure the Woosmap Store Locator Widget | Woosmap Developers
The map will automatically adapt the center and zoom to enclose all the stores attached to your project. You can also set the initialCenter and initialZoom by yourself.

If you use the Map JS API, you can set center and zoom of your MapOptions

Please let me know if you require further information.

Thank you @gael for your quick response.
We are using Map JS API and if I understood correctly there isn’t any option like fitBounds for it. We must have to give a static value to center initially. right?

Yes, If you’re using the StoresOverlay to display your stores, there’s no easy way to fit the bounds to all your assets. You could do it on your side by first requesting all your assets and then build a bounds to pass to the map object.
here is a little snippet to build a bounds object once you have all your stores.


const features = getAllStoresFromAPI() // You first need to request all your stores using API https://api.woosmap.com/stores/search/
const bounds = new woosmap.map.LatLngBounds();

features.forEach((feature) => {
    const latLng = {lat: feature.geometry.coordinates[1], lng: feature.geometry.coordinates[0]} ;
    bounds.extend(LatLng);
});
this.map.fitBounds(bounds, padding);

We note that a storesOverlay.getBounds() method would help a lot here.
Thanks for your feedback.

2 Likes

Thank you so much @gael.
I managed to have the dynamic center of the map with this approach.

1 Like

Hey @usman.qureshi,
we recently released the Bounds endpoint dedicated to compute bounds for your assets.
It accepts same search query parameter as Store Search API and returns a LatLngBoundsLiteral that you can pass to the fitBounds() method.

Here is a simple implementation to retrieve bounds based on stores country code and fit the map on them.

async function getBounds() {
  const query = "country:GB";
  const url = `https://api.woosmap.com/stores/search/bounds?key=PUBLIC_API_KEY&query=${query}`;
  const response = await fetch(url);
  return response.json();
}

getBounds().then((boundsResponse) => {
  this.map.fitBounds(boundsResponse.bounds);
});