Multiple Location Markers with OpenStreetMap and Leaflet.js

Spread the love

In this guide, we’ll walk through the process of creating a map with multiple location markers using OpenStreetMap and Leaflet.js. Leaflet.js is a lightweight and open-source JavaScript library for interactive maps.

Step 1: Set Up Your Project

To begin, set up the basic HTML structure and include the required Leaflet.js CDN links for CSS and JavaScript.

1.1 Add Required CDNs

Include the following CDNs in your HTML <head> section:

<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>

1.2 Basic HTML Structure

Create a container for the map in the <body> section:

<h3>Multiple Location Markers with OpenStreetMap</h3>
<div id="map"></div>

Step 2: Style the Map Container

Define the dimensions for your map container using CSS. This ensures the map displays properly.

#map {
      height: 500px;
      width: 100%;
     }

Step 3: Initialize the Map

Use Leaflet.js to initialize the map and set its view to a default location.

3.1 JavaScript Code to Initialize

// Initialize the map and set its view
const map = L.map('map').setView([40.730610, -73.935242], 2);

// Set up the OpenStreetMap layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors'
}).addTo(map);
  • L.map(‘map’) : Initializes the map and binds it to the HTML element with the id=”map” .
  • .setView([lat, lng], zoom) : Sets the initial center of the map to latitude and longitude with a zoom level (e.g., 2 for world view).
  • L.tileLayer() : Adds OpenStreetMap tiles as the map’s base layer.

Step 4: Add Multiple Markers

To display multiple markers on the map, use an array of locations and loop through it to create markers.

4.1 Define Location Data

Create an array of objects where each object represents a location:

const locations = [
  { lat: 40.730610, lng: -73.935242, title: "New York" },
  { lat: 34.052235, lng: -118.243683, title: "Los Angeles" },
  { lat: 51.507351, lng: -0.127758, title: "London" },
  { lat: 48.856613, lng: 2.352222, title: "Paris" }
];

4.2 Add Markers Dynamically

Loop through the array to create markers for each location:

locations.forEach(location => {
  L.marker([location.lat, location.lng]).addTo(map)
    .bindPopup(location.title);
});
  • L.marker([lat, lng]) : Creates a marker at the specified latitude and longitude.
  • .addTo(map) : Adds the marker to the map.
  • .bindPopup(title) : Binds a popup to the marker that shows when clicked.

Step 5: Full Working Example

Here’s the complete code for your project:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Multiple Location Markers</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
  <style>
    #map {
      height: 500px;
      width: 100%;
    }
  </style>
</head>
<body>
  <h3>Multiple Location Markers with OpenStreetMap</h3>
  <div id="map"></div>
  <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
  <script>
    // Initialize the map and set its view
    const map = L.map('map').setView([40.730610, -73.935242], 2);

    // Set up the OpenStreetMap layer
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    // Array containing locations [latitude, longitude, name]
    const locations = [
      { lat: 40.730610, lng: -73.935242, title: "New York" },
      { lat: 34.052235, lng: -118.243683, title: "Los Angeles" },
      { lat: 51.507351, lng: -0.127758, title: "London" },
      { lat: 48.856613, lng: 2.352222, title: "Paris" }
    ];

    // Loop through the locations and create markers
    locations.forEach(location => {
      L.marker([location.lat, location.lng]).addTo(map)
        .bindPopup(location.title);
    });
  </script>
</body>
</html>

Step 6: Test Your Map

  1. Save the file as index.html.
  2. Open the file in a browser.
  3. You should see a map displaying markers for New York, Los Angeles, London, and Paris. Clicking on a marker will display the associated location name in a popup.

Step 7: Enhance Your Map (Optional)

  • Add custom marker icons using L.icon.
  • Display a clustered view for a large number of markers using the Leaflet.markercluster plugin.
  • Include dynamic data from an API or database.

See the Pen Multiple Location Markers with OpenStreetMap – leaflet by Pawan Mall (@iPawan) on CodePen.

This project demonstrates how to use OpenStreetMap and Leaflet.js to display multiple locations interactively. It is beginner-friendly and can be easily extended with more features!

Pawan Mall

Leave a Reply

Back to top