How to implement multiple Leaflet JS maps

I’m having a lot of trouble defining multiple maps for all the maps on my website. With the code I have only two maps work, the rest don’t appear. I have been searching for a problem similar to mine but I haven’t come across any.

At the moment I create the div for the map getting the ID from my database in a loop;

<div id="map_<?php echo $data['property']->property_id;?>">...

Which outputs;

<div id="map_1"></div>
<div id="map_2"></div>
...

Those divs are on separate pages. Then I define the maps in my .js file which is where I think I am going wrong, at the moment I have the code below. Is this the wrong way to do it?

// Footer Map
var map = L.map('map').setView([36.367, -5.23], 11);
L.marker([36.367, -5.23]).addTo(map)
        .bindPopup("<center>We are happy to visit:</center> <b>Marbella, Estepona, Sotogrande</b> and all surrounding areas").openPopup();
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoicGF1bHNlYWwiLCJhIjoiY2trMm1zemg4MGxvajJ3b2JwaDdibTA4diJ9.EsvbN_RfG0a1xVHLmpxnjQ', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox/streets-v11',
    tileSize: 512,
    zoomOffset: -1,
    accessToken: 'pk.eyJ1IjoicGF1bHNlYWwiLCJhIjoiY2trMm1zemg4MGxvajJ3b2JwaDdibTA4diJ9.EsvbN_RfG0a1xVHLmpxnjQ'
}).addTo(map);

// Beach House
var map_1 = L.map('map_1').setView([36.33, -5.24], 11);
L.marker([36.367, -5.23]).addTo(map_1)
        .bindPopup("Aldea Beach House").openPopup();
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoicGF1bHNlYWwiLCJhIjoiY2trMm1zemg4MGxvajJ3b2JwaDdibTA4diJ9.EsvbN_RfG0a1xVHLmpxnjQ', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox/streets-v11',
    tileSize: 512,
    zoomOffset: -1,
    accessToken: 'pk.eyJ1IjoicGF1bHNlYWwiLCJhIjoiY2trMm1zemg4MGxvajJ3b2JwaDdibTA4diJ9.EsvbN_RfG0a1xVHLmpxnjQ'
}).addTo(map_1);

1 thought on “How to implement multiple Leaflet JS maps”

  1. If you have the map ids or you can extract them somehow from your php code then you can create an associative array to keep track of the map instances and avoid copy pasting the same code by looping over them.

    <!DOCTYPE html>
    <html>
    
      <head>
    
        <title>Quick Start - Leaflet</title>
    
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
        <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
    
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
        <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
    
      </head>
    
      <body>
    
    
    
        <div id="map_1" style="width: 200px; height: 200px;"></div>
        <div id="map_2" style="width: 200px; height: 200px;"></div>
    
        <script>
          const mapIds = ['map_1', 'map_2'];
          const maps = {};
    
          mapIds.forEach(mapId => {
            maps[mapId] = L.map(mapId).setView([51.505, -0.09], 13);
    
            L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
              maxZoom: 18,
              attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
                'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
              id: 'mapbox/streets-v11',
              tileSize: 512,
              zoomOffset: -1
            }).addTo(maps[mapId]);
    
            if (mapId === mapIds[0]) {
              L.marker([51.5, -0.09]).addTo(maps[mapId])
                .bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
            }
          })
    
        </script>
    
    
    
      </body>
    
    </html>

    You can even render things conditionally depending on the map id.

    What you are doing is not wrong, you just reusing the same code chunk. I am not sure if that answers your question but you can follow this approach to avoid rewriting the same chunks of code

    Reply

Leave a Comment