首页 > 代码库 > 使用鼠标控制地图

使用鼠标控制地图

Tangram使用两种方式来控制地图:

  1. 使用Gesture API
  2. 使用Camera API

因为现在是在PC上控制, 因此使用了Camera API, 基本原理就是根据鼠标动作换算出camera变化量, 然后更新camera。

主要代码如下

Zoom在mouse wheelEvent里实现:

namespace Tangram {
class Map {
public:
    // Set the fractional zoom level of the view; if duration (in seconds) is provided,
    // zoom eases to the set value over the duration; calling either version of the setter
    // overrides all previous calls
    void setZoom(float _z);
    // Get the fractional zoom level of the view
    float getZoom();
};

void MapWidget::wheelEvent(QWheelEvent *event) {
    float zoom = m_map->getZoom();
    if(event->delta() > 0){
        zoom += 0.5;
    }else{
        zoom -= 0.5;
    }

    if (zoom > Max_Zoom_Level) {
        zoom = Max_Zoom_Level;
    }
    if (zoom < Min_Zoom_Level) {
        zoom = Min_Zoom_Level;
    }

    m_map->setZoom(zoom);
    update();
}
}

 

Rotate, Tilt和Pan在mouseMoveEvent里实现:

namespace Tangram {
class Map {
public:
    // Set the counter-clockwise rotation of the view in radians; 0 corresponds to
    // North pointing up; if duration (in seconds) is provided, rotation eases to the
    // the set value over the duration; calling either version of the setter overrides
    // all previous calls
    void setRotation(float _radians);
    // Get the counter-clockwise rotation of the view in radians; 0 corresponds to
    // North pointing up
    float getRotation();
// Set the tilt angle of the view in radians; 0 corresponds to straight down; // if duration (in seconds) is provided, tilt eases to the set value over the // duration; calling either version of the setter overrides all previous calls void setTilt(float _radians); void setTiltEased(float _radians, float _duration, EaseType _e = EaseType::quint); // Get the tilt angle of the view in radians; 0 corresponds to straight down float getTilt(); }; static float getTilt(QPoint p0, QPoint p1) { return p1.y() - p0.x(); } static float getRotation(QPoint p0, QPoint p1, QPoint center) { return QLineF(p1, center).angle() - QLineF(p0, center).angle(); } void MapWidget::mouseMoveEvent(QMouseEvent *event) { auto pos = event->pos(); if (m_gestureInprogress) { switch(m_gestureType) { case GESTURE_TAP: break; case GESTURE_PAN: { m_map->handlePanGesture(m_gestureStartPoint.x(), m_gestureStartPoint.y(), pos.x(), pos.y()); m_gestureStartPoint = pos; } break; case GESTURE_SHOVE:{ float currentTilt = toDegree(m_map->getTilt()); float newTilt = currentTilt + (pos.y() - m_gesturePreviousPoint.y()); if(newTilt>60){ newTilt = 60; } else if(newTilt<0) { newTilt = 0; } m_map->setTilt(toRadians(newTilt)); } break; case GESTURE_ROTATE:{ float currentRotation = m_map->getRotation(); m_map->setRotation(currentRotation + toRadians(getRotation(pos, m_gesturePreviousPoint, rect().center()))); } break; default: break; } } m_gesturePreviousPoint = pos; update(); } }

 

项目代码:

  • https://github.com/tiangles/ltdmap
  • https://github.com/tiangles/tangram-es

使用鼠标控制地图