GeoDjango - 如何将GMap标记的坐标保存到模型中

时间:2016-06-16 09:45:58

标签: django google-maps gis postgis geodjango

models.py:

class Location(models.Model):
    name = models.CharField(max_length=100, verbose_name=u"Location", default=u'')
    coords = gis_models.PointField(u"lng/lat", srid=4326, blank=True, null=True)

views.py:

class AddLocationPageView(CreateView):
    model = Location
    form_class = LocationForm
    template_name = 'add_location.html'

forms.py:

class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        fields = ['name']       # there is no 'coords'

add_location.html:

<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}

            <div id="map-add-location" ></div>       # place for GMap

            <div>
                {{ form.as_p }}
                <button type="submit">Add</button>
            </div>
</form>

JS:

$(document).ready(function(){
    var mapOptions = ...
    map = new google.maps.Map($('#map-add-location')[0], mapOptions);

    map.addListener('click', function(e){
            placeMarker(e.latLng, map);
            var position = marker.getPosition();
            var lat_input = $('<input type="hidden" name="lat"/>');
            var lng_input = $('<input type="hidden" name="lng"/>');
            $(lat_input).insertBefore($('#id_name'));
            $(lng_input).insertBefore($('#id_name'));
            $(lat_input).val(position.lat());
            $(lng_input).val(position.lng());
    });

    var marker;
    function placeMarker(latLng, map) {
        marker = new google.maps.Marker({
            position: latLng,
            map: map,
        });
        return marker
    }

});

我很困惑。我不明白我应该做些什么。 请帮助..如何在位置模型的'coords'字段中保存lat和lng值?

感谢!!!

0 个答案:

没有答案