在Python中比较Lat / Lon和最接近最远的显示

时间:2018-03-01 05:12:48

标签: python

我有一个程序可以将Lat / Lon的用户输入与一组Lat / Lon进行比较,并显示最接近的。代码如下,并且工作正常:

#prints out the closest lat and lon
from math import cos, asin, sqrt

#Haversine formula
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 in km


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))

但是我希望在距离列表最近到最远的Lat / lon范围内显示结果,而不是单个Lat / lon输出。
输入lat:40 lon:80
输出{'lat': 40.42, 'lon': 86.123}
预期输出{'lat': 40.42, 'lon': 86.123}, {'lat': 39.78, 'lon': 89.336}, {'lat': 39.66, 'lon': 87.11},{'lat': 41.35, 'lon': 90.21 },{'lat': 38.88, 'lon': 87.251 },{'lat': 37.82, 'lon': 86.142}

2 个答案:

答案 0 :(得分:1)

获取输入的所有距离列表,然后对其进行排序

在Python3中测试

<div *ngIf="data.mod=='goLocation'" class="panel-body">
  <form #f="ngForm" (ngSubmit)="go(f.value); f.reset();" class="settings-form">
    <table>
      <tr>
        <td>
          <mat-form-field>
            <input matInput placeholder="Longitude(X)" name="lon" id="lon" #lon="ngModel" ngModel required>
            <mat-error *ngIf="lon.touched && lon.invalid">
              <div *ngIf="lon.errors.required">Bu alanı boş geçemezsiniz.</div>
            </mat-error>
          </mat-form-field>
        </td>
        <td>
          <mat-form-field>
            <input matInput placeholder="Latitude(Y)" name="lat" id="lat" #lat="ngModel" ngModel required>
            <mat-error *ngIf="lat.touched && lat.invalid">
              <div *ngIf="lat.errors.required">Bu alanı boş geçemezsiniz.</div>
            </mat-error>
          </mat-form-field>
        </td>
      </tr>
    </table>
    <button [disabled]="!f.valid" class="btn btn-outline-primary">Git</button>
  </form>
</div>

输出

from operator import itemgetter 

# Use raw_input() with Python 2
lat = float(input("Latitude:"))
lon = float(input("Longitude:"))

distances = (distance(v['lat'],v['lon'],lat,lon) for v in sdata)
for lat_lng, d in sorted(zip(sdata, distances), key=itemgetter(1)):
  print(lat_lng['lat'], lat_lng['lon'], d)

答案 1 :(得分:0)

您也可以在一行中完成。

cust = {'lat': 40, 'lon': 80}
out = sorted(sdata, key=lambda data: distance(data['lat'], data['lon'], cust['lat'], cust['lon']))
print(out)

输出:

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