1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| ''' @file_name :shortest_dist.py @description : @time :2020/10/18 20:24:21 @author :Qifei @version :1.0 ''' from math import radians, cos, sin, asin, sqrt from itertools import permutations
class Route(): def __init__(self,data): self.data = data self.home = {'lng':'104.270910','lat':'30.876583'} self.distances = [] self.routes = [] self.iter_routes = permutations(data,len(data)) for iter_route in self.iter_routes: self.routes.append(list(iter_route)) def best_route(self): for route in self.routes: distance = 0 if len(route) > 1: for i in range(len(route)-1): distance += self.calc_distance(route[i+1]['lng'],route[i+1]['lat'],route[i]['lng'],route[i]['lat']) distance += self.calc_distance(self.home['lng'],self.home['lat'],route[0]['lng'],route[0]['lat']) distance += self.calc_distance(self.home['lng'],self.home['lat'],route[-1]['lng'],route[-1]['lat']) self.distances.append(distance) return self.routes[self.distances.index(min(self.distances))]
def calc_distance(self,lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [float(lon1), float(lat1), float(lon2), float(lat2)]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 return c * r * 1000
if __name__ == '__main__': data = [{'name':'大弯中学','lng':'104.278184','lat':'30.879862'},{'name':'怡湖公园','lng':'104.261332','lat':'30.878314'},{'name':'大弯小学','lng':'104.270611','lat':'30.880657'},{'name':'长河郡','lng':'104.278201','lat':'30.872356'}] route = Route(data) best_route = route.best_route() print(best_route)
|