Search code examples
pythondjangodjango-leaflet

How to add more than one django-leaflet map in a view?


I was able to show a map on a single page using django-leaflet. In another page, I am trying to show two (or more) maps in page but I couldn't figure out how.

For showing map in a single page:

<div class="card">
   {% leaflet_map "main" callback="map_init" %}
</div>

<script type="text/javascript">
function map_init(map, options) {
    // get point lat and lon
    var lon = "{{ project.longitude }}";
    var lat = "{{ project.latitude }}";
    // zoom to point & add it to map
    map.setView([lat, lon], 12);
    L.marker([lat, lon]).addTo(map);

}</script>

Above works fine as long as one map needs to be shown. However I am not sure how I can modify above to support multiple maps.

I have started jsfiddle page here (which is kind of blank), not sure if it's going to helpful.

What I am trying is to fill the 'img-top' div in the html below:

var locations = [
	{"lat":27.988098,"lng":86.924925},
	{"lat":27.679535,"lng":83.507020}
]
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="card-columns m-5">
  <div class="card">
    <div class="card-header">Location A </div>
    <div class="img-top" id="map-1" style="height:200px"></div>
    <div class="card-body">
    Some information of A
    </div>
  </div>
  
   <div class="card">
    <div class="card-header">Location B </div>
    <div class="img-top" id="map-2" style="height:200px"></div>
    <div class="card-body">
    Some information of B
    </div>
  </div>
  
</div>


Solution

  • This is how I was able to display the two (or more) maps dynamically in a div.

    <script type="text/javascript">
    
    items_json.forEach(item => {
        let map = L.map(item.id + "-map").setView([item.fields.latitude, item.fields.longitude], 10);
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);
    });
    
    </script>
    

    In HTML this <div class="img-top" id="{{id}}-map" style="height:200px"></div> gets filled in with the map.

    Here's JS Fiddle: https://jsfiddle.net/droidxn/w7d5nqps/10/