1

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

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

在模板中,我只调用“forms.location”,它使用控件呈现地图以设置标记

这就是我得到的

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

4

1 回答 1

1

首先,您应该在表单中添加一个额外的 JavaScript 文件,您可以在其中捕获事件并使用它做任何您喜欢的事情。为此,在表单中添加一个类媒体,并在里面指明 JS 的位置:

class WorkerForm(forms.ModelForm):

    ...

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

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

// 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
        var coordinates;
        Object.keys(layers).forEach(function(key) {
            coordinates = layers[key]._latlng;
        });
        // Your stuff
    });
});

查看Leaflet Draw 文档以查看所有可用的事件。

于 2021-05-27T23:27:49.030 回答