我正在尝试在基于MapBox的地图上放置来自GeoDjango模型的一些点。这是我第一次使用MapBox和here,我已经知道如何在MapBox的地图上添加GeoJson。
models.py
class AddPoint(models.Model):
geom = models.PointField()
def __int__(self):
return self.pk
def coordinates_geodjango(self):
return str(self.geom.x) + ', ' + str(self.geom.y)
map.html
mapboxgl.accessToken = 'my.access.token';
var map = new mapboxgl.Map({
container: 'map',
accessToken: mapboxgl.accessToken,
style: 'mapbox://styles/maxdragonheart/cjxkimp5j5s0o1ct4b68n4x1p',
minZoom: 2,
maxZoom: 22,
logoPosition: 'bottom-right',
center: [15,41],
zoom: 4,
})
map.on('load', function () {
map.addSource('some id', {
type: 'geojson',
data: {
"type": "FeatureCollection",
"features": [{% for point in geo_objects %}
{
"type": "Feature",
"properties": {
"pk": "{{ point.pk }}"
},
"geometry": {
"type": "Point",
"coordinates": [{{ point.coordinates_geodjango }}]
}
{% if forloop.last %}} {% else %}}, {% endif %}{% endfor %}
]
}
});
});
[当我看到页面源代码时,我可以看到要点列表:
map.addSource('some id', {
type: 'geojson',
data: {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"pk": "3"
},
"geometry": {
"type": "Point",
"coordinates": [15.996093749999993, 41.24477234308207]
}
},
{
"type": "Feature",
"properties": {
"pk": "2"
},
"geometry": {
"type": "Point",
"coordinates": [12.392578124999993, 43.13306116240612]
}
},
{
"type": "Feature",
"properties": {
"pk": "1"
},
"geometry": {
"type": "Point",
"coordinates": [14.348144531249998, 40.96330795307351]
}
}
]
}
});
问题是这些点没有显示在地图上,并且在Chrome控制台中没有错误。我错了吗?
您快到了。
您已设法将GeoJSON源添加到地图,但尚未从该源创建图层。
让我们关注this example并将其修改为我们当前的需求:
map.on('load', function () {
map.addSource('some-id', {
type: 'geojson',
data: {
"type": "FeatureCollection",
"features": [{% for point in geo_objects %}
{
"type": "Feature",
"properties": {
"pk": "{{ point.pk }}"
},
"geometry": {
"type": "Point",
"coordinates": [{{ point.coordinates_geodjango }}]
}
{% if forloop.last %}} {% else %}}, {% endif %}{% endfor %}
]
}
});
map.addLayer({
"id": "some-other-id",
"type": "fill",
"source": "some-id", // Here is the part where you add the source to a layer.
"paint": {
"fill-color": "#888888",
"fill-opacity": 0.4
}
});
});
[C0中显示了一种直接的方法:
this other example