如何在django-leaflet中将事件添加到LeafletWidget? [英] How to add event to LeafletWidget in django-leaflet?

查看:40
本文介绍了如何在django-leaflet中将事件添加到LeafletWidget?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django应用中,我有一个带有名称和位置(点)的Worker模型.使用django-leflet LeafletWidget,我可以创建一个Form,用户可以在其中设置位置(该工作人员的标记).是否可以向小部件添加事件,因此,每当用户设置标记或更改标记位置时,它都会获取该点的坐标并执行其他操作(例如ajax请求)?

In my django app I have a Worker model with a name and location (Point). Using django-leflet LeafletWidget I can create a Form where the user can set a location (marker to that worker). Is it possible to add an event to the widget, so, every time the user sets the marker, or change the marker position it gets the coordinates of that point and perform other actions (like an ajax request)?

class WorkerForm(forms.ModelForm):
    
    class Meta:
        model = WorkerModel
        exclude = ("id",)
        widgets = {
            'name':forms.TextInput(attrs={'class': 'form-control'}),
            'location': LeafletWidget(),
}

在我刚才调用的模板中"forms.location"并使用控件设置标记来渲染地图

in the template i just call 'forms.location' and it renders the map with the controls to set a marker

每次用户设置标记时,我都要获取该标记的位置.我该怎么做?

Every time the user sets the marker I want to get the location of that marker. How do I do that?

推荐答案

首先,您应该在表单中添加其他JavaScript文件,以便在其中捕获事件并随心所欲地进行操作.为此,将一个类媒体添加到表单中并指示JS在其中的位置:

First you should add an additional JavaScript file to the form, where you can capture the event and do whatever you like with it. To do so, add a class media to the form and indicate the location of the JS inside:

class WorkerForm(forms.ModelForm):

    ...

    class Media:
        js = ('path/to/script.js',)

在应用程序静态目录内的path/to目录中创建script.js文件.在该script.js上,添加以下代码:

Create the script.js file on the path/to directory inside your static directory of your app. On that script.js, add the following code:

// Wait for the map to be initialized
$(window).on('map:init', function(e) {
    // Get the Leaflet map instance
    map = e.originalEvent.detail.map;
    // Capture the creation of a new feature
    map.on('draw:created', function (e) {
        const coordinates = e.layer._latlng;
        // Your stuff
    });
    map.on('draw:edited', function (e) {
        var layers = e.layers;
        layers.eachLayer(function (layer) {
            const coordinates = layer._latlng;
            // your other stuff
        });
    });

检查传单绘制文档查看所有可用事件.

Check the Leaflet Draw documentation to see all the events available.

这篇关于如何在django-leaflet中将事件添加到LeafletWidget?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