GDAL 搭建一个gis界面 有一个按钮可以选择本地shp文件进行加载显示在地图中 并有工具按钮可以绘制点、线、面
时间: 2024-06-12 13:06:03 浏览: 122
gis加载天地图后,显示shp文件
5星 · 资源好评率100%
等要素,同时支持编辑和保存。以下是一个简单的示例代码:
```python
from osgeo import gdal, ogr, osr
import tkinter as tk
from tkinter import filedialog
class GISInterface:
def __init__(self):
self.root = tk.Tk()
self.root.title("GIS Interface")
self.canvas = tk.Canvas(self.root, width=800, height=600)
self.canvas.pack()
self.layer = None
self.current_tool = None
# Add buttons for loading shapefile and drawing tools
self.load_button = tk.Button(self.root, text="Load Shapefile", command=self.load_shapefile)
self.load_button.pack(side="left")
self.point_button = tk.Button(self.root, text="Point", command=self.set_tool("point"))
self.point_button.pack(side="left")
self.line_button = tk.Button(self.root, text="Line", command=self.set_tool("line"))
self.line_button.pack(side="left")
self.polygon_button = tk.Button(self.root, text="Polygon", command=self.set_tool("polygon"))
self.polygon_button.pack(side="left")
self.root.mainloop()
def load_shapefile(self):
file_path = filedialog.askopenfilename(filetypes=[("Shapefile", "*.shp")])
if file_path:
driver = ogr.GetDriverByName("ESRI Shapefile")
self.layer = driver.Open(file_path).GetLayer()
self.draw_layer()
def draw_layer(self):
# Clear canvas
self.canvas.delete("all")
# Set up projection transformation
proj = self.layer.GetSpatialRef()
source_proj = osr.SpatialReference()
source_proj.ImportFromEPSG(4326) # WGS84
transform = osr.CoordinateTransformation(source_proj, proj)
# Draw features
for feature in self.layer:
geom = feature.GetGeometryRef()
geom.Transform(transform)
self.draw_feature(geom)
def draw_feature(self, geom):
if geom.GetGeometryName() == "POINT":
self.canvas.create_oval(geom.GetX()-5, geom.GetY()-5, geom.GetX()+5, geom.GetY()+5, fill="red")
elif geom.GetGeometryName() == "LINESTRING":
points = [coord for coord in geom.GetPoints()]
self.canvas.create_line(points, fill="blue")
elif geom.GetGeometryName() == "POLYGON":
points = [coord for ring in geom for coord in ring.GetPoints()]
self.canvas.create_polygon(points, fill="green")
def set_tool(self, tool):
self.current_tool = tool
def on_canvas_click(self, event):
if self.current_tool == "point":
self.draw_point(event)
elif self.current_tool == "line":
self.draw_line(event)
elif self.current_tool == "polygon":
self.draw_polygon(event)
def draw_point(self, event):
x, y = event.x, event.y
self.canvas.create_oval(x-5, y-5, x+5, y+5, fill="red")
def draw_line(self, event):
pass # TODO
def draw_polygon(self, event):
pass # TODO
if __name__ == "__main__":
gis = GISInterface()
```
此代码是一个简单的GIS界面,它使用GDAL库加载本地的shapefile文件,并在地图上绘制要素。它还提供了几个绘制工具按钮,包括点、线和面。用户可以选择一个工具并在单击地图时使用它。这个代码还有一些需要完善的地方,例如绘制线和面的功能。
阅读全文