How to get a reference to the already loaded leaflet map in Djano's admin page using Django-leaflet

405 Views Asked by At

I'm trying to add markers to the leaflet map loaded in Django's admin pages with data retrieved from an ajax call. However I cannot get a reference to the map that I can use in my template used to override the Django admin template.

If I load the page, open the console, and run the code below it works. The marker is added to the map.

Console:

var map = window['leafletmapid_location-map'];
L.marker([40.3830621, -111.773658]).addTo(map);

However if I include the exact same code in my template it doesn't work because it is not getting the reference to the map, and I can't figure out why.

Template:

{% extends "admin/change_form.html" %}
{% load i18n admin_urls %}

{% block content %}{{ block.super }}
<script>
    var map = window['leafletmapid_location-map'];
    L.marker([40.3830621, -111.773658]).addTo(map);
</script>
{% endblock %}

If I replace the entire script tag with the following I get undefined which I believe is the cause of the problem.

Template:

<script>
    console.log(window['leafletmapid_location-map'])
</script>

However if in change the template to the following I get the window object, and it shows it has the leafletmapid_location-map object available.

Template:

<script>
    console.log(window)
</script>
1

There are 1 best solutions below

0
Ernesto Ruiz On

The official django-leaflet documentation offers details of how to do it. Read documentation

<script>
    window.addEventListener("map:init", function (e) {
        var detail = e.detail;
        ...
        L.marker([50.5, 30.5]).addTo(detail.map);
        ...
    }, false);
</script>