python實現根據經緯度計算距離


import math
from math import pi, sin, cos

addresses = [118.746795, 32.028986, 118.744657, 32.02933]
EARTH_REDIUS = 6378.137

def rad(d):
    return d * pi / 180.0

def getDistance(lat1, lng1, lat2, lng2):
    """ 根據兩地的經緯度,計算對應的距離km"""
    radLat1 = rad(lat1)
    radLat2 = rad(lat2)
    a = radLat1 - radLat2
    b = rad(lng1) - rad(lng2)
    s = 2 * math.asin(math.sqrt(math.pow(math.sin(a / 2), 2) + math.cos(radLat1) * cos(radLat2) * math.pow(sin(b / 2), 2)))
    s = s * EARTH_REDIUS
    return s

題外話:根據地址,獲取對應的經緯度。

Key的獲取方式:百度地圖開放平台  控制台 --> 應用管理 --> 我的應用 --> 創建應用(成功后返回會獲得 【訪問應用(AK)】及Key)

API:web端的api

import geocoder

Key = "kKLSYO6Xoxlb****1Bbilr8A6ijHp6Pz"

import hashlib
import http
import json
from urllib import parse

import requests


def get_url(address):
    # http://api.map.baidu.com/geocoder/v2/?address=你的地址&output=json&ak=你的ak
    queryStr = f'/geocoder?address={address}&output=json&ak={Key}'
    # 對queryStr進行轉碼,safe內的保留字符不轉換
    encodedStr = parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
    # 在最后直接追加上sk
    rawStr = encodedStr + '你的sk'
    # 計算sn
    sn = (hashlib.md5(parse.quote_plus(rawStr).encode("utf8")).hexdigest())
    # 由於URL里面含有中文,所以需要用parse.quote進行處理,然后返回最終可調用的url
    url = parse.quote("http://api.map.baidu.com" + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;'@()*[]")

    return url

def get_Location(url):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74',
               'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',}
    data = requests.get(url, headers=headers).json()
    coordinate = data['result']['location']
    return coordinate

if __name__ == '__main__':
    while True:
        address = input('請輸入您要查詢的地址:')
        if address.__eq__(''):
            print("請輸入地址!")
            continue
        url = get_url(address)
        print(url)
        coordinate = get_Location(url)
        lng = coordinate['lng']
        lat = coordinate['lat']
        print(coordinate)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM