erdem / django-map-widgets

Highly customizable, intuitive, and user-friendly map widgets for GeoDjango applications.
MIT License
447 stars 119 forks source link

Help request: Create javascript event listener #152

Closed ShmuelTreiger closed 1 month ago

ShmuelTreiger commented 1 month ago

Hi! I'm trying to create an event listener for the djange-map-widget. I've tried the following ways, none of which as worked:

            document.getElementById("id_address_point").addEventListener("change", updateFakePoint);
            document.getElementById("id_address_point").addEventListener("leafletPointFieldWidget:markerChange", updateFakePoint);

            (function ($) {
                $(document).on("leafletPointFieldWidget:markerChange", updateFakePoint);
            })(jQuery)

I also tried just

        (function ($) {
            $(document).on("leafletPointFieldWidget:markerChange", function (e, lat, lng, locationInputElem, mapWrapID) {
                console.log(locationInputElem); // Django widget textarea widget (hidden)
                console.log(lat, lng);  // Changed marker coordinates
                console.log(mapWrapID); // Map widget wrapper element ID
            });
        })(jQuery)

And nothing prints to console.

In my head I have: <script src="https://code.jquery.com/jquery-3.7.1.slim.min.js"></script>

When I update id_address_point, updateFakePoint doesn't trigger. Would appreciate recommendation on how I can do this correctly. Thank you!

erdem commented 1 month ago

Hi @ShmuelTreiger

Unfortunately, those event triggers are not available for the Leaflet interactive widget. It was my copy-paste mistake that added the wrong info to the widget documentation. I have just pushed a commit to main to update the widget documentation.

However, you can catch those events with Leaflet instance map objects which are bound to the map HTML element data here.

// HTML element given by id string formatting, "<field_name>-map-elem". My demo model field name is `location`.

(function ($) {
    $("#location-map-elem").data("mwMapObj"); // Leaflet map object
    $("#location-map-elem").data("mwClassObj"); // jQuery class implementation object
})(jQuery);

Feel free to open a pull request to fix this; otherwise, I will add this feature to the next release. Thanks for the notice.

ShmuelTreiger commented 1 month ago

Sorry, I'm not terribly familiar with jQuery. Do you have any idea why this isn't working?

            $('#address-point-map-elem').change(function () {
                <function>;
            });

I also tried address_point-map-elem and id_address_point.

erdem commented 1 month ago

This is not what I meant, get to know how you can use jquery data in your cases.