How to Create a Web Map (Leaflet, Mapbox, OpenLayers)

How to Create a Web Map (Leaflet, Mapbox, OpenLayers)

I remember my first web map very clearly, because it was so disappointing. It was 2007, and I had spent a week writing a page that displayed twelve points on a gray rectangle. It loaded slowly, it didn’t zoom smoothly, and it looked like nothing. Then I discovered the libraries that came afterward, and in an afternoon I had a full-screen, pannable, zoomable map with pop-ups. The leap between those two experiences is why I tell every GIS professional: you should know how to put a map on a web page.

Web maps are how most people encounter geography now. Your colleagues, your clients and the public expect to open a link, drag a map and click on things. In this guide I will show you how a web map is built, compare the main libraries, Leaflet, OpenLayers, MapLibre and Mapbox, and walk you through creating your first maps with working code. You don’t need to be a programmer. If you can edit an HTML file, you can follow this.

If you prefer to publish without code, the cloud platforms described in Getting Started with ArcGIS Online and the export tools mentioned in Best GIS Plugins for QGIS are good alternatives. Learning the code, though, gives you full control.

Diagram: A web map is a browser library on top of tile and data services, a server and a database.
A web map is a browser library on top of tile and data services, a server and a database.

What Is a Web Map?

A web map is an interactive map displayed in a browser. Under the hood, it’s assembled from a few parts.

  • A map library: JavaScript code that draws the map and handles interaction, such as dragging and zooming.
  • A basemap: the background, usually made of small square images called tiles, or of vector tiles that the browser draws.
  • Overlay layers: your own data, such as points, lines and polygons (often GeoJSON), or imagery and services (WMS, WMTS).
  • Interaction: pop-ups, tooltips, filters, legends and controls.
  • A hosting location: a web server that delivers the page and the data.

How tiles work

A tiled map is like a giant paper atlas cut into small squares. The world is divided into a pyramid of zoom levels. At zoom 0, the whole world fits in one tile. At each higher zoom, every tile is divided into four. The browser requests only the tiles needed for the current view, using addresses of the form z/x/y: zoom level, column and row. This is why web maps load quickly even though the world is large.

Most tile maps use the Web Mercator projection (EPSG:3857), which gives the familiar look and the smooth zoom, but distorts areas near the poles. We explain its strengths and traps in Map Projections: How to Choose the Right One. The key practical rule: display in Web Mercator, but analyze in a proper projection.

Raster tiles vs. vector tiles

  • Raster tiles are pre-drawn images. Simple and universally supported, but the style is fixed on the server, and they look soft on high-resolution screens unless larger versions are provided.
  • Vector tiles contain the geometry and attributes, and the browser draws them. They’re smaller, sharp at every scale, can be restyled on the fly, rotated and tilted. They require a library that supports them, such as MapLibre or OpenLayers.

The Main Libraries Compared

Leaflet

A lightweight, friendly, open-source library, and the easiest way to get started. It handles raster tiles, markers, shapes and GeoJSON beautifully, with a huge plugin ecosystem. It’s designed for simplicity and works on both desktop and mobile.

  • Best for: simple to moderately complex maps, quick prototypes, learning, and most everyday needs.
  • Limits: not designed for very large datasets or advanced rendering. Vector tiles and 3D need plugins.

OpenLayers

A powerful, feature-rich, open-source library built for GIS-grade web applications. It supports many projections, vector tiles, WMS, WMTS and WFS services, editing, complex styling and large data.

  • Best for: professional web GIS, applications requiring standards support, many coordinate systems and advanced functionality.
  • Limits: a steeper learning curve and a more verbose API.

MapLibre GL JS

An open-source library for fast, smooth, WebGL-rendered vector maps. It was born as a community continuation of Mapbox GL JS after that project changed its license. It handles vector tiles, rotation, tilt, 3D terrain, heat maps, clustering and data-driven styling.

  • Best for: modern, beautiful, high-performance maps with vector data, and large datasets.
  • Limits: needs a source of vector tiles and a style, and works best with a graphics-capable browser.

Mapbox GL JS

The proprietary library from Mapbox, with a similar feature set to MapLibre, tightly integrated with Mapbox’s data, styles and services. Recent versions need an access token and are billed by usage, with a free tier.

  • Best for: teams that want a polished, integrated commercial platform with design tools and support.
  • Limits: a commercial license and usage-based costs, plus dependence on one vendor.

Others to know

  • Google Maps JavaScript API: a well-known commercial option with its own data and terms.
  • CesiumJS: 3D globes and terrain.
  • deck.gl: large-scale data visualization layers, often used together with a base library.
  • Turf.js: spatial analysis in the browser, a companion to any of the above.

Choosing

NeedGood choice
Learn, prototype or build a simple map quicklyLeaflet
A professional web GIS, with many projections and OGC servicesOpenLayers
A modern vector-tile map with smooth zoom, tilt and big dataMapLibre GL JS
A polished commercial platform with design toolsMapbox GL JS
3D globeCesiumJS
Huge datasets and analytical visualsdeck.gl with a base library

For a broader view of the open-source toolkit, see Best Free and Open-Source GIS Tools, and for the development ecosystem, Geospatial Development & Automation: The Ultimate Guide.


Basemaps and Their Terms of Use

You need a source of background tiles. Options:

  • OpenStreetMap standard tiles: convenient for learning and small sites, but the public tile server has a usage policy: it is not intended for heavy traffic or commercial services, and requires attribution.
  • Free-tier tile providers: several companies offer basemaps with free tiers and an API key. Check their quotas and terms.
  • Commercial providers: paid services with high-quality maps, imagery and support.
  • Your own tiles: you can generate and host your own, using open data, for full control.
  • Satellite and aerial imagery: available from providers with specific licenses. Don’t copy imagery from popular map websites, since their terms generally forbid it.
Illustration: Each zoom level splits the map into four times as many tiles, all with the same pixel size.
Each zoom level splits the map into four times as many tiles, all with the same pixel size.

Attribution is mandatory

Almost every basemap and data source requires attribution, a visible credit such as “© OpenStreetMap contributors”. Leave the attribution control on, and follow each provider’s wording. It’s both a legal duty and a courtesy.


Your First Map With Leaflet

Create a file called index.html and paste this. Open it in a browser and you have a working map.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>My first web map</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
  <style>
    html, body, #map { height: 100%; margin: 0; }
  </style>
</head>
<body>
  <div id="map"></div>

  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
  <script>
    // Create the map: [latitude, longitude], zoom level
    var map = L.map('map').setView([48.8566, 2.3522], 12);

    // Add the basemap tiles, with the required attribution
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    // Add a marker with a pop-up
    L.marker([48.8584, 2.2945]).addTo(map).bindPopup('<b>Eiffel Tower</b>');
  </script>
</body>
</html>

What each part does:

  • The link and script tags load the Leaflet library.
  • The #map container must have a height, or the map will be invisible. This is the most common beginner problem.
  • L.map(...).setView(...) creates the map, centered on a latitude and longitude (in that order for Leaflet), at a zoom level.
  • L.tileLayer(...) adds the basemap, with its attribution.
  • L.marker(...) adds a point with a pop-up.

Adding your own data as GeoJSON

Most of your data will arrive as GeoJSON. Here is how to load a polygon layer and color it by a value, a simple choropleth.

// Choose a fill color from a value (thresholds are examples)
function colorFor(rate) {
  return rate > 60 ? '#bd0026' :
         rate > 40 ? '#f03b20' :
         rate > 20 ? '#fd8d3c' :
         rate > 10 ? '#fecc5c' : '#ffffb2';
}

fetch('districts.geojson')
  .then(function (response) { return response.json(); })
  .then(function (data) {
    var layer = L.geoJSON(data, {
      style: function (feature) {
        return {
          color: '#ffffff',      // outline
          weight: 1,
          fillColor: colorFor(feature.properties.rate),
          fillOpacity: 0.8
        };
      },
      onEachFeature: function (feature, lyr) {
        lyr.bindPopup('<b>' + feature.properties.name + '</b><br>Rate: ' + feature.properties.rate);
      }
    }).addTo(map);

    map.fitBounds(layer.getBounds());   // zoom to the data
  });

Because browsers restrict reading local files, you should view this through a web server, such as a simple local server or a hosting service, rather than by double-clicking the file. A quick local option is to run a tiny server in the folder with your files. The color choices follow the rules in Color Theory for Maps, and the classification logic is covered in Choropleth, Heat, and Proportional Symbol Maps: When to Use Each.


The Same Idea With OpenLayers

OpenLayers is usually used with a build tool, so here is the minimal modern setup. First install it in a project:

npm install ol

Then write your map code:

import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import { fromLonLat } from 'ol/proj';

new Map({
  target: 'map',
  layers: [
    new TileLayer({ source: new OSM() })
  ],
  view: new View({
    center: fromLonLat([2.3522, 48.8566]),   // [longitude, latitude]
    zoom: 12
  })
});

