tames
tames

Reputation: 19

Django - How can I pass information from my google map to my view?

I am using Django and I have my map set up like this in my 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>

First I want to initiate the map with markers from my database which fit within the shown area. Then add the ability for the user to change the shown area (drag or zoom) and press a button which will query my database based on the newly shown area of the map. How can I tell what area my map is currently showing?

I'd also like to query my database when the user clicks on a marker using information stored in that marker, how can I pass information to my view onclick?

Upvotes: 1

Views: 848

Answers (1)

pistolpete
pistolpete

Reputation: 998

You can get the bounding box from the map and then send that data as a query parameter in a GET request to your django server, which can then perform a spatial query on your data in that bounding box and send data back to your map. It would look something like this.

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'),
]

Upvotes: 1

Related Questions