python GUI查看baidumap实现代码
时间: 2023-12-13 08:05:34 浏览: 107
使用python+spider+baiduMap实现过去全国的城市信息
以下是一个使用Python GUI(tkinter)实现在百度地图上查看指定地址的代码示例:
```python
import tkinter as tk
import requests
from io import BytesIO
from PIL import Image, ImageTk
# 百度地图API AK(需要自己去百度地图开发者中心申请)
AK = "your_ak_here"
class MapView(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.address_var = tk.StringVar()
self.address_var.set("北京市海淀区中关村")
self.create_widgets()
def create_widgets(self):
# 地址输入框
address_label = tk.Label(self, text="地址:")
address_label.grid(row=0, column=0, padx=5, pady=5)
address_entry = tk.Entry(self, textvariable=self.address_var)
address_entry.grid(row=0, column=1, padx=5, pady=5)
# 搜索按钮
search_button = tk.Button(self, text="搜索", command=self.search_address)
search_button.grid(row=0, column=2, padx=5, pady=5)
# 地图显示区域
self.map_canvas = tk.Canvas(self, bg="white", width=600, height=400)
self.map_canvas.grid(row=1, column=0, columnspan=3, padx=5, pady=5)
def search_address(self):
address = self.address_var.get()
# 构造百度地图API请求URL
url = f"http://api.map.baidu.com/geocoding/v3/?address={address}&output=json&ak={AK}"
response = requests.get(url)
result = response.json()
# 解析返回结果获取经纬度
location = result["result"]["location"]
lat, lng = location["lat"], location["lng"]
# 构造静态地图API请求URL
url = f"http://api.map.baidu.com/staticimage/v2?ak={AK}¢er={lng},{lat}&width=600&height=400&zoom=16"
response = requests.get(url)
# 将返回的图片数据转换为PIL Image对象并显示在Canvas上
img = Image.open(BytesIO(response.content))
img = ImageTk.PhotoImage(img)
self.map_canvas.create_image(0, 0, anchor="nw", image=img)
self.map_canvas.image = img
if __name__ == "__main__":
root = tk.Tk()
root.title("Baidu Map View")
root.geometry("610x440+100+100")
MapView(root).pack(expand=True, fill="both")
root.mainloop()
```
这个程序会在GUI界面中显示一个输入框和一个按钮,用户可以在输入框中输入要查看的地址,然后点击按钮,程序会调用百度地图API获取该地址的经纬度,并将其作为静态地图API的参数,从而获取包含该地址位置的地图图片,并将其显示在GUI界面中。
阅读全文