How to center a Leaflet Map forms in a Django template

问题描述 投票:0回答:4

在尝试自己完成 2 天后,我需要一些帮助

我正在使用 GeoDjango 和 Leaflet。我有一个模型“列表”,它有一个字段 location 作为 PointField,我的表单使用 LeafletWidget,如下所示。 事实上,它正在运行,但是当我创建一个新列表时,location 中没有任何内容,因此它显示默认的世界地图。 我想在我的模板中设置以下内容:

CENTER:({{ user.lat }},{{ user.lng }})和缩放:10

因为我知道新列表将与用户位于同一地理区域。 而且我不知道该怎么做!

模型.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>
django leaflet geodjango
4个回答
2
投票

所以,解决办法就是在模板中加入这段JS:

<script type="text/javascript">
    window.addEventListener("map:init", function (e) {
        var detail = e.detail;
        detail.map.setView([{{user_lat}},{{user_lng}}], 10);
    }, false);

</script>

0
投票

在简单的 JS 中,您可以将其设置为:

map.setView([{{ user.lat }}, {{ user.lng }}], 10);

但是使用 GeoDjango,您可以尝试:

LEAFLET_WIDGET_ATTRS = {
    'map_height': '600px',
    'map_width': '50%',
    'display_raw': 'true',
    'map_srid': 4326,
}

LEAFLET_CONFIG {
    'DEFAULT_CENTER': ({{ user.lat }}, {{ user.lng }}),
    'DEFAULT_ZOOM': 10,
}

查看此文档:https://buildmedia.readthedocs.org/media/pdf/django-leaflet/latest/django-leaflet.pdf


0
投票

在你的 Django.settings 文件中添加这些行:

LEAFLET_CONFIG = { 'DEFAULT_CENTER': (41.25 ,20), # Latitude ,  Longitude 
'DEFAULT_ZOOM': 8,
'MAX_ZOOM': 28,
'MIN_ZOOM': 1,
'SCALE':'both',
'TILES': [], }

0
投票

如 django-leaflet 文档

可以动态覆盖

LeafletWidget
init中的设置:

from leaflet.forms.widgets import LeafletWidget


class WeatherStationForm(forms.ModelForm):

    class Meta:
        model = WeatherStation
        fields = ('name', 'geom')
        widgets = {'geom': LeafletWidget(attrs={
            'settings_overrides': {
                'DEFAULT_CENTER': (6.0, 45.0),
            }
        })}

要覆盖

LeafletGeoAdmin
中的设置,请使用设置适当的属性:

class WeatherStationAdminAdmin(LeafletGeoAdmin):
    settings_overrides = {
       'DEFAULT_CENTER': (6.0, 45.0),
    }
© www.soinside.com 2019 - 2024. All rights reserved.