Notice two differences from Leaflet. OpenLayers expects longitude first, and works in the map’s projection, so you convert coordinates with fromLonLat. That explicit handling of projections is why OpenLayers shines for professional work, and why it can display layers in many coordinate systems. See Coordinate Reference Systems (CRS) Explained Simply.


A Vector-Tile Map With MapLibre

MapLibre GL JS draws vector maps with WebGL. This minimal page uses a public demonstration style from the project:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>MapLibre example</title>
  <link href="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css" rel="stylesheet" />
  <style>
    html, body, #map { height: 100%; margin: 0; }
  </style>
</head>
<body>
  <div id="map"></div>
  <script src="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script>
  <script>
    var map = new maplibregl.Map({
      container: 'map',
      style: 'https://demotiles.maplibre.org/style.json',
      center: [2.3522, 48.8566],     // [longitude, latitude]
      zoom: 4
    });
    map.addControl(new maplibregl.NavigationControl());
  </script>
</body>
</html>

The demonstration style is a basic world map for testing. For a real project you will use a style and tiles from a provider you trust, or host your own. In production, pin the library version (as shown) instead of loading “the latest”, so that updates don’t break your site unexpectedly. Check the project’s site for the current release number.


And With Mapbox GL JS

Mapbox GL JS works in a very similar way to MapLibre, but requires an access token from your Mapbox account:

mapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN';

const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v12',
  center: [2.3522, 48.8566],   // [longitude, latitude]
  zoom: 11
});

Treat the token with care: restrict it to your website’s domain in the account settings, so that others can’t use your quota, and monitor your usage.


The Coordinate Order Trap

One mistake accounts for a remarkable share of web map bugs: the order of latitude and longitude.

ContextOrder
Leaflet positions (setView, L.marker)latitude, longitude
GeoJSON coordinateslongitude, latitude
OpenLayers (with fromLonLat)longitude, latitude
MapLibre and Mapboxlongitude, latitude
Everyday speech and many GPS displayslatitude, longitude

If your points appear in the ocean off the coast of Africa, or in the wrong hemisphere, you’ve almost certainly swapped them. Leaflet’s GeoJSON helper handles the conversion for you, but manually created markers don’t.


Preparing Your Data for the Web

Raw GIS data is usually too heavy for a browser. Prepare it.

  1. Reproject to WGS 84 (EPSG:4326) for GeoJSON, which is the standard’s requirement. Libraries then project it for display.
  2. Convert to a web-friendly format: GeoJSON for small to medium data. You can do it in QGIS by exporting, or with GDAL:
ogr2ogr -f GeoJSON districts.geojson districts.gpkg -t_srs EPSG:4326 \
  -lco COORDINATE_PRECISION=6
  1. Reduce precision: six decimal places (about 10 centimeters) is plenty for most uses, and shrinks files significantly.
  2. Simplify geometry for display with a tool such as mapshaper or QGIS’s simplify function, keeping an eye on topology. Don’t simplify your analytical data.
  3. Remove unneeded attributes. Send only the fields your map uses.
  4. Check the size. A few megabytes of GeoJSON is comfortable. Tens of megabytes will make a page sluggish.
  5. For bigger data, use tiles. Convert to vector tiles, using tools such as tippecanoe, and host them as a tileset or in a single-file format such as PMTiles. Then the browser loads only what is visible.
  6. For imagery and large rasters, use tiled formats, such as Cloud Optimized GeoTIFF with a tile server, or pre-generated XYZ or WMTS tiles.
  7. Use standard services when appropriate. Your GIS server can publish WMS, WMTS and WFS, and the libraries above can consume them. See Enterprise GIS & Spatial Databases: PostGIS, Geodatabases, and Server Architecture, and later Intro to Web GIS APIs and OGC Standards (WMS, WFS, WMTS).

For the data format background, see Shapefile vs. GeoJSON vs. GeoPackage: Which Format to Use?


Making the Map Useful: Design and Interaction

