Package: baidumap
Baidu Map ApiBaidu Map ApiDescriptionGet StartHandleFactory ModeAgent ModeObjectJsonLike__init__(json=dict(), **kwargs)__str__()is_list()get_property(p_key, p_default=None)get_properties(p_keys, p_defaults=None)set_property(p_key, p_value)keys()from_json(json, **kwargs)to_json()Location(JsonLike)__str__()BaiduMapObject(JsonLike)from_uid(handle, detail=False)from_address(handle, detail=False)from_location(handle, detail=False)ExceptionBaiduMapApiExceptionHandleNotExistsErrorNetErrorOtherErrorHow to workcorecollectorcontrollerstatusutildict_tool & list_toolurlLogconfigDescriptionThis module is an python sdk for baidu map. You are only required to write a few code to get an execllent effect. Also, this module may work on another map api after some modificationAuthor: cpak00@githubEmail:cymcpak00@gmail.comGet Startpipinstallbaidumapinstall with pip, requestes required only.test.pyfrombaidumapimportconfigfrombaidumap.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)HandleFactory ModeGet handle from factory functionget_handlefrombaidumap.api.handleimportget_handleUse name frombaidu map web apiSampleFrombaidu map web api行政区划区域检索http://api.map.baidu.com/place/v2/search?query=ATM机&tag=银行&region=北京&output=json&ak=您的ak//GET请求The api path ishttp://api.map.baidu.com/place/v2/search(the / in the end or not is very important)So this handle's name isplace/v2/search(just remove the head of the api path)# 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'))Agent ModeYou can also use handle byagent modefirst. you need to importBaiduMapObjectfrombaidumap.objectimportBaiduMapObjectsecond. you need to create a BaiduMapObject with some keys and valuesthu_main=BaiduMapObject(address='北京市清华大学紫荆宿舍')then. you need to create a raw handle withak_keyraw_handle=get_handle(ak_key)finally. you just call the agent method to fill the data ofBaiduMapObject# 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)ObjectJsonLike__init__(json=dict(), **kwargs)JsonLikeobject can be inited withlistordict, you can replace some parameters by decalrekwargs__str__()JsonLikeobject will be transfered asstrjust likedictis_list()JsonLikeobject can bedict-likeorlist-likedetermined by which one init itget_property(p_key, p_default=None)if you want to read value ofJsonLike, this method is suggested, it will return adict.if there is only one result, it will returndictas {key: value}if there are more results, it will return alist-likedictwhich contains locationget_properties(p_keys, p_defaults=None)you can combine two or more properties in onelist-likedictset_property(p_key, p_value)you can't set key-value using <JsonLike>[key]=valueyou are supposed to set property with this method, if there is nop_keyin theJsonLikeobject, you can not set it with this methodkeys()return the keys in theJsonLikeobjectfrom_json(json, **kwargs)reconstruct theJsonLikeobject bydictorlist, can replace some properties bykwargsto_json()returndictinJsonLikeLocation(JsonLike)__str__()location will be formatted as lat,lngBaiduMapObject(JsonLike)from_uid(handle, detail=False)fill theBaiduMapObjectby uidneeds a handle with valid ak_keyfrom_address(handle, detail=False)fill theBaiduMapObjectby addressneeds a handle with valid ak_keyfrom_location(handle, detail=False)fill theBaiduMapObjectby locationneeds a handle with valid ak_keyExceptionBaiduMapApiExceptionbase exceptionin baidumap.api.exceptionHandleNotExistsErrorinherit fromBaiduMapApiExceptionhandle name not validin baidumao.api.exceptionNetErrorinherit fromBaiduMapApiExceptionnet connection brokenin baidumao.api.exceptionOtherErrorinherit fromBaiduMapApiExceptionerror which can not be recognizedin baidumao.api.exceptionHow to workcorepackage baidumap.corecollectorcontrollerstatusutilpackage baidumap.utildict_tool & list_toolsome safe operation functionsurlclassUrlmanager the params and url pathuse packagerequeststo get json by http request[GET]Logconfigbaidumap.config.modevaluedescriptionconfig.value.DEBUGlog detail informationconfig.value.INFOlog important statementconfig.value.WARNINGlog unsafe statementconfig.value.ERRORlog errorconfig.value.NONEno logbaidumap.config.filenamevaluedescriptionNonedirectly record in shellLoggeruse module logging