makinacorpus / django-leaflet

Use Leaflet in your Django projects
GNU Lesser General Public License v3.0
716 stars 282 forks source link

Cannot get reference to map loaded in admin pages. #347

Open kysevenle opened 2 years ago

kysevenle commented 2 years ago

I'm trying to manipulate the admin map after it is loaded however I cannot get a reference to the map. I've set NO_GLOBAL to false, and my template to override the admin template is as follows.

Template:

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

{% block content %}{{ block.super }}
<script>
    map = window['leafletmapid_location-map'];
    console.log(map);
</script>
{% endblock %}

This logs "undefined", but if I load the page, open the console, and run the exact same code I get a reference to the map, and can then add markers as needed. Am I going about this the wrong way? Should I be able to get a reference to the map this way?

I've tried placing the script tag into the admin_change_form_document_ready block.

I've also tried the following with the same results.

<script>
    $(document).ready(function() {
        console.log(window['leafletmapid_location-map']);
    });
</script>

Edit: It appears the issue is that the map is not initialized by the time var map = window['leafletmapid_location-map']; runs. If I run it in an event listener after a button click it works, but it is in the scope of the listener function.

I cannot find anyway to get a reference to the admin map in the global scope of my template. Is there anyway to accomplish this?

Gagaro commented 2 years ago

The map is probably not initialized yet. Try overwriting the callback block in leafet/admin/widget.html, you should have the map variable there.