我想用传单创建一个地图,并让用户有机会从用户界面向该地图添加一个标记。用户应该标记一个点(市场到地图)。然后,当设置点时,我想获取该标记的位置(坐标)并执行其他操作。它应该只允许一个标记
问问题
312 次
2 回答
0
为此,我必须为位置字段(点)定义一个 LeafletWidget,并使用 mesa 类向表单添加一些 javascript
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');
}
});
}
});
于 2021-06-08T18:23:04.680 回答
-1
Leaflet 快速入门指南有一个关于处理事件的部分https://leafletjs.com/examples/quick-start/ 在那里您可以看到单击地图时添加弹出窗口的示例:
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);
我们需要修改这个函数来添加一个标记:
var marker = L.marker();
function onMapClick(e) {
marker
.setLatLng(e.latlng)
.addTo(mymap);
}
mymap.on('click', onMapClick);
于 2021-05-27T20:59:45.080 回答