DEV Community

Cover image for Your Web GIS, your UI: building a custom map dashboard with NextGIS Frontend
Eduard Kazakov
Eduard Kazakov

Posted on

Your Web GIS, your UI: building a custom map dashboard with NextGIS Frontend

Building a custom Web GIS application often means spending a lot of time on things that are not unique to your project: configuring data services, implementing map rendering, handling coordinate systems, connecting a frontend to geospatial data.

But what if we already have a Web GIS server that takes care of all these tasks?

In my previous article, I demonstrated how to deploy a fully functional, open-source NextGIS Web server on a VPS using Docker.

Today, we will take the next step: build a completely custom web application using our existing NextGIS Web instance as its backend.

Our application will feature:

  • An interactive map with layers and styles loaded from NextGIS Web.
  • A custom sidebar displaying map layers and their legend symbols.
  • A histogram showing the population distribution of cities in the current map extent.
  • Automatic statistics updates as the user pans and zooms.

We will use NextGIS Frontend, an open-source JavaScript SDK designed specifically for building geospatial web applications on the top of NextGIS Web.

Additional GIS backend, separate map services, or complicated frontend frameworks are not required!

Custom app build in the top of NextGIS Web

Meet NextGIS Frontend

NextGIS Frontend is a collection of JavaScript libraries that simplify the development of custom mapping applications on the top of NextGIS Web.

It supports three popular open-source mapping engines:

NextGIS Frontend provides a common API across these different mapping engines, so you can easily switch between them.

For example, this is enough to display an existing NextGIS Web Map in your application:

import NgwMap from '@nextgis/ngw-leaflet';

const ngwMap = new NgwMap({
  target: 'map',
  baseUrl: 'https://ekazakov.nextgis.com',
  resources: [
    { resource: 4778, fit: true }
  ]
});

await ngwMap.onLoad();
Enter fullscreen mode Exit fullscreen mode

The SDK automatically retrieves the Web Map configuration from NextGIS Web and initializes its layers using the corresponding styles.

NextGIS Frontend also includes NgwConnector, a library providing convenient access to the NextGIS Web REST API. It handles API routing, authentication, and request caching, so we do not need to construct HTTP requests manually.

In our application, we will use the SDK higher-level methods whenever possible, and access NgwConnector directly when we need additional information from the GIS backend. Both approaches allow us to interact with NGW without depending on a particular mapping engine.

We do not need to manually configure endpoints, reproduce layer styling, or load individual datasets. And because we are working with NextGIS Web through its API, we can also access feature attributes, perform spatial queries, and build custom interactions.

Let's see how this works in practice!

Prepare a Web Map in NextGIS Web

First, we need some data. We will use a world map based on Natural Earth datasets, containing four layers:

  • Populated places
  • Lakes
  • Rivers
  • Land

Source web map in NextGIS Web UI

The populated places dataset includes a POP_MAX attribute, representing the estimated maximum population of each populated place. We will use it to calculate our population histogram.

The easiest way to prepare this example is to organize and style the layers in QGIS, then upload the QGIS project to NextGIS Web using the NextGIS Connect plugin.

You can also upload individual datasets and configure a Web Map through the NextGIS Web interface.

For this tutorial, I have already prepared a public example: https://ekazakov.nextgis.com/resource/4778/display?panel=layers

We only need two resource IDs:

Why two IDs?

The Web Map stores the configuration of our map, including layers, styles, their order, and other visualization settings.

The vector layer stores the actual geographical features and their attributes, including POP_MAX.

We can inspect the configuration of any resource through the NextGIS Web REST API: https://ekazakov.nextgis.com/api/resource/4778

For example, the webmap.root_item property contains the map's layer hierarchy.

This separation between data, map configuration, and visualization is exactly what makes NextGIS Web convenient as a backend for custom applications!

Create the application

Get the code here.

Let's start a new project with Vite.

! Make sure you have Node.js and npm installed.

npm create vite@latest ngw-cities-dashboard -- --template vanilla

cd ngw-cities-dashboard

npm install

Now install NextGIS Frontend and Chart.js:

npm install @nextgis/ngw-leaflet chart.js

We will keep the application simple:

ngw-cities-dashboard/
├── index.html
├── package.json
├── vite.config.js
└── src/
    ├── main.js
    └── style.css
Enter fullscreen mode Exit fullscreen mode

Configure Vite

We will deploy the application under /cities/, so let's configure the build accordingly.

Create vite.config.js:

import { defineConfig } from 'vite';

export default defineConfig({
  base: '/cities/'
});
Enter fullscreen mode Exit fullscreen mode

This tells Vite to generate asset URLs relative to /cities/ instead of the domain root.

Create the page layout

Replace the contents of index.html with:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0"
    />
    <title>World Cities Dashboard</title>
  </head>

  <body>
    <div id="app">
      <aside class="sidebar">
        <header>
          <h1>World Cities</h1>
          <p>
            An interactive geospatial dashboard
            powered by NextGIS Web
          </p>
        </header>

        <section>
          <h2>Map layers</h2>
          <div id="layers"></div>
        </section>

        <section>
          <h2>Population distribution</h2>
          <p id="statistics-status">
            Loading population data...
          </p>

          <div class="chart-container">
            <canvas id="population-chart"></canvas>
          </div>
        </section>
      </aside>

      <main id="map"></main>
    </div>

    <script type="module" src="/src/main.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Our application has two main components: a sidebar containing the layer controls and statistics, and a map to be rendered in the remaining space.

Display the map legend

Let's build a sidebar showing the layers and their original legend symbols.

We could manually inspect the Web Map configuration, retrieve individual style resources, and generate symbols ourselves... But NextGIS Frontend already provides this functionality!

The getLegend() method retrieves legend information for the layers loaded in our map:

const legends = await ngwMap.getLegend();

Each legend object contains information about an individual map layer and its symbols.We can access:

  • layer.layerId, an internal identifier assigned by NextGIS Frontend.
  • layer.resourceId, the NGW resource associated with the legend.
  • layer.legend, an array containing the legend symbols.
  • layer.create(), a method for retrieving the legend symbols when necessary.

The symbol objects contain information such as:

{
  display_name: '1 - 600000',
  icon: {
    format: 'png',
    data: 'iVBORw0KGgoAAAANSUhEUg...'
  },
  render: true
}
Enter fullscreen mode Exit fullscreen mode

The icon.data property contains a base64-encoded image, while icon.format identifies its format.

This means we can display the original symbols from NGW without reproducing their appearance using CSS or other rendering libraries.

Get the original layer names

There is one more thing we need: the identifiers returned by the legend API are not necessarily the human-readable layer names configured in NextGIS Web. Fortunately, the Web Map resource already contains those names.

We could retrieve its configuration by sending a regular HTTP request to the NGW API, but NextGIS Frontend provides a more convenient solution: NgwConnector.

Every NgwMap instance includes an initialized connector that provides access to NextGIS Web resources and API endpoints.

Let's use it to retrieve our Web Map configuration:

const webmapResource = await ngwMap.connector.getResource(
  WEBMAP_ID,
  { cache: true }
);

const webmapLayers = webmapResource.webmap.root_item.children
  .filter(item => item.item_type === 'layer');
Enter fullscreen mode Exit fullscreen mode

That's all we need!

Alternatively, we can access the NGW REST API through the connector's route interface:

const webmapResource = await ngwMap.connector
  .route('resource.item', { id: WEBMAP_ID })
  .get({ cache: true });
Enter fullscreen mode Exit fullscreen mode

This gives us access to the full NextGIS Web API without manually constructing URLs or handling HTTP requests.

NgwConnector also provides request caching and authentication support, making it especially useful when building more sophisticated applications.

Each layer entry contains its display name and associated resource identifiers:

{
  item_type: 'layer',
  display_name: 'Populated places (NED)',
  layer_style_id: 104,
  style_parent_id: 103,
  layer_enabled: true
}
Enter fullscreen mode Exit fullscreen mode

We can use these properties to display the actual names configured in the Web Map.

Render the legend

Now let's combine the layer names and symbols. Add the following function to main.js:

