| 10 | from ...tool import Tool |
| 11 | |
| 12 | class BaiduMapAPI: |
| 13 | def __init__(self, ak: str, sk: str): |
| 14 | self.ak = ak |
| 15 | self.sk = sk |
| 16 | self.base_url = 'http://api.map.baidu.com' |
| 17 | |
| 18 | def generate_url_with_sn(self, url: str) -> str: |
| 19 | """ |
| 20 | 生成百度地图API请求中的SN码 |
| 21 | :param url: API请求的URL |
| 22 | :return: SN码 |
| 23 | """ |
| 24 | query_str = url[len('http://api.map.baidu.com/') - 1:] |
| 25 | encoded_str = quote(query_str, safe="/:=&?#+!$,;'@()*[]") |
| 26 | raw_str = encoded_str + self.sk |
| 27 | sn = hashlib.md5(urllib.parse.quote_plus(raw_str).encode('utf-8')).hexdigest() |
| 28 | url_with_sn = f'{url}&sn={sn}' |
| 29 | return url_with_sn |
| 30 | |
| 31 | def get_location(self, address: str) -> Optional[Tuple[float, float]]: |
| 32 | """ |
| 33 | 该函数仅适用于中国境内地图(内陆),this function only suitable for locations in Mainland China |
| 34 | 根据地址获取地点经纬度, return the coordinates |
| 35 | :param address: 地址 |
| 36 | :return: 地点经纬度 (纬度, 经度),若无法获取则返回None; return (latitute, longitute) |
| 37 | """ |
| 38 | url = f'{self.base_url}/geocoding/v3/?address={address}&output=json&ak={self.ak}&callback=showLocation' |
| 39 | url = self.generate_url_with_sn(url) |
| 40 | response = requests.get(url) |
| 41 | json_text = response.text[len('showLocation&&showLocation('):-1] |
| 42 | data = json.loads(json_text) |
| 43 | if data['status'] == 0: |
| 44 | result = data['result'] |
| 45 | location = result['location'] |
| 46 | return location['lat'], location['lng'] |
| 47 | else: |
| 48 | return None |
| 49 | |
| 50 | def get_address_by_coordinates(self, lat: float, lng: float) -> Optional[str]: |
| 51 | """ |
| 52 | 该函数仅适用于中国境内地图(内陆),this function only suitable for locations in Mainland China |
| 53 | 根据经纬度获取地点名称 |
| 54 | :param lat: 纬度 |
| 55 | :param lng: 经度 |
| 56 | :return: 地点名称列表,包含经纬度,具体地址等信息,若无法获取则返回None |
| 57 | """ |
| 58 | url = f'{self.base_url}/reverse_geocoding/v3/?location={lat},{lng}&output=json&ak={self.ak}' |
| 59 | url = self.generate_url_with_sn(url) |
| 60 | response = requests.get(url) |
| 61 | data = response.json() |
| 62 | if data['status'] == 0: |
| 63 | result = data['result']['formatted_address'] |
| 64 | return result |
| 65 | else: |
| 66 | return None |
| 67 | def get_nearby_places(self, location: Tuple[float, float], radius: int, keyword: Optional[str] = '餐厅') -> List[str]: |
| 68 | """ |
| 69 | 该函数仅适用于中国境内地图(内陆),this function only suitable for locations in Mainland China |