QML Maps with Pinch Zoom
Jump to navigation
Jump to search
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":http://doc.qt.nokia.com/4.7-snapshot/qml-pincharea.html element which was introduced in Qt Quick 1.1.
I hope you find this helpful!
<br />import QtQuick 1.1<br />import QtMobility.location 1.2
Rectangle {<br /> id: pinchmap
property double defaultLatitude: 37.69<br /> property double defaultLongitude: –97.33<br /> property int defaultZoomLevel: 7
property alias mapType: map.mapType
width: 640<br /> height: 350
Map {<br /> id: map
anchors.fill: parent<br /> zoomLevel: pinchmap.defaultZoomLevel<br /> plugin: Plugin { name: "nokia&quot; }<br /> mapType: Map.StreetMap
center: Coordinate {<br /> latitude: pinchmap.defaultLatitude<br /> longitude: pinchmap.defaultLongitude<br /> }<br /> }
PinchArea {<br /> id: pincharea
property double _''oldZoom
<br /> anchors.fill: parent
<br /> function calcZoomDelta(zoom, percent) {<br /> return zoom + Math.log(percent)/Math.log(2)<br /> }
<br /> onPinchStarted: {<br />oldZoom = map.zoomLevel<br /> }
<br /> onPinchUpdated: {<br /> map.zoomLevel = calcZoomDelta(oldZoom, pinch.scale)<br /> }
<br /> onPinchFinished: {<br /> map.zoomLevel = calcZoomDelta(oldZoom, pinch.scale)<br /> }<br /> }
<br /> MouseArea {<br /> id: mousearea
<br /> property boolisPanning: false<br /> property intlastX: –1<br /> property intlastY: –1
<br /> anchors.fill : parent
<br /> onPressed: {<br />isPanning = true<br />lastX = mouse.x<br />lastY = mouse.y<br /> }
<br /> onReleased: {<br />isPanning = false<br /> }
<br /> onPositionChanged: {<br /> if (isPanning) {<br /> var dx = mouse.x -lastX<br /> var dy = mouse.y -lastY<br /> map.pan(-dx, -dy)<br />lastX = mouse.x<br />lastY = mouse.y<br /> }<br /> }
<br /> onCanceled: {<br />''_isPanning = false;<br /> }<br /> }<br />}<br />