65.9K
CodeProject 正在变化。 阅读更多。
Home

在 OpenGL 中渲染 Shapefile

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.89/5 (13投票s)

2008 年 12 月 29 日

CPOL

2分钟阅读

viewsIcon

117204

downloadIcon

9355

使用 OpenGL 渲染 ESRI Shapefiles(.shp)

引言

ESRI shapefile 是众所周知的矢量数据格式,用于地图绘制,也称为 GIS 应用程序。 有许多开源软件,如 JUMP、SharpMap,允许用户查看 shapefile。 本文重点介绍如何在 OpenGL 控制台中渲染它们。

背景

Shapefile 以点、线和多边形的形式保存地理信息。 例如,像国家、州这样的政治边界被视为多边形 shapefile; 诸如道路、河流之类的线性特征是线 shapefile; 机场或公共汽车站有时被视为点 shapefile。

Using the Code

我假设目标受众熟悉 OpenGL,并且了解诸如在 Microsoft Visual Studio 环境中与静态或动态库链接之类的概念。

为了解析 shapefile,我使用了 Shapelib (http://shapelib.maptools.org/)。 在开头包含 shapefile.h。 通过转到“项目”>“设置”>“链接”,将 shapelib\shapelib.lib 添加到对象/库模块,从而利用 shapelib.lib

   #include "shapelib\shapefil.h"

通过传递 .shp 文件名来调用以下函数以打开 Shapefile。 该函数解析地理坐标信息并将其存储在 Vectors vPointsvLines vPolygons 中。

  //Function to Open Shapefile and parse the info 
  void OpenShapeFile(char* fileName)

SBoundingBox 是一个结构,定义为保存 shapefile 的边界框。 边界框坐标在 OpenShapeFile 函数中读取并分配为 glOrtho() 参数,这将限制显示范围到包围感兴趣区域的矩形。

 //Assign Bounding Box Coordinates of Shapefile to glOrtho()
 glOrtho(sBoundingBox.fMinX, sBoundingBox.fMaxX,
	sBoundingBox.fMinY,sBoundingBox.fMaxY,-1,1);

最后,只需设置适当的 OpenGL 基元(GL_POINTSGL_LINE_STRIPGL_LINE_LOOP)来渲染点、线或多边形类型的 shapefile。

void draw()
{
  //Render Point Shapefile glColor3f (0.0, 0.0, 1.0);
   glEnable(GL_POINT_SMOOTH) ; 
   glPointSize(5.0); 
   glBegin(GL_POINTS); 
   for(int i=0;i < vPoints.size();i++)  
   {
    glVertex2f(vPoints[i].dX,vPoints[i].dY); 
    glEnd();
   } 
   	
	//Render Line Shapefile
	glColor3f (0.0, 1.0, 0.0);
	for( i=0;i < vLines.size();i++)
	{
		glBegin(GL_LINE_STRIP);
		for(int j=0;< vLines[i].vPointList.size();j++)
		{
		  glVertex2f(vLines[i].vPointList[j].dX,vLines[i].vPointList[j].dY);
		}
		glEnd();
	}
	
	//Render Polygon Shapefile
	glColor3f(1.0,0.0, 0.0);
	for( i=0;i < vPolygons.size();i++)
	{
		glBegin(GL_LINE_LOOP);
		for(int j=0;j <vPolygons[i].vPointList.size();j++)
		{
			glVertex2f(vPolygons[i].vPointList[j].dX,
					vPolygons[i].vPointList[j].dY);
		}
		glEnd();
	}
    glFlush();  
}

输出

Sample Output- OpenGL Console

关注点

如果有人能够通过读取 .shp 文件随附的 .prj 文件中的投影信息来读取/应用/重新投影 .shp 文件,那就太好了。 如果你想尝试一下,PROJ.4 是一个开源投影库。

尝试平移和缩放功能将是一个很好的挑战。

保持纵横比是 GIS 应用程序中的一个主要功能。 我将其留给您作为另一个探索的功能。

历史

  • 2008 年 12 月 29 日:首次发布
© . All rights reserved.