http://en.wikipedia.org/wiki/Geohash 简单使用 geohash, redis,bottle, python-geohash 来实现 restful api的地理位置附近人搜素
from bottle import Bottle, run
import time
import json
from redis_pool import Redis
R = Redis().connection_pool()
import geohash
app = Bottle()
@app.route('/v1/mark/<longitude:float>/<latitude:float>')
def mark_police(longitude, latitude):
geo_encode = geohash.encode(longitude, latitude, 12)
R.set(geo_encode, time.time())
return json.dumps({"code":"success", "msg":{"geohash":geo_encode}})
@app.route('/v1/show/<longitude:float>/<latitude:float>')
def show(longitude, latitude):
geo_encode = geohash.encode(longitude, latitude, 7)
eight = geohash.expand(geo_encode)
response = []
for e in eight:
response.extend([geohash.decode(i) for i in R.keys("%s*"%e)])
return json.dumps({"code":"success", "msg":response})
run(server='eventlet', app=app, host='0.0.0.0', port=9090)
依赖的redis封装class
import redis
class Redis(object):
pool=None
R = None
def __init__(self, host='localhost', port=6379, max_connections=2048):
self.host=host
self.port=port
self.max_connections=int(max_connections)
self.pool = redis.ConnectionPool(host=host,
port=port, db=0,
max_connections=max_connections)
def connection_pool(self):
if not self.R:
self.R = redis.Redis(connection_pool=self.pool)
return self.R
API 接口使用example
1. 标记 user 位置
http://localhost:9090/v1/mark/longitude/latitude example:
http://localhost:9090/v1/mark/12.1256/22.22 {"msg": {"geohash": "s6pucxkhex8v"}, "code": "success"}
2. 用户请求周围1km内的 其他 user 位置信息
http://localhost:9090/v1/show/longitude/latitude example:
http://localhost:9090/v1/show/12.1256/22.22
{"msg": [[12.123455917462707, 22.220000009983778], [12.125600008293986, 22.220000009983778]], "code": "success"}
注:
longitude 经度
latitude 纬度
均为float 型