【发布时间】:2020-10-28 11:33:47
【问题描述】:
在我自己尝试了 2 天后,我需要一些帮助
我正在使用 GeoDjango 和 Leaflet。我有一个模型“列表”,其中有一个字段 location 作为 PointField,我的表单使用 LeafletWidget,如下所示。 实际上,它正在工作,但是当我创建一个新列表时,location 中没有任何内容,因此它显示了默认的世界地图。 我想在我的模板中设置以下内容:
中心:({{ user.lat }}, {{ user.lng }}) 和缩放:10
因为我知道新列表将与用户位于同一地理区域。 而且我不知道该怎么做!!!
Model.py
location = models.PointField(null=True, blank=True)
forms.py
from leaflet.forms.fields import PointField
from leaflet.forms.widgets import LeafletWidget
...
LEAFLET_WIDGET_ATTRS = {
'map_height': '600px',
'map_width': '50%',
'display_raw': 'true',
'map_srid': 4326,
}
...
class ListingForm(forms.ModelForm):
required_css_class = 'required'
...
location = forms.PointField(
widget=LeafletWidget(attrs=LEAFLET_WIDGET_ATTRS))
...
template.html
<!-- form start -->
<form action="{% url 'listing_new' %}" method="POST" class="listing-form" role="form" novalidate enctype="multipart/form-data" id="listingform">
{% csrf_token %}
<div class="box-body">
{{ form.non_field_errors }}
{% for field in listingform %}
<div class="fieldWrapper form-group {% if field.errors %} field_error{% endif %} ">
<label for="{{ field.id_for_label }}">
{{ field.label }}{% if field.field.required %}<span class="required-asterisk">*</span>{% endif %}
</label>
{{ field }}
{% for error in field.errors %}
<span class="help-block">{{ error }}</span>
{% endfor %}
</div>
{% endfor %}
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary" form="listingform">Submit</button>
</div>
</form>
我尝试使用以下内容:
<script type="text/javascript">
window.addEventListener("map:init", function (e) {
var detail = e.detail;
detail.options.djoptions['center']=[{{ listing_lat }}, {{ listing_lng }}];
detail.options.djoptions['zoom']=10;
console.log(detail.options);
console.log(detail.loadmap);
}, false);
</script>
但它不会修改传单小部件自动生成的代码:
<div id="id_location-map" class="leaflet-container-default"></div>
<script type="text/javascript">
(function () {
function loadmap() {
var djoptions = {"srid": null, "extent": [[-90, -180], [90, 180]], "fitextent": true, "center": null, "zoom": null, "minzoom": null, "maxzoom": null, "layers": [["OSM", "//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", "\u00a9 <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"]], "overlays": [], "attributionprefix": null, "scale": "metric", "minimap": false, "resetview": true, "tilesextent": []},
options = {djoptions: djoptions, initfunc: loadmap,
globals: false, callback: id_location_map_callback},
map = L.Map.djangoMap('id_location-map', options);
}
var loadevents = ["load"];
if (loadevents.length === 0) loadmap();
else if (window.addEventListener) for (var i=0; i<loadevents.length; i++) window.addEventListener(loadevents[i], loadmap, false);
else if (window.jQuery) jQuery(window).on(loadevents.join(' '), loadmap);
})();
</script>
【问题讨论】: