#StandWithUkraine - Stop the Russian invasion

Join us and donate. We are contributing all book royalties from 2022 to present to:
Save Life in Ukraine and Ukraine Humanitarian Appeal.

Leaflet Maps with CSV Data

This open-source template is designed to improve your coding skills by demonstrating how to create a Leaflet point map that pulls data from a CSV file located in your GitHub repo. While you can make the same type of map on other platforms, such as Google My Maps as described in Chapter 7, you’ll more about how the Leaflet code library works by doing it yourself.

Figure 12.40 shows a simple point map of some colleges and universities in Connecticut. But instead of individually creating markers in JavaScript using Leaflet’s L.marker() function, the point data is stored in a local CSV file (data.csv) that is easy to modify in any text editor or spreadsheet. Each time the map is loaded by the browser, point data from the CSV file is read and markers are generated “on the fly.”

Figure 12.40: Explore the interactive Leaflet point map with CSV data.

You can adapt this template to create your own point map by following these instructions:

  1. Visit the GitHub repo that stores the code for this template. Make sure you are logged in, and press Use this template button to create a copy of this repository in your own GitHub account.
  2. Put your point data inside data.csv. The only relevant columns that will be read by the template are Latitude, Longitude, and Title. The first two determine the location of the marker, and the last one is displayed in a popup. The order of columns does not matter. There can be other columns in the dataset, but they will be ignored.

Your data can look like the following:

Trinity College,41.745167,-72.69263
Wesleyan University,41.55709,-72.65691
  1. Depending on the geography of your points, you will want to change the default position of the map on start. In index.html, find the <script> tag, and edit the following chunk of code:
var map = L.map('map', {
  center: [41.57, -72.69], // Default latitude and longitude on start
  zoom: 9,  // Between 1 and 18; decrease to zoom out, increase to zoom in
  scrollWheelZoom: false

We used default Leaflet markers for code simplicity, but you may want to use custom icons instead. The code snippet below can give you an idea how to set it up in your GitHub repository, where you insert your unique pathname to your icon in place of the sample.

var marker = L.marker([row.Latitude, row.Longitude], {
  opacity: 1,
  // Customize your icon
  icon: L.icon({
    iconUrl: 'path/to/your/icon.png',
    iconSize: [40, 60]

To learn more, see this helpful Leaflet documentation example about custom icons.