Created
March 8, 2015 12:52
-
-
Save ccwang002/59b7c4b6bdd80a6af9c6 to your computer and use it in GitHub Desktop.
Baidu map API usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import requests | |
class BaiduMap: | |
def __init__(self, key=''): | |
"""Helper class for Baidu map API | |
Parameters | |
---------- | |
key: str | |
API key | |
""" | |
if not key: | |
raise ValueError('Baidu map API key required') | |
# set fixed parameters | |
self._params = { | |
'ak': key, # baidu api key | |
'output': 'json', # always use json | |
} | |
def get(self, params): | |
full_params = {} | |
full_params.update(self._params) | |
full_params.update(params) | |
r = requests.get( | |
'http://api.map.baidu.com/geocoder/v2/', | |
params=full_params | |
) | |
return r.json() | |
def resolve_address(self, lat, lng, show_nearby=False): | |
"""Resolve the postal address by geo location | |
Parameters | |
---------- | |
lat: float | |
Latitude | |
lng: float | |
Longitude | |
show_nearby: bool, False | |
Whether to show nearby postal addresses within 100m | |
""" | |
params = { | |
'location': '{!s},{!s}'.format(lat, lng), | |
'pois': 1 if show_nearby else 0, | |
} | |
json = self.get(params) | |
return json['result'] | |
def resolve_location(self, address, city=None): | |
"""Resolve the geo location by postal address | |
Parameters | |
---------- | |
address: str | |
postal address | |
city: str | |
city name | |
""" | |
params = { | |
'address': address, | |
'city': city, | |
} | |
json = self.get(params) | |
return json['result'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment