百度地图的api句柄
baidumap的Python项目详细描述
百度地图API
说明
本模块是百度地图的python开发包。你只需要写一些代码就可以得到一个可执行的效果。此外,经过一些修改后,此模块还可以在另一个MAP API上工作
作者:cpak00@github
电子邮件:cymcpak00@gmail.com
开始
pip install baidumap
使用pip安装,只需要请求。
test.py
frombaidumapimportconfigfrombaidumap.api.handleimportget_handlefrombaidumap.objectimportBaiduMapObjectimportlogging# get raw handlerak_key='ZAMW5**********************'raw_handler=get_handle(ak_key)# get loggerFORMAT="%(asctime)s%(thread)d%(message)s"logging.basicConfig(format=FORMAT,datefmt="[%Y-%m-%d %H:%M:%S]")logger=logging.getLogger()logger.setLevel(logging.DEBUG)if__name__=='__main__':# log config(no necessary)config.mode=config.value.DEBUGconfig.logger=logger# Agent Modeprint('---\nAgent Mode:\n')raw_handler=get_handle(ak_key)thu_main=BaiduMapObject(address='北京市清华大学紫荆园餐厅')thu_main.from_address(raw_handler)print('from address find location: %s'%thu_main.get_property('location')['location'])print('from address find location: %s'%thu_main.get_properties(['lat','lng'],p_defaults={'lat':'-1','lng':'-1'}))thu_main.from_location(raw_handler)print('\nfrom location find uid: %s'%thu_main.get_property('uid'))print('and its name: %s'%thu_main.get_property('name'))find_location=thu_main.get_properties(['uid','name'],p_defaults={'uid':'','name':''})print('--\nfrom location find uid and name: %s'%find_location)forindexinfind_location:thu_main.from_json(find_location[index])thu_main.from_uid(raw_handler,detail=True)print('-\nfrom uid find info:\n%s'%thu_main)# Factory Modeprint('---\nFactory Mode:\n')iplocer=get_handle(ak_key,'location/ip')iplocer.set_params()print(iplocer.run(collect_keys=['address','content']).get_property('address')['address'])print('---\n')placeser=get_handle(ak_key,'place/v2/search',is_list=True,query='ATM机',tag='银行',region='北京',)print(placeser.run(page_size=20,max_page_num=1,max_result_num=15).get_property('address'))# complex sample# get zijing dormitory location from agent modethu_main=BaiduMapObject(address='北京市清华大学紫荆宿舍')thu_main.from_address(raw_handler)thu_location=thu_main.get_property('location')['location']print('---\n\n起始坐标: %s'%(thu_location))# get circle search handle from factory mode# sort by distancecircleser=get_handle(ak_key,'place/v2/search',is_list=True,query='火车站',scope=2,filter='sort_name:distance|sort_rule:1')circleser.set_params(radius=10000,location=thu_location)nearest_station=circleser.run(max_result_num=5)['results'][0]station_location=nearest_station.get_property('location')['location']print('万米内最近的火车站: %s'%(nearest_station.get_property('name')['name']))# get a handle to find road to hospitalrouter=get_handle(ak_key,'direction/v2/transit',is_list=True)router.set_params(origin=thu_location,destination=station_location)result=router.run()# print(repr(result))station=result.get_properties(['on_station','off_station'])print('提取出全部的on_station, off_station属性(地铁站名)')print(station)
手柄
工厂模式
从工厂函数获取句柄get_handle
frombaidumap.api.handleimportget_handle
使用baidu map web api中的名称
示例
检查
http://api.map.baidu.com/place/v2/search?query=ATM机&tag=银行®ion=北京&output=json&ak=您的ak///获取{p>
api路径是http://api.map.baidu.com/place/v2/search
(最后的/是否非常重要)
所以这个句柄的名称是place/v2/search
(只需删除api路径的头即可)
# ak_key is the authority key of the baidu map# you need to apply for it from ('http://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5')ak_key='********************'# you can set params when get it from factory# (the first two is not params, they are ak_key and handle's name)# set is_list: true to get multi-page resultplace_search=get_handle(ak_key,'place/v2/search',is_list=True)# then use method set_params() to set request parameterplace_search.set_params(query='ATM机',region='北京')# use method run to get result# you can limit the max_page_num(=-1 not limited), page_size(=10, limited by baidu mao), max_result_num(=-1 not limited) and interval(=0 second between each request(too frequently request will be block by baidu map and baidumap.api will raise baidumap.api.exceptions.BaiduMapApiException))# place_search.run([max_page_num=-1[, max_result_num=-1[, page_size=10[, interval=0]]]])atm_in_beijing=place_search.run(max_page_num=3,page_size=20,max_result_num=55,interval=0.5)# get resultprint(atm_in_beijing)# get property(find mode)# will return a dictprint(atm_in_beijing.get_property('address'))
代理模式
您还可以使用handle by agent模式
首先。您需要导入baidumapobject
frombaidumap.objectimportBaiduMapObject
第二。您需要使用一些键和值创建baidumapobject
thu_main=BaiduMapObject(address='北京市清华大学紫荆宿舍')
那么。您需要使用ak_键创建原始句柄
raw_handle=get_handle(ak_key)
最后。您只需调用代理方法来填充baidumapobject的数据
# geography decoder call# it will fill Object with locationthu_main.from_address(handle)# geography encoder call# it will fill Object with address and uid found by location# it will create a list-like BaiduMapObjectthu_main.from_location(handle)# create a object with uidthu_main=BaiduMapObject(uid=thu_main.get_property('uid')[0].uid)# uid info call# it will fill Object with detail info found by uidthu_main.from_uid(handle,detail=True)
对象
jsonlike
__init__(json=dict(), **kwargs)
JsonLike object can be inited with list or dict, you can replace some parameters by decalre kwargs
__str__()
JsonLike object will be transfered as str just like dict
is_list()
JsonLike object can be dict-like or list-like determined by which one init it
get_property(p_key, p_default=None)
if you want to read value of JsonLike, this method is suggested, it will return a dict.
if there is only one result, it will return dict as {key: value}
if there are more results, it will return a list-likedict which contains location
get_properties(p_keys, p_defaults=None)
you can combine two or more properties in one list-likedict
set_property(p_key, p_value)
you can't set key-value using <JsonLike>[key]=value
you are supposed to set property with this method, if there is no p_key in the JsonLike object, you can not set it with this method
keys()
return the keys in the JsonLike object
from_json(json, **kwargs)
reconstruct the JsonLike object by dict or list, can replace some properties by kwargs
to_json()
return dict in JsonLike
位置(jsonlike)
__str__()
location will be formatted as lat,lng
Baidumapobject(jsonlike)
from_uid(handle, detail=False)
fill the BaiduMapObject by uid
needs a handle with valid ak_key
from_address(handle, detail=False)
fill the BaiduMapObject by address
needs a handle with valid ak_key
from_location(handle, detail=False)
fill the BaiduMapObject by location
needs a handle with valid ak_key
异常
baidumapapiexception
base exception
in baidumap.api.exception
HyrOntOutStReRoR < EH3>inherit from BaiduMapApiException
handle name not valid
in baidumao.api.exception
网络错误
inherit from BaiduMapApiException
net connection broken
in baidumao.api.exception
其他错误
inherit from BaiduMapApiException
error which can not be recognized
in baidumao.api.exception
如何工作
核心
package baidumap.core
收集器
控制器
状态
效用
package baidumap.util
听写工具和列表工具
inherit from BaiduMapApiException
handle name not valid
in baidumao.api.exception
inherit from BaiduMapApiException
net connection broken
in baidumao.api.exception
inherit from BaiduMapApiException
error which can not be recognized
in baidumao.api.exception
package baidumap.core
package baidumap.util
一些安全操作功能
网址
类url
管理参数和url路径
使用包requests通过http请求获取json[get]
日志
配置
baidumap.config.mode
value | description |
---|---|
config.value.DEBUG | log detail information |
config.value.INFO | log important statement |
config.value.WARNING | log unsafe statement |
config.value.ERROR | log error |
config.value.NONE | no log |
baidumap.config.filename
value | description |
---|---|
None | directly record in shell |
Logger | use module logging |