简体   繁体   English

在Ajax成功使用Django之后创建一个新的Google Maps

[英]Create a new Google Maps after Ajax success with Django

I have made a Google Maps with dive location in the Netherlands. 我在荷兰的潜水地点制作了Google地图。 The next step is that an user can search on the page for a dive location and that the search results are showing on the Google Maps. 下一步是,用户可以在页面上搜索潜水地点,并且搜索结果将显示在Google地图上。 So it must replace the exisitng map. 因此,它必须替换现有地图。

I'm a new to Django and never worked with Javascript before. 我是Django的新手,之前从未使用Javascript。 The problem is that I don't know how to make a new map with dive locations that are getting back from the search result. 问题是我不知道如何使用从搜索结果中获取的潜水位置来制作新地图。

Urls.py Urls.py

from django.conf.urls import url
from . import views

app_name = 'kaart'

urlpatterns = [
    # /gis
    url(r'^$', views.index, name='index'),

    # Voor ajax zoekfunctie
    url(r'^search/$', views.search_duik_locaties, name='search_duik_locaties'),

    # /gis/id_number/
    url(r'^(?P<duik_id>[0-9]+)/$', views.detail, name='detail'),

]

views.py views.py

from django.shortcuts import render, get_object_or_404
from .models import Duikplaats


def index(request):
    all_duik_locaties = Duikplaats.objects.all()
    longitude = Duikplaats.objects.values('longitude')
    latitude = Duikplaats.objects.values('latitude')


    content = {
        'all_duik_locaties': all_duik_locaties,
        'longitude': longitude,
        'latitude': latitude,
    }
    return render(request, 'kaart/index.html', content)


def detail(request, duik_id):
    duikplaats = get_object_or_404(Duikplaats, pk=duik_id)
    return render(request, 'kaart/details.html', {'duikplaats': duikplaats})


def search_duik_locaties(request):
    query = request.GET.get('q')

    if query is not None and query != '' and request.is_ajax():
        zoek_duik_locaties = Duikplaats.objects.filter(duik_locatie__icontains=query)
        lat = zoek_duik_locaties.values('latitude')

        con = {
            'zoek_duik_locaties': zoek_duik_locaties,
            'lat': lat
        }

        return render(request, 'kaart/ajax_search.html', con)
    return render(request, 'kaart/ajax_search.html')

index.html (part of the Ajxax Call) index.html(Ajxax调用的一部分)

    $('#search').keyup(function (event) {
      var query =($('#search').val());


          if (query != '' || query != ' ') {
            $.ajax({
               type: 'GET',
               url: '/gis/search',
               data: {
                 'csrfmiddlewaretoken': '{{ csrf_token }}',
                 'q': query
               },
{#                dataType: 'json',#}
               success: function(data) {
                  $('#search-results').html(data);
                  for (var i=0; i <markers.length; i++) {
                      markers[i].setMap(null);

                  }
                  markers = [];


               },
               error: function(data) {
                  console.log(data);
               }
             });
          }
        });

ajax_search.html ajax_search.html

<ul id="results">
    {% for locatie in zoek_duik_locaties %}
        <li><a href="/gis/{{ locatie.id }}">{{ locatie.duik_locatie }}</a> </li>
        <p>{{ lat }}</p>
    {% endfor %}


</ul>

I want that the map will update with the new markers. 我希望地图将使用新标记进行更新。 So that an user can see on the map where the dive location is where he searched for. 这样用户就可以在地图上看到他搜索的潜水地点。

I got now a list of the dive location when the user search and the existing markers are gone but I don't get it done that the markers will update. 现在,当用户搜索和现有标记消失时,我得到了潜水位置的列表,但我做不完,标记将更新。

I ran into the same problem, please let me share you the code for adding a marker via AJAX. 我遇到了同样的问题,请让我分享通过AJAX添加标记的代码。

The following code updates via AJAX markers of interest depending of the user current location. 以下代码根据用户当前位置通过感兴趣的AJAX标记进行更新。

var map = new google.maps.Map(document.getElementById('map'),
var pos = {lat: position.coords.latitude,lng: position.coords.longitude};    
function updatePosition()
    $.ajax({
    url: '/ajax/geo/',
    type: 'POST',
    data: {
      'csrfmiddlewaretoken': '{{ csrf_token }}',
      'pos': pos
    },
    dataType: 'json',
    success: function (outcome) {
        var locations = outcome;
        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                icon : 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
                position: new google.maps.LatLng(locations[i].Latitud, locations[i].Longitud),
                map: map
            });

The views of ajax/geo looks the following: ajax / geo的视图如下所示:

def ajaxGeo(request):
  data = request.POST
  lati = data.get('pos[lat]','')
  longi = data.get('pos[lng]','')
  # EDIT: Only for prototyping
  model = Locacion.objects.filter(Latitud__lte=float(lati)+0.001)
  model = model.filter(Latitud__gte=float(lati)-0.001)
  model = model.filter(Longitud__lte=float(longi)+0.001)
  model = model.filter(Longitud__gte=float(longi)-0.001)
  outcome =[]
  for m in model:
    outcome.append(model_to_dict(m))
  return JsonResponse(outcome, safe=False)

For what I am seeing from your code you are entirely missing your view from where the AJAX get its response. 对于我从您的代码中看到的内容,您完全错过了AJAX获得响应的视图。 And you will need as well to modify your function to add markers. 而且,您还需要修改功能以添加标记。

Note: If you want an entirely new map for prototyping I would best be suited to reload the web page, only afterwards optimize your API quota usage and UX. 注意:如果您想要一个全新的原型图,我将最适合重新加载网页,只有在此之后优化您的API配额使用量和UX。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM