找到最近的纬度和经度

时间:2016-12-26 22:07:33

标签: python

我正在编写一个小程序并提高效率,我需要能够在我的数组中找到最接近的纬度和经度。

假设您有以下代码:

 Private Sub Foo()

        Dim connection As New MySqlConnection(MyConString)
        Dim sQuery As String = "Select * from Table"
        Dim myDA As New MySqlDataAdapter(sQuery, connection)
        Dim cmb As New MySqlCommand(myDA,connection)
        Dim MyDT As New DataTable() ' <- datatable must be filled with data from the datagrid

        myDA.Fill(MyDT)
        ' * Add new rows or delete/update existing one
        ' * and update the DataTable using 
        myDA.Update(MyDT)

    End Sub

我得到的结果是:

tempDataList = [{'lat': 39.7612992 , 'lon': -86.1519681}, 
                {"lat": 39.762241, "lon": -86.158436}, 
                {"lat": 39.7622292, "lon": -86.1578917}]

tempLatList = []
tempLonList = []

for item in tempDataList:
    tempLatList.append(item['lat'])
    tempLonList.append(item['lon'])

closestLatValue = lambda myvalue: min(tempLatList, key=lambda x: abs(x - myvalue))
closestLonValue = lambda myvalue: min(tempLonList, key=lambda x: abs(x - myvalue))

print(closestLatValue(39.7622290), closestLonValue(-86.1519750))

应该是什么(在本例中,列表中的最后一个对象)

(39.7622292, -86.1519681)

我知道如何获得单个值的最接近的单元格,但是,我想让lambda函数考虑这两个值,但我不完全确定如何。帮助

3 个答案:

答案 0 :(得分:21)

要正确计算地球上各点之间的距离,您需要https://technet.microsoft.com/en-us/library/bb522495(v=sql.105).aspx公式之类的内容。使用Haversine中提供的Python实现,您可以像这样编写代码:

<?= Html::dropDownList('food', $food_id, $foodList, ['id'=>'food-select']); ?>

答案 1 :(得分:0)

如果地球是平面的,

from itertools import combinations
from math import sqrt

coords = [{'lat': 39.7612992 , 'lon': -86.1519681}, 
                {"lat": 39.762241, "lon": -86.158436}, 
                {"lat": 39.7622292, "lon": -86.1578917}]


def euclidean(l1, l2):
    return ((l1[0]**2)-(l2[0]**2)) + ((l1[1]**2)-(l2[1]**2)) 

pairs = [j for j in combinations([i.values() for i in coords], 2)]
pairs.sort(key= lambda x: euclidean(*x))
print pairs[-1]

答案 2 :(得分:0)

您也可以简单地这样做:

import mpu
def distance(point1, point2):
    return mpu.haversine_distance(point1, point2)

def closest(data, this_point):
    return min(data, key=lambda x: distance(this_point, x))