使用地图

地图是osgEarth的中心数据模型,是影像、高程和特征图层的存储器。

从地球文件中载入地图

渲染一张地图最简单的方法是从一个地球文件(earth file)中载入。由于osgEarth使用OpenSceneGraph插件,你可以使用这行代码:

  1. osg::Node* globe = osgDB::readNodeFile("myglobe.earth");

现在你有一个可以添加到场景图形中显示的osg::Node,这真的很简单。

这种载入地图的方法通常是一个应用程序需要做的所有事情,如果你想使用API创建地图,请往下读。

程序化创建地图

osgEarth提供一个在运行时创建地图的API。

使用API创建一幅地图的基本步骤有:

  1. 创建一个地图对象

  2. 根据你的需要在地图中添加影像和高程图层

  3. 创建一个MapNode(地图节点)来渲染地图对象

  4. 在场景图形中添加你的MapNode

你可以随时在地图中添加图层:

  1. using namespace osgEarth;
  2. using namespace osgEarth::Drivers;
  3. #include <osgEarth/Map>
  4. #include <osgEarth/MapNode>
  5. #include <osgEarthDrivers/tms/TMSOptions>
  6. #include <osgEarthDrivers/gdal/GDALOptions>
  7. using namespace osgEarth;
  8. using namespace osgEarth::Drivers;
  9. ...
  10. // Create a Map and set it to Geocentric to display a globe
  11. // 创建一幅地图并将其设置为以地球为中心来显示一个球形
  12. Map* map = new Map();
  13. // Add an imagery layer (blue marble from a TMS source)
  14. // 添加一个影像图层(TMS源中的蓝色纹理)
  15. {
  16. TMSOptions tms;
  17. tms.url() = "http://labs.metacarta.com/wms-c/Basic.py/1.0.0/satellite/";
  18. ImageLayer* layer = new ImageLayer( "NASA", tms );
  19. map->addImageLayer( layer );
  20. }
  21. // Add an elevationlayer (SRTM from a local GeoTiff file)
  22. // 添加高程图层(本地GeoTiff文件中的SRTM)
  23. {
  24. GDALOptions gdal;
  25. gdal.url() = "c:/data/srtm.tif";
  26. ElevationLayer* layer = new ElevationLayer( "SRTM", gdal );
  27. map->addElevationLayer( layer );
  28. }
  29. // Create a MapNode to render this map:
  30. //创建一个地图节点来渲染这个地图
  31. MapNode* mapNode = new MapNode( map );
  32. ...
  33. viewer->setSceneData( mapNode );

在运行时使用地图节点(MapNode)

MapNode是用来渲染Map的场景图形节点。不论你是从地球文件中载入地图或是使用API创建,你都可以在运行时得到地图以及它的MapNode来做一些改变。如果你没有准确地使用API来创建MapNode,你首先需要对MapNode进行引用才能使用。使用静态函数get

  1. // Load the map
  2. // 载入地图
  3. osg::Node* loadedModel = osgDB::readNodeFile("mymap.earth");
  4. // Find the MapNode
  5. // 寻找地图节点
  6. osgEarth::MapNode* mapNode = MapNode::get( loadedModel );

一旦对MapNode有了一个引用,就可以得到地图:

  1. // Add an OpenStreetMap image source
  2. // 添加一个开放街景影像源
  3. TMSOptions driverOpt;
  4. driverOpt.url() = "http://tile.openstreetmap.org/";
  5. driverOpt.tmsType() = "google";
  6. ImageLayerOptions layerOpt( "OSM", driverOpt );
  7. layerOpt.profile() = ProfileOptions( "global-mercator" );
  8. ImageLayer* osmLayer = new ImageLayer( layerOpt );
  9. mapNode->getMap()->addImageLayer( osmLayer );

你也可以移除或重新排列图层:

  1. // Remove a layer from the map. All other layers are repositioned accordingly
  2. // 从地图中移除一个图层。其它所有图层将重新定位
  3. mapNode->getMap()->removeImageLayer( layer );
  4. // Move a layer to position 1 in the image stack
  5. // 将图层移动到影像堆栈中的位置1
  6. mapNode->getMap()->moveImageLayer( layer, 1 );

使用图层

Map存储了ImageLayer(影像图层)和ElevationLayer(高程图层)对象,它们有一些特性可以在运行时进行调整。例如,你可以使用API来开启或关闭一个图层或者调整ImageLayer的不透明度:

  1. ImageLayer* layer;
  2. ...
  3. layer->setOpacity( 0.5 ); // makes the layer partially transparent使图层部分透明