Quantcast
Channel: Python/Django Solr Lucene ubuntu linux developer
Viewing all articles
Browse latest Browse all 10

Calculating distance between two locations in python/django

$
0
0

In my new Searching App i want to simply be able to figure out the distance, geographically, between two points says user and doctor  based on their zip code and then sort a list based on that. I couldn’t find  this functionality built-in  Django. then i found a piece of code.

from math import sin, cos, radians, acos

# http://en.wikipedia.org/wiki/Earth_radius
# """For Earth, the mean radius is 6,371.009 km (˜3,958.761 mi; ˜3,440.069 nmi)"""
EARTH_RADIUS_IN_MILES = 3958.761

def calculate(lat_a, long_a, lat_b, long_b):
    """all angles in degrees, result in miles"""
    lat_a = radians(lat_a)
    lat_b = radians(lat_b)
    delta_long = radians(long_a - long_b)
    cos_x = (
        sin(lat_a) * sin(lat_b) +
        cos(lat_a) * cos(lat_b) * cos(delta_long)
        )
    return acos(cos_x) * EARTH_RADIUS_IN_MILES

#SFO (37.676, -122.433) to NYC (40.733, -73.917)
#calculate -> 2570.9028268899356
#A US government website (http://www.nhc.noaa.gov/gccalc.shtml) -> 2569
#This website (http://www.timeanddate.com/worldclock/distanceresult.html
# ?p1=179&p2=224), from which I got the SFO and NYC coordinates, -> 2577

but this did’t solve my whole issue ,in my request i have Zip Codes only so the crack was to get the database of all the zips from ZIP DIR in csv or sql format and add to the database of the App e.g the table name is ZipCode.

from django import template
from models import ZipCode

register = template.Library()

EARTH_RADIUS_IN_MILES = 3958.761

@register.filter
def calculate_distance(zip1,zip2):
    coordinate1 = ZipCode.objects.get(zip = zip1)
    coordinate2 = ZipCode.objects.get(zip = zip2)
    distance = calculate(coordinate1.latitude,coordinate1.longitude,coordinate2.latitude,coordinate2.longitude)
    if distance>= 0:
        return "%.2f"%round(distance,2)
    return "Sorry can't determine the distance from %s TO %s"%(zip1,zip2)

Usage

{% if request.GET.ZipCode %}
     {{ doctor.ZipCode|calculate_distance:request.GET.ZipCode }}
{% endif %}

Tagged: django, geodjango, math, python, solr

Viewing all articles
Browse latest Browse all 10

Trending Articles