async function renderLegend() {
  const container = document.getElementById('legend');
  container.replaceChildren();

  try {
    // Retrieve legends through NextGIS Frontend
    const legends = await ngwMap.getLegend();

    // Retrieve Web Map configuration through NgwConnector
    const webmapResource = await ngwMap.connector.getResource(
      WEBMAP_ID,
      { cache: true }
    );

    if (!webmapResource?.webmap?.root_item) {
      throw new Error('Web Map configuration is unavailable');
    }

    const webmapLayers = webmapResource.webmap.root_item.children
      .filter(item => item.item_type === 'layer');

    // Render each layer and its legend
    for (const [index, layer] of legends.entries()) {
      const group = document.createElement('div');
      group.className = 'legend-layer';

      // Use the original NGW layer name
      const heading = document.createElement('strong');

      heading.textContent =
        webmapLayers[index]?.display_name ??
        `Layer ${layer.layerId}`;

      group.append(heading);

      // Retrieve legend symbols if necessary
      const symbols = layer.legend?.length
        ? layer.legend
        : (await layer.create?.()) ?? [];

      for (const symbol of symbols) {
        const row = document.createElement('div');
        row.className = 'legend-symbol';

        // Display the original NGW legend icon
        if (symbol.icon?.data) {
          const icon = document.createElement('img');

          icon.src =
            `data:image/${symbol.icon.format};base64,${symbol.icon.data}`;

          icon.alt = symbol.display_name || '';

          row.append(icon);
        }

        // Display the symbol label
        const label = document.createElement('span');

        label.textContent = symbol.display_name || '';

        row.append(label);
        group.append(row);
      }

      container.append(group);
    }

    if (!legends.length) {
      container.textContent = 'No legend available.';
    }

  } catch (error) {
    console.error('Failed to load map legend:', error);

    container.textContent = 'Could not load legend.';
  }
}

await renderLegend();
Enter fullscreen mode Exit fullscreen mode

That's it! We've created a custom legend using the original symbols and layer names from NextGIS Web.

Custom sidebar displaying the four map layers and their original NGW legend symbols

The resulting legend can contain multiple symbols for a single layer, including categorized or graduated styles created in QGIS.

Notice that we don't need to implement our own rendering logic. We use the symbols prepared by NextGIS Web!

For a more advanced implementation, see the official NextGIS Frontend Web Map Legend example: https://code.nextgis.com/demo-examples-ngw-webmap-legend

Request features within the current map extent

Now let's add something that is not available in our original Web Map: an interactive population histogram. When the map displays the whole world, we will calculate the population distribution of all populated places in our dataset.

When we zoom into Europe, the histogram should show only populated places within the current map extent. If we pan to another region, it should update again.

To do this, we need to retrieve the POP_MAX attribute from our populated places layer. We could write raw HTTP requests to the NextGIS Web API and manually construct spatial filters.

But once again, NextGIS Frontend already provides the functionality we need!

Get the current map extent

First, we can obtain the geographical bounds of our map:

const bounds = ngwMap.getBounds();
console.log(bounds);
Enter fullscreen mode Exit fullscreen mode

The result is an array containing the current bounds: [west, south, east, north]

All coordinates are expressed in longitude and latitude.

We don't even need to know the coordinate reference system used internally by NextGIS Web, NextGIS Frontend handles the spatial request for us.

Query NextGIS Web features

The SDK provides the fetchNgwLayerFeatures() method, which allows us to retrieve features from an NGW vector layer using spatial and attribute filters. For example, we can request all populated places intersecting the current map extent:

const result = await ngwMap.fetchNgwLayerFeatures({
  resourceId: CITIES_LAYER_ID,
  intersects: bounds,
  fields: ['POP_MAX'],
  geom: false
});
Enter fullscreen mode Exit fullscreen mode

The bounds variable here is obtained from ngwMap.getBounds() as shown above.

Notice how little GIS-specific code we need:

  • resourceId identifies our vector layer.
  • intersects limits the query to the current map extent.
  • fields specifies which attributes we need.
  • geom: false avoids transferring feature geometries that aren't needed for the histogram.

We don't need to transform coordinates into Web Mercator or construct WKT geometries manually. NextGIS Frontend takes care of preparing the request.

The result is a GeoJSON FeatureCollection.

To extract population values:

const populations = result.features
  .map(feature => Number(feature.properties.POP_MAX))
  .filter(pop => Number.isFinite(pop) && pop > 0);
Enter fullscreen mode Exit fullscreen mode

We now have an array of population values for the cities currently visible on the map.

Handle pagination

For larger extents, a query might return thousands of features.

To make sure we retrieve all matching records, let's implement pagination.

Instead of keeping the individual query examples above, we'll combine everything into a single function that we can reuse throughout the application. Add the following to main.js:

async function getVisiblePopulations() {
  const bounds = ngwMap.getBounds();

  if (!bounds) {
    return [];
  }

  const populations = [];
  const limit = 1000;

  for (let offset = 0; ; offset += limit) {
    const result = await ngwMap.fetchNgwLayerFeatures({
      resourceId: CITIES_LAYER_ID,
      intersects: bounds,
      fields: ['POP_MAX'],
      geom: false,
      limit,
      offset
    });

    const features = result.features ?? [];

    for (const feature of features) {
      const population = Number(
        feature.properties?.POP_MAX
      );

      if (
        Number.isFinite(population) &&
        population > 0
      ) {
        populations.push(population);
      }
    }

    // Stop when the final page is reached
    if (features.length < limit) {
      break;
    }
  }

  return populations;
}
Enter fullscreen mode Exit fullscreen mode

Now we can retrieve population values using:

const populations = await getVisiblePopulations();

The function automatically determines the current map extent and retrieves all matching records. It doesn't need to know how the map is rendered or which geographical projection is used by the backend.

The SDK handles communication with NGW, and we only implement the application-specific logic.

For very large datasets, we could potentially implement server-side aggregation instead of transferring all matching attributes to the browser.

Also, if we wanted to display a large vector dataset using dynamic viewport-based loading, NextGIS Frontend provides its BBOX and BBOX+ strategies. You can explore this functionality in the BBOX+ strategy example: https://code.nextgis.com/demo-examples-ngw-bbox-plus-strategy

In our case, the populated places are already displayed using their NGW styles. We don't need to load a second vector layer for rendering, only retrieve the attributes required for statistics.

Create the population histogram

City populations vary enormously, from small towns with a few thousand residents to megacities with tens of millions, so we'll use logarithmic population intervals:

  • Below 10000
  • 10000-100000
  • 100000-1 million
  • 1-10 million
  • 1M-10M
  • Above 10 million

Let's implement a simple function to count populated places within each interval.

const populationBins = [
  0,
  10_000,
  100_000,
  1_000_000,
  10_000_000,
  Infinity
];

const populationLabels = [
  '<10K',
  '10K-100K',
  '100K-1M',
  '1M-10M',
  '>10M'
];

function calculateHistogram(populations) {
  const counts = populationLabels.map(() => 0);

  for (const population of populations) {
    for (let i = 0; i < counts.length; i++) {
      if (
        population >= populationBins[i] &&
        population < populationBins[i + 1]
      ) {
        counts[i]++;
        break;
      }
    }
  }

  return counts;
}
Enter fullscreen mode Exit fullscreen mode

This is vanila JavaScript. NextGIS Frontend has already handled the geospatial part of the problem.

Initialize Chart.js

Let's create our chart! Add the following to main.js:

const chart = new Chart(
  document.getElementById('population-chart'),
  {
    type: 'bar',

    data: {
      labels: populationLabels,

      datasets: [
        {
          label: 'Populated places',
          data: populationLabels.map(() => 0),
          backgroundColor: '#377eb8',
          borderRadius: 4
        }
      ]
    },

    options: {
      responsive: true,
      maintainAspectRatio: false,

      plugins: {
        legend: {
          display: false
        },

        tooltip: {
          callbacks: {
            label: (context) =>
              `${context.parsed.y} populated places`
          }
        }
      },

      scales: {
        x: {
          title: {
            display: true,
            text: 'Population'
          }
        },

        y: {
          beginAtZero: true,

          ticks: {
            precision: 0
          },

          title: {
            display: true,
            text: 'Number of populated places'
          }
        }
      }
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

We now have a simple bar chart showing the number of populated places in each population category. Initially, all values are zero.

Let's create a function to update it when new data becomes available.

function updateHistogram(populations) {
  const counts = calculateHistogram(populations);

  chart.data.datasets[0].data = counts;
  chart.update();

  document.getElementById(
    'statistics-status'
  ).textContent =
    `${populations.length.toLocaleString()} populated places in view`;
}
Enter fullscreen mode Exit fullscreen mode

The function calculates the population distribution, updates Chart.js, and displays the total number of populated places in the current map extent.

We now have all the components necessary for our dashboard! The only thing missing is connecting the histogram to map navigation.

Update the histogram when the map moves

We want our histogram to update whenever the user pans or zooms the map. The idea is to listen for viewport changes, request updated population values, and redraw the chart. First, let's create the update function.

let requestVersion = 0;

async function refreshStatistics() {
  const version = ++requestVersion;

  const status = document.getElementById(
    'statistics-status'
  );

  status.textContent = 'Updating statistics...';

  try {
    const populations = await getVisiblePopulations();

    // Ignore results from outdated requests
    if (version !== requestVersion) {
      return;
    }

    updateHistogram(populations);

  } catch (error) {
    if (version !== requestVersion) {
      return;
    }

    console.error(
      'Could not retrieve population statistics:',
      error
    );

    status.textContent =
      'Could not load population statistics.';
  }
}
Enter fullscreen mode Exit fullscreen mode

The requestVersion variable ensures that an older request cannot overwrite the results of a newer one. For example, if the user quickly zooms from Europe to Asia, we want to display the statistics for Asia even if the previous request takes longer to complete.

This doesn't cancel the previous request, but it prevents outdated data from appearing in the interface.

Listen for map movements

NextGIS Frontend provides a common event system that works across the supported mapping engines. We can subscribe to the moveend event, which fires when the user finishes panning or zooming the map:

ngwMap.emitter.on('moveend', refreshStatistics);

// Load the initial statistics
await refreshStatistics();
Enter fullscreen mode Exit fullscreen mode

That's it! We don't need to access the underlying Leaflet, OpenLayers, or MapLibre GL instance.

This is another advantage of NextGIS Frontend unified API: our application logic remains independent of the mapping engine.

Now, whenever the map extent changes:

  1. NextGIS Frontend provides the new geographical bounds.
  2. We request matching populated places from NextGIS Web.
  3. We extract their population attributes.
  4. Chart.js displays the updated distribution.

Add some styling

Create src/style.css to set up the app appearance:

* {
  box-sizing: border-box;
}

html,
body,
#app {
  margin: 0;
  width: 100%;
  height: 100%;
}

body {
  font-family: system-ui, sans-serif;
  color: #263238;
  background: #fff;
}

#app {
  display: flex;
}

.sidebar {
  width: 360px;
  flex-shrink: 0;
  padding: 24px;

  background: #fff;
  border-right: 1px solid #e0e0e0;

  overflow-y: auto;
}

.sidebar header {
  margin-bottom: 32px;
}

.sidebar h1 {
  margin: 0 0 8px;
  font-size: 24px;
}

.sidebar h2 {
  margin: 0 0 16px;
  font-size: 16px;
}

.sidebar p {
  color: #607d8b;
  line-height: 1.5;
}

.sidebar section {
  margin-bottom: 32px;
}

.legend-layer {
  margin-bottom: 16px;
}

.legend-layer strong {
  display: block;
  margin-bottom: 8px;
}

.legend-symbol {
  display: flex;
  align-items: center;
  gap: 10px;

  margin: 6px 0;
  font-size: 14px;
}

.legend-symbol img {
  max-width: 32px;
  max-height: 24px;
  object-fit: contain;
}

.chart-container {
  height: 260px;
}

#map {
  flex: 1;
  min-width: 0;
  height: 100%;
}

