[Django]-Get coordinates from Point Django

7👍

>>> 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)

4👍

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:

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

👤mahyar

1👍

You can fetch lat, lng values from database using Func() expressions:

from django.db.models import Func, FloatField


class GeometryPointFunc(Func):
    template = "%(function)s(%(expressions)s::geometry)"

    def __init__(self, expression: Any) -> None:
        super().__init__(expression, output_field=FloatField())


class Latitude(GeometryPointFunc):
    function = "ST_Y"


class Longitude(GeometryPointFunc):
    function = "ST_X"

Then use in queryset:

query = MapPoint.objects.annotate(lat=Latitude("p"), lng=Longitude("p")).values()

0👍

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})

0👍

I annotated a queryset with lat and lon separately, as floats. Evgeni’s answer put me on the right track, but I ended up doing it like this:

from django.db.models import Func, FloatField

query = MapPoint.objects.annotate(
    lat=Func("p", function="ST_Y", output_field=FloatField()),
    lon=Func("p", function="ST_X", output_field=FloatField()),
).values()

for place in query:
    print(place)
# {'id': 1, 'lat': 52.018948, 'lon': 8.819528}
# {'id': 2, 'lat': 53.692242, 'lon': 9.373505}
# ... 

Leave a comment