效果图
在左上角显示当前鼠标所在点的经纬度和高度
实现原理
- 在视图中添加控件用于显示文本
- 添加事件控制器捕获鼠标坐标
添加控件
//Label
osgEarth::Util::Controls::LabelControl* mouseCoords;
// 添加视点信息控件
void addViewePointLabel();
mRoot->addChild(osgEarth::Util::Controls::ControlCanvas::get(mViewer));
osgEarth::Util::Controls::ControlCanvas* canvas = osgEarth::Util::Controls::ControlCanvas::get(mViewer);
//添加控件显示视点信息
//添加控件用于显示鼠标交点信息
mouseCoords =
new osgEarth::Util::Controls::LabelControl("test",osg::Vec4f(1.0,1.0,1.0,1.0),18.0f);
//位置
mouseCoords->setHorizAlign(osgEarth::Util::Controls::Control::ALIGN_RIGHT);
mouseCoords->setVertAlign(osgEarth::Util::Controls::Control::ALIGN_BOTTOM);
mouseCoords->setBackColor(0, 0, 0, 0.5);//背景颜色
canvas->addControl(mouseCoords);
if(labelHandler == 0 )
{
labelHandler = new LableControlEventHandler(viewCoords, mouseCoords, mapNode);
}
mViewer->addEventHandler(labelHandler);
添加事件控制器
新建类 LableControlEventHandler 继承osgGA::GUIEventHandler
class LableControlEventHandler : public osgGA::GUIEventHandler
{
public:
LableControlEventHandler(osgEarth::Util::Controls::LabelControl* mouseLabel
,osgEarth::Util::Controls::LabelControl* viewLabel
,osgEarth::MapNode* mapN);
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) override;
void setMouseLabel(const GeoPoint& coords, osg::View* view, MapNode* mapNode);
private:
//labels
osgEarth::Util::Controls::LabelControl* mouseCoords;
osgEarth::Util::Controls::LabelControl* viewCoords;
osgEarth::MapNode* mapNode;
osg::NodePath nodePath;
};
#endif // LABLECONTROLEVENTHANDLER_H
构造函数初始化参数
LableControlEventHandler::LableControlEventHandler(osgEarth::Util::Controls::LabelControl* mouseLabel
,osgEarth::Util::Controls::LabelControl* viewLabel
,osgEarth::MapNode* mapN)
{
mouseCoords = mouseLabel;
viewCoords = viewLabel;
mapNode = mapN;
nodePath.push_back((osg::Node *)mapNode->getTerrainEngine());
}
重写函数 handle(const GUIEventAdapter &ea, GUIActionAdapter &aa)
bool LableControlEventHandler::handle(const GUIEventAdapter &ea, GUIActionAdapter &aa)
{
osgViewer::Viewer *viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
if(viewer)
{
if(ea.getEventType() == ea.MOVE || ea.getEventType() == ea.DRAG)
{
osg::Vec3d world;
//qDebug()<< " fvv";
if (mapNode->getTerrain()->getWorldCoordsUnderMouse(aa.asView(), ea.getX(), ea.getY(), world))
{
GeoPoint map;
map.fromWorld(mapNode->getMapSRS(), world);
setMouseLabel(map, aa.asView(), mapNode);
}
}
}
}
return false;
}
void LableControlEventHandler::setMouseLabel(const GeoPoint &coords, osg::View *view, MapNode *mapNode)
{
char wsrc[512];
sprintf(wsrc, " lat:%.3f Lan:%.3f Height:%.3f",coords.x(), coords.y(),coords.z());
mouseCoords->setText(wsrc);
}