@media (max-width: 700px) {
  #app {
    flex-direction: column-reverse;
  }

  #map {
    height: 55vh;
    flex: none;
  }

  .sidebar {
    width: 100%;
    height: 45vh;

    border-right: none;
    border-top: 1px solid #e0e0e0;
  }
}
Enter fullscreen mode Exit fullscreen mode

Everything is very simple here. We can combine an existing GIS backend with completely custom interfaces and functionality.B the way, nothing prevents us from using React, Vue, or another frontend framework for more sophisticated applications together with NextGIS Frontend.

Run and test the application

Finally, we have built an interactive geospatial dashboard without implementing any custom GIS backend. Let's run it.

npm run dev

Vite will start a local development server, usually at:

http://localhost:5173

Open it in your browser.

Final app

Notice that our application doesn't have a local copy of the geospatial data. All map layers, styles, and feature attributes come directly from NextGIS Web.

For this public example, the relevant NGW resources are accessible anonymously. For private applications, NextGIS Frontend also provides mechanisms for authenticated interaction with NGW. You should also set up CORS in NextGIS Web: https://docs.nextgis.com/docs_ngweb/source/cors.html#cross-origin-resource-sharing-cors

Final thoughts

There are many ways to build applications like this, and some are certainly more straightforward. For example, you could load geospatial data directly from a static, hosted GeoParquet file without setting up a GIS backend at all.

However, having a fully functional, powerful Web GIS like NextGIS Web behind your application offers some significant advantages:

  • Efficient data storage and management for vector and raster datasets, as well as point clouds.
  • QGIS-based symbology, providing virtually unlimited styling flexibility that goes far beyond what standard web mapping libraries offer.
  • Built-in APIs for data access, spatial filtering, and aggregation.
  • Flexible, fine-grained permission management to control access to resources and data.
  • A ready-to-use administration interface for managing data, maps, styles, users, and permissions.

You can manage data and map configurations directly through the NextGIS Web interface, use the QGIS integration to enable collaborative data editing across large teams, or connect your own external tools and workflows. All these changes can then be reflected in your custom frontend application.

NextGIS Frontend makes it easy to focus on building the interfaces and functionality your users actually need, while NextGIS Web takes care of the GIS infrastructure behind them.

Useful links

Top comments (0)