Search code examples
djangoleafletdjango-leaflet

How to add ''draw a marker" Control to leaflet Map and capture event?


I want to create a map with leaflet and give the user the opportunity to add a marker to that map from the user interface. The user shuld mark a point(market to th map). Then when the point is set I want to get the location (coordinates) of that marker and perform other operations. It should allow only one marker

I want this result enter image description here


Solution

  • For doing this I had to define a LeafletWidget for the location field (Point) and adding some javascript to the form using the mesa class

     class WorkerForm(forms.ModelForm):
        
            class Meta:
                model = WorkerModel
                exclude = ("id",)
                widgets = {
                    'name':forms.TextInput(attrs={'class': 'form-control'}),
                    
                    'location': LeafletWidget(),
                    'last_name1' : forms.TextInput(attrs={'class': 'form-control'}),
                    'last_name2' : forms.TextInput(attrs={'class': 'form-control'}),
                    'identification':forms.TextInput(attrs={'class': 'form-control'}),
                    'birthday_date' :forms.DateInput(attrs={'class': 'form-control datepicker', 'autocomplete': 'off'}),
                    'address'       : forms.TextInput(attrs={'class': 'form-control'}),
                    'municipality_id' : ModelSelect2Widget(model=MunicipalityModel, queryset=MunicipalityModel.objects.filter(),
                                                    search_fields=['municipio__icontains'],
                                                    dependent_fields={'province_id': 'cod_prov'},
                                                    attrs={'style': 'width: 100%;'}),
                    'province_id' : ModelSelect2Widget(model=ProvinceModel, queryset=ProvinceModel.objects.filter(),
                                                    search_fields=['des_prov__icontains'],
                                                    attrs={'style': 'width: 100%;'}),
                   
                    }
            class Media:
                js = ('form_media/worker_form.js',)
    

    worker_form.js

    // Wait for the map to be initialized
    $(window).on('map:init', function(e) {
    
        map = e.originalEvent.detail.map;
      
        map.on('draw:created', function (e) {
            const coordinates = e.layer._latlng;
            
            call_ajax(coordinates);
    
        });
        map.on('draw:edited', function (e) {
            var layers =e.layers._layers
            var coordinates;
            Object.keys(layers).forEach(function(key) {
    
                coordinates = layers[key]._latlng;
                //console.log(coordinates)
            });
            call_ajax(coordinates);
        });
    
        function call_ajax(coordinates)
        {
    
            $.ajax({
                type: "GET",
                url: "/riesgo/trabajador/provincia_municipio/ajax/",
                data: {
                    'lat': coordinates.lat,
                     'lng': coordinates.lng,
                },
                dataType: "json",
                success: function (response) {
    
                    $('#id_province_id').val(response.province_id); // Select the option with a value of '1'
                    $('#id_province_id').trigger('change'); // Notify any JS components that the value changed
                },
                error: function (rs, e) {
                    console.log('ERROR obteniendo el bounding box');
                }
            });
        }
    });