【问题标题】:fetch data from django and place on google maps using javascript从 django 获取数据并使用 javascript 放置在谷歌地图上
【发布时间】:2026-01-14 18:50:02
【问题描述】:

我需要从 django 后端获取数据,并在用户当前位置 1 公里半径内的谷歌地图上放置标记。我如何在没有 api 密钥的情况下使用 google maps api 根据 django 提供的信息放置标记

【问题讨论】:

    标签: javascript html css django google-maps


    【解决方案1】:

    假设你有一个类似的模型

    class Point(models.Model):
        name = models.CharField(max_length = 32)
        lon = models.FloatField()
        lat = models.FloatField()
    

    和类似的视图

    def find_points(request):
        from haversine import haversine
        points = []
        all_points = Point.objects.all()
        result_list = []
        your_location = (YOUR_LATITUDE,YOUR_LONGITUDE)
        for point in all_points:
            point_loc = (point.lat,point.lon)
            if(haversine(you,point_loc)<1):
                #print point
                result_list.append(point)
        custom_list = [rec.id for rec in result_list]
        points = Point.objects.filter(id__in=custom_list)
        return render(request,"points.html",{'points':points})
    

    并像写points.html一样

    {% extends "base.html" %}
    {% block content %}
    <style>
      html, body, #map-canvas {
        height: 80%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&    signed_in=true"></script>
    <script>
    // This example adds a marker to indicate the position
    // of Bondi Beach in Sydney, Australia
    function initialize() {
        var marker;
        var map;
        var mapOptions = {
            zoom: 16,
            center: new google.maps.LatLng({{latitude}},{{longitude}})
        }
        map = new google.maps.Map(document.getElementById('map-canvas'),
                                    mapOptions);
    
      //var image = '/static/checkmark.png';
    
      {% for point in points %}
        //console.log({{ point.lat }}, {{ point.lon }});
        var myLatLng = new google.maps.LatLng({{ point.lat }}, {{ point.lon }});
    
        marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: '{{ point.name }}',
            url: '/{{point.id}}',
        });
        google.maps.event.addListener(marker, 'click', function() {
            console.log("here");
            window.location.href = this.url;
        });
      {% endfor %}
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
    
    </script>
    <div id="map-canvas"></div>
    <div id="map_wrapper">
        <div id="map_canvas" class="mapping"></div>
    </div>
    <div id="map_wrapper">
        <div id="map-canvas" class="mapping"></div>
    </div>
    <script type="text/javascript">
    
    var x = document.getElementById("demo");
    
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
            } else { 
                x.innerHTML = "Geolocation is not supported by this browser.";
            }
        }
    
        function showPosition(position) {
            document.getElementById('latitude').value =  position.coords.latitude ;
            document.getElementById('longitude').value =  position.coords.longitude ;
            x.innerHTML = "Latitude: " + position.coords.latitude + 
            "<br>Longitude: " + position.coords.longitude;  
        }
    </script>
    
    {% endblock %}
    

    【讨论】:

      【解决方案2】:

      我已经尝试过了,但由于我在提供 haversine equation 的数据中有一些 str 数据类型,所以我遇到了麻烦。

      这是一个工作示例的快照,该示例循环haversine 方程并获取指定区域(公里)内的所有值。

      if form.is_valid():
          lat = form.cleaned_data.get('lat')
          lng = form.cleaned_data.get('lng')
          points = []
          all_points = business_filter.qs
          result_list = []
          selected_location = (lat, lng)
      
          for point in all_points:
              if isinstance(point.latitude, str) == True:
                  break
              elif isinstance(point.longitude, str) == True:
                  break
      
              points = (point.latitude, point.longitude)
      
              from haversine import haversine, Unit
              result = haversine(selected_location, points)
              if result < 5: ```# check for distance in km```
                  result_list.append(point.id)
              
          business_filter = all_points.filter(id__in=result_list).all()        
          filter_count = business_filter.count()
      

      【讨论】:

        最近更新 更多