简体   繁体   中英

Comparing Lat/Lon values from the Database in Python

I have a python Program that compares a particular Lat/Lon against a set of lat/lon and displays the closest lat/lot.The code is as follows:

def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295#degree to radian
    a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
    return 12742 * asin(sqrt(a)) #print data in kms


def closest(data, v):
    return min(data, key=lambda p: distance(v['lat'],v['lon'],p['lat'],p['lon']))

sdata = [{'lat': 37.82, 'lon': 86.142}, 
    {'lat': 38.88,  'lon': 87.251 }, 
    {'lat': 39.78, 'lon': 89.336},
    {'lat': 40.42, 'lon': 86.123}, 
    {'lat': 41.35,  'lon': 90.21 }, 
    {'lat': 39.66, 'lon': 87.11}]

lat = input("Latitude:")
lon = input("Longitude:")

cust = {'lat': lat, 'lon':lon}

print(closest(sdata,cust))

Result:

Input: Latitude:45
Longitude:85
Output:{'lat': 40.42, 'lon': 86.123}

This snippet works fine however I want to integrate the data from my database.So there's a list of lat and lon from my database as such:

(('25.2748603820801', '55.327449798584'), ('25.2712', '55.298'), ('25.277031', '55.275226'), ('25.251389', '55.332222'), ('25.275397', '55.328213'), ('25.275397', '55.328213'))

How to I integrate the above code so that I can run a loop on the the values from database and compare the values among themselves without the input ie it gives me 7 different answers hopefully

Iterate over the tuple and convert to the required format of an array of dicts format in the following way and use it as input to your method.

sdata = (('25.2748603820801', '55.327449798584'), ('25.2712', '55.298'), ('25.277031', '55.275226'), ('25.251389', '55.332222'), ('25.275397', '55.328213'), ('25.275397', '55.328213'))
b = [{'lat':l1, 'lon':l2} for l1,l2 in sdata]

i = 0
for cust in b:
    tempb = [{'lat':l1, 'lon':l2} for l1,l2 in sdata]
    tempb.pop(i)
    print(closest(tempb,cust))
    i += 1

 #value of b
 [{'lat': '25.2748603820801', 'lon': '55.327449798584'}, 
 {'lat': '25.2712', 'lon': '55.298'}, 
 {'lat': '25.277031', 'lon': '55.275226'}, 
 {'lat': '25.251389', 'lon': '55.332222'}, 
 {'lat': '25.275397', 'lon': '55.328213'}, 
 {'lat': '25.275397', 'lon': '55.328213'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM