English | Български
QML Map using PinchArea to zoom and MouseArea to pan
Qt Mobility’s Location plugin provides a very nice QML Map item, but currently leaves navigation up to the developer to implement. Two common navigation methods are using a swipe gesture to pan the map around and using a pinch gesture to zoom in and out.
Having not found any solid examples of how to do these two things together, I thought I would post an example of some code which implement these two features. The code uses the PinchArea [doc.qt.nokia.com] element which was introduced in Qt Quick 1.1.
I hope you find this helpful!
- import QtQuick 1.1
- import QtMobility.location 1.2
- Rectangle {
- id: pinchmap
- property double defaultLatitude: 37.69
- property double defaultLongitude: -97.33
- property int defaultZoomLevel: 7
- property alias mapType: map.mapType
- width: 640
- height: 350
- Map {
- id: map
- anchors.fill: parent
- zoomLevel: pinchmap.defaultZoomLevel
- plugin: Plugin { name: "nokia" }
- mapType: Map.StreetMap
- center: Coordinate {
- latitude: pinchmap.defaultLatitude
- longitude: pinchmap.defaultLongitude
- }
- }
- PinchArea {
- id: pincharea
- property double __oldZoom
- anchors.fill: parent
- function calcZoomDelta(zoom, percent) {
- return zoom + Math.log(percent)/Math.log(2)
- }
- onPinchStarted: {
- __oldZoom = map.zoomLevel
- }
- onPinchUpdated: {
- map.zoomLevel = calcZoomDelta(__oldZoom, pinch.scale)
- }
- onPinchFinished: {
- map.zoomLevel = calcZoomDelta(__oldZoom, pinch.scale)
- }
- }
- MouseArea {
- id: mousearea
- property bool __isPanning: false
- property int __lastX: -1
- property int __lastY: -1
- anchors.fill : parent
- onPressed: {
- __isPanning = true
- __lastX = mouse.x
- __lastY = mouse.y
- }
- onReleased: {
- __isPanning = false
- }
- onPositionChanged: {
- if (__isPanning) {
- var dx = mouse.x - __lastX
- var dy = mouse.y - __lastY
- map.pan(-dx, -dy)
- __lastX = mouse.x
- __lastY = mouse.y
- }
- }
- onCanceled: {
- __isPanning = false;
- }
- }
- }

