You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Maps与Django集成:监听地图拖拽事件重新筛选周边店铺

实现方案

整体分为前端Google Maps事件监听、后端接口适配两部分:

前端Google Maps侧实现

  • 给地图绑定dragend事件(拖拽结束后触发,相比实时监听中心点变更可减少无效请求),事件触发后获取新的地图中心点经纬度
  • 携带新坐标发起AJAX请求到Django后端,获取筛选后的店铺数据
  • 清空地图原有标记,重新渲染新的店铺标记,同时更新页面店铺列表

示例JS代码:

// 全局变量存储所有标记点,用于清空
let markers = [];
// 假设你的地图实例变量为map
map.addListener('dragend', function() {
  // 获取新的中心点坐标
  const newCenter = map.getCenter();
  const lat = newCenter.lat();
  const lng = newCenter.lng();

  // 发起请求获取新的店铺数据
  fetch('/filter-shops/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': getCookie('csrftoken') // 替换为你自己获取CSRF Token的逻辑
    },
    body: JSON.stringify({lat: lat, lng: lng})
  })
  .then(res => res.json())
  .then(data => {
    // 清空旧标记
    clearOldMarkers();
    // 渲染新标记
    data.shops.forEach(shop => {
      const marker = new google.maps.Marker({
        position: {lat: shop.lat, lng: shop.lng},
        map: map,
        title: shop.name
      });
      markers.push(marker);
      // 原有标记点击弹窗等逻辑可在这里复用
    });
    // 更新页面上的店铺列表DOM
    renderShopList(data.shops);
  })
});

// 清空旧标记工具函数
function clearOldMarkers() {
  markers.forEach(marker => marker.setMap(null));
  markers = [];
}

// 获取CSRF Token的工具函数,适配Django校验
function getCookie(name) {
  let cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

优化提示:可以给dragend事件加300ms防抖,避免用户连续拖拽时频繁发起请求,降低服务器压力。

Django后端侧适配

你已经实现了坐标筛选逻辑,只需要新增一个接受POST请求的接口,返回JSON格式的店铺数据即可:

示例视图代码:

from django.http import JsonResponse
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
from .models import Shop
import json

def filter_shops(request):
    if request.method != "POST":
        return JsonResponse({"code": 400, "msg": "请求方法错误"}, status=400)
    
    # 解析前端传的坐标
    req_data = json.loads(request.body)
    lat = req_data.get("lat")
    lng = req_data.get("lng")
    if not lat or not lng:
        return JsonResponse({"code": 400, "msg": "坐标参数缺失"}, status=400)
    
    # 构造中心点坐标,注意Point参数顺序是(经度, 纬度)
    center_point = Point(float(lng), float(lat), srid=4326)
    # 筛选5公里范围内的店铺,可根据需求调整距离或改为前端传参
    nearby_shops = Shop.objects.filter(
        location__distance_lte=(center_point, D(km=5))
    ).values("name", "address", "city", "location")

    # 格式化返回数据
    res_data = []
    for shop in nearby_shops:
        res_data.append({
            "name": shop["name"],
            "address": shop["address"],
            "city": shop["city"],
            "lat": shop["location"].y,
            "lng": shop["location"].x
        })
    
    return JsonResponse({"code": 200, "shops": res_data})
  • 最后在urls.py中添加对应路由,路径和前端请求的路径保持一致即可。

内容的提问来源于stack exchange,提问作者Mohamed Ibrahim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 19:15:00