Introduction to LeafletJS

Simple Map Example

var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

L.marker([51.5, -0.09]).addTo(map)
    .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
    .openPopup();

Installation

Include the CSS and JavaScript in the Head of the HTML page

Add the CSS First

 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css"/>

Then the JavaScript

Make sure you put this AFTER Leaflet's CSS

 <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>

Then create the map container

<div id="mapid"></div>

Then use CSS to create a height for the container


#mapid {
  height: 400px;
}

Using a Basemap

Mapbox Basemap Example

L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
  {
    attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
  }).addTo(mymap);

Basemap providers for LeafletJS https://leaflet-extras.github.io/leaflet-providers/preview/

What the L ?

L.map('map').setView([51.505, -0.09], 13)

Adding Markers

let marker = L.marker([51.5, -0.09]).addTo(mymap);
marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();

Removing Markers

let marker = L.marker([51.5, -0.09]).addTo(mymap);
marker.remove();

Adding Polygons

let polygon = L.polygon([
      [51.509, -0.08],
      [51.503, -0.06],
      [51.51, -0.047],
    ], { color: 'red'}).addTo(mymap);

// delete the polygon later
polygon.remove()

Other Shapes

Several other map shapes exist:

https://leafletjs.com/reference-1.3.0.html

GeoJSON

{
  "type": "Feature",
  "properties": {
    "name": "My Layer",
    "latitude": 44.0886,
    "longitude": -72.7317
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [-73.35218221090553, 45.00541896831666],
        [-73.18201496808604, 45.00562770855899],
        [-72.76588580182134, 45.00611110701493],
        [-72.34976762188519, 45.006605491799434],
        ...
        ...
      ]
  }
}
let someLayer = L.geoJSON(geoJsonData);
someLayer.addTo(mymap);

Point-within-polygon

https://github.com/mapbox/leaflet-pip

Installation

<script src="https://unpkg.com/@mapbox/leaflet-pip@latest/leaflet-pip.js"></script>

Usage


let layer = L.geoJson(statesData);
let results = leafletPip.pointInLayer([-88, 38], layer);

 Previous Lesson Next Lesson 

Outline

[menu]

/