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);

46 thoughts on “How to implement multiple Leaflet JS maps”

Leave a Comment