我使用OpenLayers在地图上创建,显示和编辑功能。功能在Django中保存为JSONField。保存后我将一个密钥django_pk添加到JSON。如何直接从该功能获取此djanog_pk?
我需要这样做,所以当编辑该功能时,我知道要在Django中更新哪些功能。
我的JS代码如下:
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector({wrapX: false});
var vector = new ol.layer.Vector({
source: source
});
var format = new ol.format.GeoJSON();
var select = new ol.interaction.Select({
wrapX: false
});
var modify = new ol.interaction.Modify({
features: select.getFeatures()
});
var map = new ol.Map({
interactions: ol.interaction.defaults().extend([select, modify]),
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var features = new ol.source.Vector({
projection: 'EPSG:4326'
});
{% for polygon in polygons.0.gates %}
console.log(format.readFeature({{ polygon|safe }}).getProperties()))
{% endfor %}
features.addFeature(format.readFeature({{ polygons.0.protected_area|safe }}));
{% for polygon in polygons.0.gates %}
features.addFeature(format.readFeature({{ polygon|safe }}));
console.log(format.readFeature({{ polygon|safe }}))
{% endfor %}
var featureOverlay = new ol.layer.Vector({
source: features,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ff78d1',
width: 2
}),
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#4ca6b6'
}),
})
})
});
featureOverlay.setMap(map);
</script>
我试过这个:买它只返回几何:
select.on(&#39; select&#39;,function(e){ 的console.log(e.selected [0] .getProperties()) });
Django中的JSONField看起来像这样:
{
"geometry":{
"type":"Polygon",
"coordinates":[
[
[
-11156543.033928039,
6698655.0485978
],
[
-11410925.464061106,
5896371.999716589
],
[
-9972686.33984723,
5084305.011214877
],
[
-9512841.177683609,
6649735.350495286
],
[
-10090093.61529326,
6972605.357971871
],
[
-11156543.033928039,
6698655.0485978
]
]
]
},
"type":"Feature",
"properties":null,
"django_pk":10
}
所以我需要在编辑时找到django_pk,选择它,然后删除它。
不确定如何获取此信息
答案 0 :(得分:0)
好吧,我其实很简单。
您可以阅读GeoJSON格式的任何属性:
select.on('select', function(e) {
console.log(e.selected[0].getProperties())
});
选择存在:
var select = new ol.interaction.Select({
wrapX: false
});
在我的Django代码中,我只是在post_save上执行此操作:
@receiver(post_save, sender=ProtectedArea)
def update_json(sender, instance, created, **kwargs):
post_save.disconnect(update_json, sender=ProtectedArea)
try:
instance.polygone = literal_eval("%s" % instance.geojson_file.read())
except:
pass
if instance.polygone['properties'] == None:
instance.polygone['properties'] = {}
instance.polygone['properties']['pk'] = instance.pk
else:
instance.polygone['properties']['pk'] = instance.pk
instance.save()
post_save.connect(update_json, sender=ProtectedArea)