0

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>
kysevenle
  • 63
  • 1
  • 6
  • How and when is `window['leafletmapid_location-map']` populated? Looks like a custom reference, not something built-in Django Leaflet? – ghybs Jan 18 '22 at 19:21
  • @ghybs Django-leaflet populates it when it generates the map if you add `NO_GLOBALS = False` to the django-leaflet config. I can use it to access the map object inside an ajax call fired from a button click, but can't figure out how to use it to assign the map to a variable on page load. – kysevenle Jan 19 '22 at 20:18

0 Answers0