0

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

Ernesto Ruiz
  • 736
  • 9
  • 31
  • 1
    Does this answer your question? [How to add event to LeafletWidget in django-leaflet?](https://stackoverflow.com/questions/67729002/how-to-add-event-to-leafletwidget-in-django-leaflet) – Marc Compte May 27 '21 at 23:38
  • I found a solution in the following post: https://stackoverflow.com/questions/67729002/how-to-add-event-to-leafletwidget-in-django-leaflet/67731081?noredirect=1#comment119721170_67731081 – Ernesto Ruiz Jun 07 '21 at 13:07

2 Answers2

0

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');
            }
        });
    }
});
Ernesto Ruiz
  • 736
  • 9
  • 31
-1

The Leaflet quick start guide has a section about dealing with events https://leafletjs.com/examples/quick-start/ There you can see an example of adding a popup when clicking on the map:

var popup = L.popup();

function onMapClick(e) {
    popup
        .setLatLng(e.latlng)
        .setContent("You clicked the map at " + e.latlng.toString())
        .openOn(mymap);
}

mymap.on('click', onMapClick);

We need to modify this function to add a marker instead:

var marker = L.marker();

function onMapClick(e) {
    marker
        .setLatLng(e.latlng)
        .addTo(mymap);
}

mymap.on('click', onMapClick);
lucutzu33
  • 3,470
  • 1
  • 10
  • 24
  • He used the tags django and django-leaflet. His question is about how to do this within Django. – Marc Compte May 27 '21 at 23:41
  • From django leaflet docs: "You can use the Leaflet API as usual". How about you tell him how to do it in django instead. – lucutzu33 May 28 '21 at 06:01
  • 1
    I already did https://stackoverflow.com/questions/67729002/how-to-add-event-to-leafletwidget-in-django-leaflet/67731081?noredirect=1#comment119721170_67731081 – Marc Compte May 28 '21 at 12:33