Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I query the nearest record in a given coordinates(latitude and longitude of string type)?

I am using GeoDjango with PostGIS. Then I am into trouble on how to get the nearest record from the given coordinates from my postgres db table.

like image 517
eros Avatar asked Oct 21 '11 07:10

eros


People also ask

How do I find the nearest location using latitude and longitude in C#?

Format("POINT({0} {1})", longitude, latitude)); var nearbyLocations = (from location in _context. Locations where // (Additional filtering criteria here...) select new { LocationID = location.ID, Address1 = location. Address1, City = location. City, State = location.


1 Answers

Using PostGIS and GeoDjango to find your nearest neighbour

Consider this the model:

from django.contrib.gis.geos import Point
from django.contrib.gis.db import models

    class Store(models.Model):
        name = models.CharField(max_length=100)
        location = models.PointField(geography=True, srid=4326)
        longitude = models.FloatField()
        latitude = models.FloatField()
        objects = models.GeoManager()
    def save(self, **kwargs):
        self.location = Point(self.longitude, self.latitude)
        super(Store, self).save(**kwargs)

In a view get all the points of interest within a 100 mile radius of a specified longitude / latitude:

from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D

point = Point(lng, lat)
points = Store.objects.filter(
    location__distance_lte=(point, D(mi=100))
).distance(point).order_by('distance')

Show the results in a template:

<ul>
    {% for point in points %}
    <li>{{ point.name }} is {{ point.distance.mi|floatformat }} miles away</li>
    {% endfor %}
</ul>
like image 124
Basil Jose Avatar answered Sep 30 '22 19:09

Basil Jose