如何将Geodjango与Google Maps API 3集成? [英] How to integrate Geodjango with Google Maps API 3?

查看:223
本文介绍了如何将Geodjango与Google Maps API 3集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个geodjango queryset包含几个字段,但只想使用 user_name 位置(一个点字段)我想用它作为google地图API 3中的一个标记。



由于我不了解Javascript而担心,因此我有一系列问题。

以新手的概念头脑风暴为例:


  1. 我的SO搜索建议我需要序列化queryset将
    对象转换为JSON。我使用内置的串行器模块将其转换为JSON。

    我认为JSON对象被转换为 views.py (让我们
    称之为 json_data )。这些JSON对象是否存储在PostGIS数据库中?这不是多余的吗?

  2. 另外,如何在 map.js 中引用它们, (谷歌地图
    API 3)javascript文件?
    我想(导入?链接?)JSON对象将它们显示为位置标记。

  3. 我想知道如何声明和迭代JavaScript变量
    locations




For var(i = 0; i< locations.length; i ++){[
[json_data.user_name,json_data.point],
]

var map = new google.maps.Map(document.getElementById ('map'),{
center:new google.maps.LatLng(49.279504,-123.1162),
zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker,i;
for(i = 0; i< locations.length; i ++){
marker = new google.maps.Marker({
position:new google.maps.LatLng(locations [i ] [1],地点[i] [2]),
地图:地图,
图标:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png '
});
google.maps.event.addListener(marker,'click',(function(marker,i){
return function(){
infowindow.setContent(locations [i] [0] );
infowindow.open(map,marker);
}
})(marker,i));

$ / code>

如果我以不必要的复杂方式完成简单任务, p>

解决方案

TL; DR
$ b


  1. $ b
  2. 你需要做一个 getJSON()函数,

你在想什么是非常正确的,但是还有改进的空间(因此下面的答案很长)。
$


答案: 前段时间我读了使用geodjango和Google地图构建GIS应用程序的非常好的入门教程。阅读它后,它会给你一个很好的开始。



读完之后,我们将采用一种有点不同的方式,为您的前端留下更多空间(使用反应例如或任何想到的)。

后端:


  1. 创建一个视图来检索您想要的信息( user_name location )作为JSON,使用 values() queryset方法返回字典列表。

    由于我们必须对列表进行JSON化,因此我们将使用 JsonResponse ,我们将其标记为不安全:

      from django.http import JsonResponse 
    $ b $ def my_view(request):
    resp = MyModel.objects.all()。values('user_name','location')
    return JsonResponse(list(resp),safe = False)


  2. 访问 urls.py

      urlpatterns = [
    ...
    url(r'^ my_endpoint / $',my_view,name ='my_endpoint'),
    ...
    ]
    my_endpoint /
    时,我们都会得到每个对象的JSON表示。 $ b> code> user_name
    location 在我们的数据库中看起来像这样:

      [
    {user_name:a_user,locat ion:[lat,lng]},
    {user_name:another_user,location:[lat,lng]},
    ...
    ]

现在转到前端:


  1. 制作 getJSON()或者 ajax()或任何其他类型的API调用,并同时创建一个标记列表(接近@MoshFeu建议的内容):

      let map = new google.maps.Map(document.getElementById('map'),{
    center:new google.maps.LatLng(49.279504,-123.1162),
    zoom:14,
    mapTypeId:google.maps.MapTypeId.ROADMAP
    });

    让marker = [];

    $ .getJSON(my_base_url / my_endpoint,function(data){
    $ .each(data,function(){
    markers.push(
    new google.maps.Marker({
    position:{
    lat:data ['location'] [0],
    lng:data ['location'] [1]
    } ,
    map:map,
    icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
    })
    );
    });
    });
    ...


几乎完成了!



您不需要对数据进行任何特殊的序列化。

您可以从任何类型的前端你可以想象哪个给你设计自由。


I have a geodjango queryset containing several fields but want to use only user_name and location (a point field) which I want to use as a marker in google maps API 3.

Bear with me as I don’t know Javascript and I have a series of questions.
Take this as conceptual brainstorming for a novice:

  1. My SO search suggests that I need to serialize the queryset objects to JSON. I use the built-in serializer module to convert to JSON.
    I think the JSON objects are converted in views.py (let’s call it json_data). Are these JSON objects stored in the PostGIS database? Wouldn’t that be redundant?

  2. Furthermore, how do I reference them in the map.js (google maps API 3) javascript file?
    I want to (import?link?) JSON objects to display them as location markers.

  3. I want to know how to declare and iterate the javascript variable locations.

For var(i=0;i< locations.length;i++){[
[json_data.user_name, json_data.point],
]

var map = new google.maps.Map(document.getElementById('map'), {
  center: new google.maps.LatLng(49.279504, -123.1162),
  zoom: 14,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
  });
  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

Guide me if I went unnecessarily convoluted way to do a simple task.

解决方案

TL;DR

  1. No, what you are doing is not redundant and nothing get's written to the database from those answers.
  2. You need to make a getJSON() or similar call to your API's endpoint to access the data.
  3. You can do it on the 2nd step's call and declare it as a list.

What you are thinking is pretty much correct but there is room for improvement (thus the long answer below).


Answer:

Some time ago I read a very good initiation tutorial on building a GIS application with geodjango and google maps. Read it and it should give you a great jump start.

After you read that we will follow a somewhat different way which leaves more room to play around with your front-end (use react for example or whatever comes to mind).

The back-end:

  1. Create a view to retrieve the information you want (user_name, location) as JSON, using the values() queryset method which returns a list of dictionaries.
    Since we have to JSONify a list, we will use JsonResponse and we will mark it as unsafe:

    from django.http import JsonResponse
    
    def my_view(request):
        resp = MyModel.objects.all().values('user_name', 'location')
        return JsonResponse(list(resp), safe=False)
    

  2. Add an endpoint to access that view on urls.py:

    urlpatterns = [
        ...
        url(r'^my_endpoint/$', my_view, name='my_endpoint'),
        ...
    ]
    

    Now whenever we access the my_endpoint/ we will get a JSON representation of every object's user_name and location in our database which will look like this:

    [
      {user_name: a_user, location: [lat, lng]},
      {user_name: another_user, location: [lat, lng]},
      ...
    ]
    

Moving to the front-end now:

  1. Make a getJSON() or an ajax() or any other type of call to the API and in the same time create a marker list (close to what @MoshFeu suggests):

    let map = new google.maps.Map(document.getElementById('map'), {
        center: new google.maps.LatLng(49.279504, -123.1162),
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    
    let markers = [];
    
    $.getJSON( "my_base_url/my_endpoint", function(data) {
        $.each(data, function() {
            markers.push(
                new google.maps.Marker({
                    position: {
                        lat: data['location'][0], 
                        lng: data['location'][1]
                    },
                    map: map,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
                })     
            );
        });
    });
    ...
    

And we are pretty much done!

You don't need to make any special serialization to your data.
You can query the data from any type of front-end you can imagine which gives you designing freedom.

这篇关于如何将Geodjango与Google Maps API 3集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