两个地理坐标距离计算

操作步骤:

  • 导包
    • 使用geodesic()函数
    • 或者使用great_circle
from geopy.distance import great_circle, geodesic
# 注意:两个函数得到的结果不同
print(geodesic((32.03128, 118.784149), (32.067131, 118.783966)).m)  # 计算两个坐标直线距离   # 3975.471457390853
print(great_circle((32.03128, 118.784149), (32.067131, 118.783966)).m)    # 两个函数的差别 3986.492256905095
结果:
3975.471457390853
3986.492256905095

那么,给定一组经纬度坐标的二维数组如何对每个位置的距离进行计算?

  • 注意: calculate_distance()方法使用np.linalg.norm()借用欧式距离进行计算,并不对
  • calculate_distance2()是正确方法
import numpy as np
import pandas as pd
from geopy.distance import geodesic

print(geodesic((31.237872, 121.470259), (31.246946, 121.513919)).m)  # 计算两个坐标直线距离   # 4279.081922014711

# 1.数据集 
C = np.array([[31.237872, 121.470259], [31.246946, 121.513919], [31.234472, 121.473219]], dtype=float)
city_num = C.shape[0]  # ES的数量

# 函数:计算城市之间的距离
def calculate_distance(C):
    """
    根据坐标,得出城市之间的距离矩阵
    :param C,城市的二维坐标
    :return: distance_matrix
    """
    num = city_num
    distance_matrix = np.zeros((num, num))  # 打印一个52行52列的二维数组
    for i in range(num):
        for j in range(i, num):
            distance_matrix[i][j] = distance_matrix[j][i] = np.linalg.norm(C[i] - C[j])
    return distance_matrix  # distance_matrix[i][j] = distance_matrix[j][i]表示城市i和j距离

def calculate_distance2(C):
    """
    根据坐标,得出城市之间的距离矩阵
    :param C,城市的二维坐标
    :return: distance_matrix
    """
    num = city_num
    distance_matrix = np.zeros((num, num), dtype=float)  # 打印一个52行52列的二维数组
    for i in range(num):
        for j in range(i, num):
            temp = geodesic(C[i], C[j]).m
            distance_matrix[i][j] = distance_matrix[j][i] = temp
    return distance_matrix  # distance_matrix[i][j] = distance_matrix[j][i]表示城市i和j距离

print(calculate_distance(C))
print("*"*60)
print(calculate_distance2(C))
输出:
4279.081922014711
[[0.         0.04459297 0.00450795]
 [0.04459297 0.         0.04256866]
 [0.00450795 0.04256866 0.        ]]
************************************************************
[[   0.         4279.08192201  470.77248076]
 [4279.08192201    0.         4116.51181745]
 [ 470.77248076 4116.51181745    0.        ]]

你可能感兴趣的:(数据分析,1024程序员节,经纬度距离计算,地理坐标计算)