使用 redis-py 储存地理位置数据( 二 )

比如说 ,要计算清远和广州之间的距离 ,我们可以执行以下代码:
>>> r.geodist("Guangdong", "Qingyuan", "Guangzhou")52094.4338因为 GEODIST 命令默认使用米作为单位 ,所以它返回了 52094.4338 米作为结果 ,为了让这个结果更为直观一些 ,我们可以将 GEODIST 命令的单位从米改为千米(公里):
【使用 redis-py 储存地理位置数据】>>> r.geodist("Guangdong", "Qingyuan", "Guangzhou", unit="km")52.0944现在 ,我们可以更直观地看到清远和广州之间相距 52.0944 公里了 。
范围查找Redis 的 GEORADIUS 命令 和 GEORADIUSBYMEMBER 命令 可以让用户基于指定的地理位置或者已有的地理位置进行范围查找 ,redis-py 也通过同名的 georadius() 方法和 georadiusbymember() 方法来执行这两个命令 。
以下是 georadius() 方法的文档:
georadius(self, name, longitude, latitude, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None) method of redis.client.Redis instanceReturn the members of the of the specified key identified by the``name``argument which are within the borders of the area specifiedwith the ``latitude`` and ``longitude`` location and the maxiumdistnance from the center specified by the ``radius`` value.The units must be one o fthe following : m, km mi, ft. By default``withdist`` indicates to return the distances of each place.``withcoord`` indicates to return the latitude and longitude ofeach place.``withhash`` indicates to return the geohash string of each place.``count`` indicates to return the number of elements up to N.``sort`` indicates to return the places in a sorted way, ASC fornearest to fairest and DESC for fairest to nearest.``store`` indicates to save the places names in a sorted set namedwith a specific key, each element of the destination sorted set ispopulated with the score got from the original geo sorted set.``store_dist`` indicates to save the places names in a sorted setnamed with a sepcific key, instead of ``store`` the sorted setdestination score is set with the distance.而以下则是 georadiusbymember() 方法的文档:
georadiusbymember(self, name, member, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None) method of redis.client.Redis instanceThis command is exactly like ``georadius`` with the sole differencethat instead of taking, as the center of the area to query, a longitudeand latitude value, it takes the name of a member already existinginside the geospatial index represented by the sorted set.作为例子 ,以下代码展示了如何通过给定深圳的地理坐标(114.0538788 , 22.5551603)来查找位于它指定范围之内的其他城市 ,这一查找操作是通过 georadius() 方法来完成的:
>>> r.georadius("Guangdong", 114.0538788, 22.5551603, 100, unit="km", withdist=True)[]# 没有城市在深圳的半径 100 公里之内>>> r.georadius("Guangdong", 114.0538788, 22.5551603, 120, unit="km", withdist=True)[['Foshan', 109.4922], ['Guangzhou', 105.8065]]# 佛山和广州都在深圳的半径 120 公里之内>>> r.georadius("Guangdong", 114.0538788, 22.5551603, 150, unit="km", withdist=True)[['Foshan', 109.4922], ['Guangzhou', 105.8065], ['Qingyuan', 144.2205]]# 佛山、广州和清远都在深圳的半径 150 公里之内