日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python利用Redis計(jì)算經(jīng)緯度距離案例_python

作者:時(shí)光不寫代碼 ? 更新時(shí)間: 2022-11-01 編程語言

1. 需要的庫, redis

pip install redis

2. 連接Redis

import redis
class RedisCtrl(object):
    @staticmethod
    def connect(config):
        pool = redis.ConnectionPool(
            host=config['host'],
            db=config['db'],
            port=config['port'],
            password=config['password'],
        )
        return redis.StrictRedis(connection_pool=pool)

rd = RedisCtrl.connect({
    "db": 1,
    "port": "6379",
    "password": "password",
    "host": "",
})

3. 計(jì)算

把已知的地址經(jīng)緯度導(dǎo)入到Redis中, 用于計(jì)算

rd.geoadd(name="集合名稱", values=["經(jīng)度", "維度", "地址名稱"])

一次添加多個(gè)位置values=[經(jīng)度1, 維度1, 地址名稱1, 經(jīng)度2, 維度2, 地址名稱2, 經(jīng)度3, 緯度3, 地址名稱3......]

4. 查看已添加位置的經(jīng)緯度

result = rd.geopos("集合名稱", "地址名稱1", "地址名稱2")
print(result)  # [(地址1的經(jīng)度, 地址1的維度), (地址2的經(jīng)度, 地址2的維度)]

如果未查到, 會(huì)返回None

result = rd.geopos("集合名稱", "錯(cuò)誤名稱1", "錯(cuò)誤名稱2")
print(result)  # [None, None]

5. 計(jì)算兩地之間的距離

rd.geodist("集合名稱", "地址名稱1", "地址名稱2", unit="km")

unit:距離的單位, 可選("m": 米, "km": 千米, "mi": 英里, "ft": 英尺), 默認(rèn)值為m

6. 搜索范圍內(nèi)的地址

result = rd.georadius(name="集合名稱", longitude="經(jīng)度", latitude="維度", radius="半徑距離", unit="半徑單位",
                     sort='ASC', count=10, withdist=True, withcoord=True)
print(result)    # [[b'地址名稱', 距離, (經(jīng)度, 維度)], [b'shanghai', 0.1774, (121.4813420176506, 31.235159732038248)]]
  • sort: 排序方式, ASC由近到遠(yuǎn), DESC由遠(yuǎn)到近。
  • count: 指定返回前幾條數(shù)據(jù)。
  • withdist: 是否返回距離。
  • withcoord: 是否返回經(jīng)緯度信息。

注意: 返回的數(shù)據(jù)其中的地址名稱是byte類型的, 使用時(shí)需要decode('utf-8)處理。

原文鏈接:https://blog.csdn.net/weixin_44649870/article/details/126668523

欄目分類
最近更新