Search code examples
djangoleaflet

leaflet does not display the map in my django application


I am developing an application with django. In a page of this application I want to display a map with leaflet. I try to display a basic map according to the information I could have on the leaflet site but nothing is displayed. There is not even an error message in the console.
templatefile.html:

{% extends 'elec_meter/base.html' %}
{% load static %}
{% block title %}Geolocalisation des compteurs - Interactiv {% endblock %}
{% block titre %} Carte {% endblock %}
{% block css %}
     <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
       integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
       crossorigin=""/>

    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
       integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
       crossorigin="">
    </script>
    <script src="{% static 'assets/js/main.js' %}"></script>
<style>
    <link href="{% static 'assets/css/style.css' %}" rel="stylesheet" />
</style>
{% endblock %}
{% block add %}{% endblock %}

{% block content %}
    <div class="row" onload="init">
        <div id="mapid" style="height:450;">

        </div>
    </div>
{% endblock %}

Here is the content of my js file which initializes the map: main.js

function init(){
    const coordGabon = {
        lat: -0.803689,
        lng: 11.609444
    }
    const zoomLevel = 13;

    const mymap = L.map('mapid').setView([coordGabon.lat, coordGabon.lng],zoomLevel);

    const mainLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19,attribution: '© OpenStreetMap'}).addTo(mymap);
}

Solution

  • From reading your code, I suspect there are two things at play:

    1. onload is not a valid event for a div element
    2. height:450; is not valid CSS

    In short: the map does not get instantiated and has no height.

    Please try the following; modify this part

    {% block content %}
        <div class="row" onload="init">
            <div id="mapid" style="height:450;">
    
            </div>
        </div>
    {% endblock %}
    

    to

    {% block content %}
        <div class="row">
            <div id="mapid" style="height:450px;"></div>
        </div>
    
        <script>
          // in case the document is already rendered
          if (document.readyState !== 'loading') {
            init();
          }
          // modern browsers
          else if (document.addEventListener) {
            document.addEventListener('DOMContentLoaded', init());
          }
        </script>
    {% endblock %}
    
    

    Of course this is a quick prototype solution. If it works, I recommend moving the inline CSS style to the 'assets/css/style.css' file.