SoFunction
Updated on 2024-11-10

Python using Redis to calculate latitude and longitude distance case

1. Required libraries, redis

pip install redis

2. Connecting to Redis

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

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

3. Calculations

Import the known address latitude and longitude into Redis for the calculation of the

(name="Collection name", values=["Longitude.", "Dimension.", "Name of address"])

Add multiple locations at oncevalues=[longitude1, dimension1, address name1, longitude2, dimension2, address name2, longitude3, latitude3, address name3......]

4. View latitude and longitude of added locations

result = ("Collection name", "Address name 1", "Address name 2")
print(result)  # [(address1longitudes, address1dimensionality), (address2longitudes, address2dimensionality)]

If not found, it returnsNone

result = ("Collection name", "Error name 1", "Error name 2")
print(result)  # [None, None]

5. Calculation of the distance between the two places

("Collection name", "Address name 1", "Address name 2", unit="km")

unit: unit of distance, optional("m": meter, "km": kilometer, "mi": mile, "ft": foot), the default value ism

6. Addresses within the scope of the search

result = (name="Collection name", longitude="Longitude.", latitude="Dimension.", radius="Radius distance", unit="Radius unit",
                     sort='ASC', count=10, withdist=True, withcoord=True)
print(result)    # [[b'Address name', gap, (longitudes, dimension (math.))], [b'shanghai', 0.1774, (121.4813420176506, 31.235159732038248)]]
  • sort: Sort by.ASCFrom near to far.DESCFrom far to near.
  • count: Specifies the previous data to be returned.
  • withdist: Whether to return the distance.
  • withcoord: Whether to return latitude and longitude information.

Attention:The returned data where the address name isbytetype, the use of which requires thedecode('utf-8)Processing.

To this article on the use of Python Redis to calculate the latitude and longitude distance case is introduced to this article, more related Python Redis content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!