我正在使用Django,并且在index.html中设置了这样的地图:
<div id="map"></div>
<script>
var map;
function initMap(){
map = new google.maps.Map(document.getElementById('map'),{
center: {lat: {{clat}}, lng: {{clng}}},
zoom:12
});
}
</script>
<script src={{gmap_url}} async def></script>
首先,我想使用数据库中适合显示区域的标记来启动地图。然后为用户添加更改显示区域(拖动或缩放)的功能,然后按一个按钮,该按钮将根据地图的新显示区域查询我的数据库。如何知道我的地图当前显示的区域?
当用户使用存储在标记中的信息单击标记时,我还想查询数据库,如何将信息传递给onclick视图?
答案 0 :(得分:0)
您可以从地图上获取边界框,然后将该数据作为GET请求中的查询参数发送到django服务器,然后django服务器可以对该边界框中的数据执行空间查询并将数据发送回您的地图。看起来像这样。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src={{gmap_url}}></script>
<script src={{axios_url}}></script>
<script src={{js-cookie_url}}></script>
</head>
<button onclick="sendBounds()">Click me to send bounds!</button>
<div id="map"></div>
</html>
<script>
var map
const postRequest = axios.create({
baseURL: '/api',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': Cookies.get('csrftoken')
}
})
function initMap() {
map = new google.maps.Map(document.getElementById('map'),{
center: {lat: {{clat}}, lng: {{clng}}},
zoom:12
})
}
function sendBounds() {
const payload = { 'bounds': map.getBounds() }
postRequest.get(`models/`, { params: payload })
.then(response => response.data.results)
}
</script>
views.py
from django.contrib.gis.geos import Polygon
from rest_framework import generics
from .models import Model
from .serializers import ModelSerializer
class ModelAPIView(generics.ListAPIView):
lookup_field = 'pk'
serializer_class = ModelSerializer
def get_queryset(self):
bounds = self.request.GET.get('bounds')
# Probably need to cast all these string coordinates to floats here
geom = Polygon.from_bbox(bounds)
queryset = Model.objects.filter(poly__contained=geom)
return queryset
def get_serializer_context(self, *args, **kwargs):
return {'request': self.request}
urls.py
from django.urls import path
from .views import ModelAPIView
urlpatterns = [
path('api/models/', ModelAPIView.as_view(), name='model-list'),
]