[英]Get coordinates from Point Django
I use class with PointField to store coordinates in database.我使用 PointField 类在数据库中存储坐标。
# models.py
from django.contrib.gis.db import models
class MapPoint(models.Model):
p = models.PointField()
def __str__(self):
return self.p
Coordinates I get from template using AJAX.我使用 AJAX 从模板获得的坐标。
# views.py
def mapper(request):
if request.method == "GET":
if request.is_ajax():
lat = float(request.GET.get('lat'))
lng = float(request.GET.get('lng'))
pnt = Point(lat, lng)
MapPoint.objects.create(p=pnt)
return render(request, 'map_in.html')
Then I want to show all points in other template然后我想显示其他模板中的所有点
# views.py
def mapper_done(request):
query = MapPoint.objects.all().values()
out_list = list(query)
return render(request, 'map_out.html', {'out_list': out_list})
It returns:它返回:
{'id': 1, 'p': <Point object at 0x7f42c712b670>}
How can I get coordinates from Point?如何从 Point 获取坐标? I want something like this:我想要这样的东西:
ID: 1, lat: 42.326565 lng: 52.325874
As I see, I need to iterate through querySet.如我所见,我需要遍历 querySet。 But how?但是如何?
And sorry for bad English:)抱歉英语不好:)
>>> pnt = Point(5, 23)
>>> [coord for coord in pnt]
[5.0, 23.0]
>>> pnt.coords
(5.0, 23.0)
add your variable pnt = Point(your point variable)添加您的变量 pnt = Point(您的点变量)
point is a python object so it has some attributes that you can use for example p.coords
will get you a tuple of (longitude, latitude)
so you can get: point 是一个 python 对象,所以它有一些你可以使用的属性,例如p.coords
会给你一个(longitude, latitude)
的元组,所以你可以得到:
lat = p.coords[1]
lon = p.coords[0]
also in your code you are instantiating the point object wrong the (longitude, latitude)
is the right format for it as well always check the docs同样在您的代码中,您正在错误地实例化点对象(longitude, latitude)
是它的正确格式,并始终检查文档
def mapper_done(request): query = MapPoint.objects.all() out_list = [{'ID': i.id, 'lat': i.p.x, 'lon': i.p.y} for i in query] return render(request, 'map_out.html', {'out_list': out_list})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.