百度地图的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中的名称


示例

baidu map web api

检查

http://api.map.baidu.com/place/v2/search?query=ATM机&tag=银行&region=北京&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

听写工具和列表工具

一些安全操作功能

网址

url

管理参数和url路径

使用包requests通过http请求获取json[get]

日志

配置

baidumap.config.mode

valuedescription
config.value.DEBUGlog detail information
config.value.INFOlog important statement
config.value.WARNINGlog unsafe statement
config.value.ERRORlog error
config.value.NONEno log

baidumap.config.filename

valuedescription
Nonedirectly record in shell
Loggeruse module logging

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
ArrayList Java中的搜索字符串   另一个web应用程序的java访问会话   另一个应用程序中的活动和服务之间的java通信   java根据Json字符串类型将Json字符串转换为对象   eclipse如何解决java中的错误异常。lang.NoSuchMethodError:'java。字符串javax。摆动JOptionPane。showInputDialog(java.lang.String)'   线程“main”java中的安卓异常。lang.NoClassDefFoundError:org/codehaus/jackson/JsonParseException   java如何在安卓 emulator上显示Mat图像?使用NDK   Java在本地读取测试源文件,但在服务器上读取失败   java dowhile循环用于计算输入数字中的数字。故障排除代码   JAva初学者在编写获取成本的方法时遇到困难   java是shell游戏。我如何让物体移动,特别是在特定的曲线上,但顺序是随机的?   java如何区分两个同名的JButton   java为什么我在Spring Boot中需要一个接口?   java将文件路径插入数据库将删除\   使用InterfaceType初始化java对象   java如何部署一个分为Angular、Spring Boot和MySQL的项目?   java如何使用Symja解决不等式?