14

I'm pretty new to leaflet.js and I'm trying to figure out how to assign the same map with the same set of options and layers to a different HTML container instead of having to remove and add a new one every time?

I used to deal with Open layers 2.13 and I had map.render(div); option every time I wanted to set map to another div. Is there a solution similar to this? Many thanks!

John Powell
  • 12,253
  • 6
  • 59
  • 67
Dmitry
  • 161
  • 1
  • 1
  • 5

2 Answers2

18

You can, but you have to duplicate the layers

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

// add the same OpenStreetMap tile layer to the second map
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map2);

http://jsfiddle.net/FranceImage/aj44r7v2/

YaFred
  • 9,698
  • 3
  • 28
  • 40
  • 1
    Thanks for your reply! is that correct that to run your code I would need to have two separate declarations of map and map2 with two different divs? It's fine I guess. I used to have just one declaration of map and then I was passing it to different divs for different pages(instead of creating multiple maps). – Dmitry Aug 14 '14 at 09:29
  • Yes, you must have 2 divs with different ids. You have to create 2 maps objects and you cannot reuse layers that are added to the maps. That seems logical to me when I see the internals of Leaflet (remember, it is a extra lightweight library) – YaFred Aug 14 '14 at 10:14
  • Thanks for this answer. it wasn't logical to me that i couldn't add a defined layer to more than one map. Once I defined duplicates of the layer, it all worked fine. Thanks. – JasonRDalton Nov 16 '14 at 17:32
0

The solution of copying the hard code is not satisfactory, you must of course go through a forEach loop. Here is a complete example (using CDN files):

'use strict'

const getLeaflet = (() => {
  const script = document.createElement('script')
  script.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.js')
  document.head.appendChild(script)
})()

const getMapStyles = (() => {
  const styles = document.createElement('link')
  styles.setAttribute('rel', 'stylesheet')
  styles.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.css')
  document.head.appendChild(styles)
})()

const maps = (() => {
  document.querySelectorAll('.map').forEach(function(item){
    const id = item.id
    const map = () => {
      const el = document.getElementById(id),
            coords = JSON.parse(el.dataset.coords),
            map = L.map(id).setView(coords, el.dataset.zoom)
      L.tileLayer(
        el.dataset.tileserver,
        {attribution: el.dataset.attribution}
      ).addTo(map)
      let icon = L.icon({
        iconUrl: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 512 512'%3E%3Cpath fill='%23E74C3C' d='M256 14C146 14 57 102 57 211c0 172 199 295 199 295s199-120 199-295c0-109-89-197-199-197zm0 281a94 94 0 110-187 94 94 0 010 187z'/%3E%3Cpath fill='%23C0392B' d='M256 14v94a94 94 0 010 187v211s199-120 199-295c0-109-89-197-199-197z'/%3E%3C/svg%3E", // @see https://codepen.io/tigt/post/optimizing-svgs-in-data-uris @see https://codepen.io/jakob-e/pen/doMoML
        iconSize: [40, 40],
        iconAnchor: [20, 40],
        shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
        shadowSize: [50, 70],
        shadowAnchor: [15, 70],
        popupAnchor: [0, -60]
      })
      L.marker(coords, {
        icon: icon
      })
        .bindPopup(el.dataset.name)
        .openPopup()
        .addTo(map)
    }
    window.addEventListener('load', function() {
      map()
    })
  })
})()

html target :

<div class="map" id="map" style="height: 50vh" data-name="Map 1" data-coords="[48.853133,2.349747]" data-zoom="15" data-color="#ff654f" data-tileserver="https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=pk.eyJ1Ijoib2xpdmllcmMiLCJhIjoiY2s5dnNnZWoyMDIzNDNzb2Y1dmQ4MGNtMCJ9.m4U-wYcS4EPcKe9nVXIbUA" data-attribution="&lt;a href=&quot;//www.openstreetmap.org/&quot;&gt;OSM&lt;/a&gt; | &lt;a href=&quot;//www.mapbox.com/&quot;&gt;Mapbox&lt;/a&gt;"></div>
<div class="map" id="map2" style="height: 50vh" data-name="Map 2" data-coords="[48.886719,2.343076]" data-zoom="10" data-color="#ff654f" data-tileserver="https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=pk.eyJ1Ijoib2xpdmllcmMiLCJhIjoiY2s5dnNnZWoyMDIzNDNzb2Y1dmQ4MGNtMCJ9.m4U-wYcS4EPcKe9nVXIbUA" data-attribution="&lt;a href=&quot;//www.openstreetmap.org/&quot;&gt;OSM&lt;/a&gt; | &lt;a href=&quot;//www.mapbox.com/&quot;&gt;Mapbox&lt;/a&gt;"></div>

Online example: CodePen

Olivier C
  • 899
  • 1
  • 13
  • 14