user2491297
user2491297

Reputation: 65

Finding objects nearby

objects = Position.objects.exclude(latitude__isnull = True).exclude(longitude__isnull = True).exclude(startup__isnull = True).extra(where=["3956 * 2 * ASIN(SQRT(POWER(SIN((%(latitude)s - abs(latitude)) * pi()/180 / 2), 2) + COS(%(latitude)s * pi()/180 ) * COS(abs(latitude) * pi()/180) * POWER(SIN((%(longitude)s - longitude) * pi()/180 / 2), 2) )) < 50" % {'latitude': latitude, 'longitude': longitude}],)
objects = objects.order_by('startup').distinct('startup')

I use the code above to find objects that are nearby. However, even when an object has the same latitude/longitude as the object in the database, that object in the database does not show up.

For example, let's say Position object 1 has the following coordinates:

Latitude: -23.5551522346
Longitude: -46.6540710256

And user 1 has the following coordinate:

Latitude: -23.5551522346
Longitude: -46.6540710256

Position object 1 does not show up for user 1 as an object that is nearby.

What should I do?

Upvotes: 1

Views: 169

Answers (3)

andilabs
andilabs

Reputation: 23281

If you dont't want using GeoDjango have a look on this snippet, which I used in my project (MySQL, Haversine)

def nearby_spots_old(request, lat, lng, radius=5000, limit=50):
    """
    WITHOUT use of any external library, using raw MySQL and Haversine Formula
    http://en.wikipedia.org/wiki/Haversine_formula
    """
    radius = float(radius) / 1000.0

    query = """SELECT id, (6367*acos(cos(radians(%2f))
               *cos(radians(latitude))*cos(radians(longitude)-radians(%2f))
               +sin(radians(%2f))*sin(radians(latitude))))
               AS distance FROM demo_spot HAVING
               distance < %2f ORDER BY distance LIMIT 0, %d""" % (
        float(lat),
        float(lng),
        float(lat),
        radius,
        limit
    )

    queryset = Spot.objects.raw(query)
    serializer = SpotWithDistanceSerializer(queryset, many=True)

    return JSONResponse(serializer.data)

Maybe this comparision (Haversine vs GeoDjango) will convince you: https://gist.github.com/andilab/4232b463e5ad2f19c155 [GEODJANGO EXAMPLE]

Upvotes: 1

Tomasz Wysocki
Tomasz Wysocki

Reputation: 11568

You should use geodjango (http://geodjango.org/) with postgis.

Upvotes: 0

dan-klasson
dan-klasson

Reputation: 14190

What should I do?

Get the output of the produced query (django-debug-toolbar will work for this). Run manual queries against your database server until you get it working. Then come back and modify your extra.

Upvotes: 0

Related Questions