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