A technically working map is only the start. Design it for readers.

  • Start with the message. What should a visitor understand in five seconds? Design for that. The principles are in Cartography Principles: Designing Maps That Communicate.
  • Choose a calm basemap and vivid data, with a palette that follows Color Theory for Maps.
  • Provide a legend, explaining symbols and colors in plain language.
  • Write good pop-ups: a clear title, a few relevant fields with readable labels, units and perhaps a link. Hide technical field names.
  • Add controls only if needed: zoom buttons, a scale bar, a layer switcher, a search box. Clutter hurts.
  • Set an appropriate initial extent that shows the data right away, with fitBounds.
  • Adapt to the scale: show fewer labels and symbols at small scales, and more detail as readers zoom in.
  • Cluster dense points, so that thousands of markers don’t hide the pattern, using clustering plugins or built-in options.
  • Make it responsive: test on phones, with large enough touch targets, and a layout that adapts.
  • Mind accessibility: sufficient contrast, keyboard operation, text alternatives or a data table for key information, and don’t rely on color alone.
  • Consider performance: limit data, use tiles, avoid redrawing, and load progressively.

Publishing Your Map

A web map is just files: a page, scripts, styles and data. Publishing means putting them on a web server.

  • Static hosting: services that host simple sites for free or little cost are ideal for most web maps. Upload the folder, and share the link.
  • Your own web server or content management system: embed the map in a page, or use an iframe.
  • HTTPS: serve everything over HTTPS. Browsers block “mixed content”, so an HTTPS page can’t load HTTP tiles or data.
  • CORS: if your data comes from another server, that server must allow cross-origin requests, or the browser will refuse to load it.
  • Hosting data: keep your data files on the same host, or on a service built for it.
  • Keep keys safe: never publish secret keys. Use public tokens with domain restrictions.
  • Caching and performance: enable compression and caching, and consider a content delivery network for heavy traffic.
  • Metadata and credits: include a description, data sources, date and contact, in the spirit of Metadata in GIS: Why It Matters and How to Create It.

No-Code and Low-Code Alternatives

You don’t always have to write code.

  • QGIS export plugins: tools such as qgis2web turn a QGIS project into a Leaflet or OpenLayers web map you can host anywhere. See Best GIS Plugins for QGIS.
  • Cloud platforms: ArcGIS Online and similar services let you build and share web maps in a browser. See Getting Started with ArcGIS Online.
  • Simple online map makers: services for quick, shareable maps from a spreadsheet or file.
  • Design tools: commercial platforms provide visual style editors for vector maps.

These are excellent for speed and for non-technical users. Writing code gives you more control and no dependence on a platform.


Common Mistakes

  • A map container with no height, resulting in a blank page.
  • Swapped latitude and longitude.
  • Opening the HTML from the file system and being blocked from loading data. Use a server.
  • Forgetting attribution, or using a tile source in violation of its terms.
  • Loading a huge GeoJSON and wondering why the page is slow. Simplify or use vector tiles.
  • Leaving projected coordinates in GeoJSON. Reproject to WGS 84.
  • Publishing an access key without restrictions.
  • Mixed content errors, from HTTP resources on an HTTPS page.
  • Unpinned library versions, which can break your site after an update.
  • Ignoring mobile users.
  • Too many layers and controls, drowning the message.
  • Relying on color alone, or using unreadable palettes.
  • Measuring on a web map. Remember that Web Mercator distorts areas and distances.
  • Not testing in different browsers and devices.

A Learning Path

  1. Make the Leaflet example work, and change the center, zoom and marker.
  2. Load a GeoJSON of your own, and style it by an attribute.
  3. Add a legend and a layer switcher.
  4. Try clustering on a larger point set.
  5. Convert a layer to vector tiles and display it with MapLibre.
  6. Add a service (WMS or WMTS) from a public provider.
  7. Explore OpenLayers for projections and advanced functions.
  8. Combine the map with charts and filters into a small application. See Story Maps and Interactive Dashboards.
  9. Learn Git and hosting to publish and maintain your work.

Final Thoughts

A web map is the most direct way to put geographic information in front of the people who need it. The libraries are mature, free and well documented, and the first working map takes minutes. What takes longer, and what separates a decent map from an excellent one, is the care you give to data preparation, design, performance and honesty: a clear message, a calm basemap, a readable legend, correct credits and a file size that respects your reader’s phone.

Make the first example work today. Then replace the marker with your own data, and watch your layer appear on a live map that anyone with the link can explore. That moment of seeing your work on the open web is a big step from analyst to publisher.

Where to go next: apply your classification and colors in Choropleth, Heat, and Proportional Symbol Maps: When to Use Each, and combine maps with narrative and charts in Story Maps and Interactive Dashboards.

Rachid Khouri

Rachid Khouri

Rachid Khouri is a CAD, BIM and GIS professional, Autodesk Authorized Developer, trainer and technical author with more than 30 years of experience, working with AutoCAD since 1992. He founded GISauthority.com to share practical guidance on GIS and spatial technologies.