一个用python编写的GIS程序-simple GIS

来源:互联网 发布:苏联情结 知乎 编辑:程序博客网 时间:2024/05/29 17:35

例子取自<<Learning Geospatial Analysis with Python>>

代码由两部分组成。第一部分是数据模型,第二部分是绘制数据(地图渲染)。

一、数据模型:使用python内置的列表(list),用来存储空间数据。

# DATA MODEL# All layers will have a name, 1+ points, and population countNAME = 0POINTS = 1POP = 2# Create the state layerstate = ["COLORADO", [[-109, 37], [-109, 41], [-102, 41], [-102, 37]], 5187582]# Cities layer list# city = [name, [point], population]cities = []# Add Denvercities.append(["DENVER",[-104.98, 39.74], 634265])# Add Bouldercities.append(["BOULDER",[-105.27, 40.02], 98889])# Add Durangocities.append(["DURANGO",[-107.88,37.28], 17069])
二、地图渲染

使用python Turtle 绘图模块来渲染地图。其中有一个函数用来将世界坐标转换为像素坐标。

1、首先计算地图的显示范围及设定屏幕的绘制范围

# MAP GRAPHICS RENDERINGmap_width = 800map_height = 500# State Bounding Box# Use Python min/max function to get bounding boxminx = 180maxx = -180miny = 90maxy = -90 for x,y in state[POINTS]:  if x < minx: minx = x  elif x > maxx: maxx = x  if y < miny: miny = y  elif y > maxy: maxy = y# Get earth distance on each axisdist_x = maxx - minxdist_y = maxy - miny# Scaling ratio each axis # to map points from world to screenx_ratio = map_width / dist_xy_ratio = map_height / dist_y
2、世界坐标到屏幕坐标的转换

# Function to convert lat/lon to screen coordinatesdef convert(point):  lon = point[0]  lat = point[1]  x = map_width - ((maxx - lon) * x_ratio)  y = map_height - ((maxy - lat) * y_ratio)  # Python turtle graphics start in the middle of the screen  # so we must offset the points so they are centered  x = x - (map_width/2)  y = y - (map_height/2)  return [x,y]
3、绘制地图:标注和要素图形

# Draw the statet.up()first_pixel = Nonefor point in state[POINTS]:  pixel = convert(point)  print pixel  if not first_pixel:    first_pixel = pixel  t.goto(pixel)  t.down()# Go back to the first pointt.goto(first_pixel)# Label the statet.up()t.goto([0,0])t.write(state[NAME], align="center", font=("Arial",16,"bold"))# Draw the citiesfor city in cities:  pixel = convert(city[POINTS])  t.up()  t.goto(pixel)  # Place a point for the city  t.dot(10)  # Label the city  t.write(city[NAME] + ", Pop.: " + str(city[POP]), align="left")  t.up()  # Perform an attribute query# Question: Which city has the largest population?# Write the result but make sure it's under the mapbiggest_city = max(cities, key=lambda city:city[POP])t.goto(0, -1*((map_height/2)+20))t.write("The biggest city is: " +  biggest_city[NAME])# Perform a spatial query# Question: Which is the western most city?# Write the result but make sure it's under the other questionwestern_city = min(cities, key=lambda city:city[POINTS])t.goto(0, -1*((map_height/2)+40))t.write("The western-most city is: " + western_city[NAME])  # Hide our map pent.pen(shown=False)t.done()  

三、结果








0 0
原创粉丝点击