Learn Javascript

Web Maps

Create interactive maps for the web

slides | md

About

  • Interactive maps on web pages work by loading and displaying images as map layers and then providing controls for panning, zooming, etc.
  • There are several Javascript frameworks that make it easy to create maps. This demo uses Leaflet, which is free, open source, and mobile friendly.

Map Tiles

  • Imagery in a web map consists of a base layer and overlay layers.
  • The base layer is created from a tileset, or collection of raster (e.g. satellite photos), or vector images, displayed in a grid.
  • Loading maps as tiles is efficient because the browser only needs to request those images needed in the viewport.
  • It also makes it easy to change the base image by simply pointing to a different tileset server. Example servers: Mapbox, OSM, leaflet-providers more

Zoom levels

  • In addition to location, map tiles correspond to specific zoom levels.
  • Zoom level 0 shows the full earth, while the highest level (18 in Leaflet, 23 in MapBox) shows details of a city.
This OSM (Open Street Map) tileset url refers to the zoom/x/y https://tile.openstreetmap.org/1/0/0.png

👉 Leaflet Quickstart

  1. From the Leaflet Quickstart, add the CSS, then JS
  2. Add a div for the map <div id="map"></div>
  3. Make sure the map container height is defined #map { height: 180px; }
  4. In Javascript, initialize the map, add a tileLayer, then continue adding features.
// initialize the map
var map = L.map('map').setView([35.5, -80.85], 13);
  1. Before you can see the map you need to add a tile layer.
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

Geojson

  • Geojson (supported by Leaflet) format can store map data and features.
  • 👉 Paste the below into the geojson.io editor to visualize and add data.
// example-vac.geojson
{
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
            "info": "be here now 🤩"
        },
        "geometry": {
            "coordinates": [-80.84841429929385, 35.50168511342781],
            "type": "Point"
        }
    }]
}

Geojson + Leaflet

  • To add data to a Leaflet map, simply store the geojson data above in a variable, then add it with L.geoJSON().
  • 👉 Continue Leaflet Geojson tutorial
// store previous page in an object
var geojsonFeature = { 
    "type": "FeatureCollection",
    ... 
}
// add it to the map
L.geoJSON(geojsonFeature).addTo(map);

Leaflet Maps

More tutorials

Map Library Comparison

Library Key Cost Description
Leaflet.js free
OpenLayers free
Mapbox GL JS 🔑 50,000 free loads before 💲 Style maps with mapbox-studio
Google Maps API 🔑 free $200 before 💲 Popular
ArcGIS JS API 🔑 💲 Relatively new

Tools

Examples

Presentation comments ...