计算2个邮政编码之间距离的Python代码?

时间:2021-02-07 06:19:09

标签: python python-3.x

我是python的新手,我想写一个简单的代码来学习

假设我有 2 个邮政编码,我想计算它们之间的距离。我如何编写代码会提示我输入两个邮政编码,然后输出距离(以英里为单位)??

例如:

**邮政编码 1:90210

邮政编码 2:11234

输出:2,830 英里**

是否需要某些特定的库或包??

1 个答案:

答案 0 :(得分:1)

首先得到纬度/经度...然后你可以计算2纬度经度之间的半正弦距离

此解决方案使用 API 来检索纬度/经度...没有对垃圾值的错误处理...此外,这严格来说是乌鸦飞翔...它显然不会告诉您驱动器有多远这是...

为了简单起见,它使用 requests 库...但我确定您可以使用 urllib ... math 是一个内置模块

import requests
import math
 
def get_lat_lon(zip):
    uri = 'https://public.opendatasoft.com/api/records/1.0/search/?q={zip}&dataset=us-zip-code-latitude-and-longitude'
    return requests.get(uri.format(zip=zip)).json()["records"][0]['fields']['geopoint']

def rad(x):
  return x * math.pi / 180.0;


def getHaversineDistance(p1, p2):
  R = 6378137; # Earth’s mean radius in meter
  dLat = rad(p2[0] - p1[0]);
  dLong = rad(p2[1] - p1[1]);
  a = (math.sin(dLat / 2) * math.sin(dLat / 2) +
    math.cos(rad(p1[0])) * math.cos(rad(p2[0])) *
    math.sin(dLong / 2) * math.sin(dLong / 2))
  c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
  d = R * c #
  return d # // returns the distance in meter
def Meters2Miles(meters):
    return meters * 0.000621371

zip1 = input("Enter Zip1")
p1 = get_lat_lon(zip1)
zip2 = input("Enter Zip2")
p2 = get_lat_lon(zip2)
dist_meters = getHaversineDistance(p1,p2)
dist_miles = Meters2Miles(dist_meters)
print("There are about %f miles between zipcodes %s and %s"%(dist_miles,zip1,zip2))
相关问题