Draw direction indicator triangle only when GPS location item is not visible
[situare] / src / map / mapengine.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5        Sami Rämö - sami.ramo@ixonos.com
6        Jussi Laitinen - jussi.laitinen@ixonos.com
7        Pekka Nissinen - pekka.nissinen@ixonos.com
8        Ville Tiensuu - ville.tiensuu@ixonos.com
9        Henri Lampela - henri.lampela@ixonos.com
10
11    Situare is free software; you can redistribute it and/or
12    modify it under the terms of the GNU General Public License
13    version 2 as published by the Free Software Foundation.
14
15    Situare is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with Situare; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
23    USA.
24 */
25
26 #include <QtAlgorithms>
27 #include <QDebug>
28 #include <QGraphicsView>
29 #include <QString>
30 #include <QStringList>
31 #include <QUrl>
32 #include <QHash>
33 #include <QHashIterator>
34 #include <QRect>
35
36 #include "common.h"
37 #include "frienditemshandler.h"
38 #include "gpslocationitem.h"
39 #include "mapcommon.h"
40 #include "mapfetcher.h"
41 #include "maprouteitem.h"
42 #include "mapscene.h"
43 #include "mapscroller.h"
44 #include "maptile.h"
45 #include "network/networkaccessmanager.h"
46 #include "ownlocationitem.h"
47 #include "user/user.h"
48
49 #include "mapengine.h"
50
51 const int SMOOTH_CENTERING_TIME_MS = 1000;
52
53 MapEngine::MapEngine(QObject *parent)
54     : QObject(parent),
55       m_autoCenteringEnabled(false),
56       m_scrollStartedByGps(false),
57       m_smoothScrollRunning(false),
58       m_zoomedIn(false),
59       m_zoomLevel(MAP_DEFAULT_ZOOM_LEVEL),
60       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
61       m_sceneCoordinate(SceneCoordinate(GeoCoordinate(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE))),
62       m_tilesGridSize(QSize(0, 0)),
63       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT)),
64       m_mapRouteItem(0)
65 {
66     qDebug() << __PRETTY_FUNCTION__;
67
68     m_mapScene = new MapScene(this);
69
70     m_mapFetcher = new MapFetcher(new NetworkAccessManager(this), this);
71     connect(this, SIGNAL(fetchImage(int, int, int)),
72             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
73     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
74             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
75     connect(m_mapFetcher, SIGNAL(error(int, int)),
76             this, SIGNAL(error(int, int)));
77
78     m_ownLocation = new OwnLocationItem();
79     m_ownLocation->hide(); // hide until first location info is received
80     m_mapScene->addItem(m_ownLocation);
81
82     m_gpsLocationItem = new GPSLocationItem();
83     m_mapScene->addItem(m_gpsLocationItem);
84
85     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
86     connect(this, SIGNAL(zoomLevelChanged(int)),
87             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
88
89     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
90             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
91
92     connect(this, SIGNAL(friendImageReady(User*)),
93             m_friendItemsHandler, SLOT(friendImageReady(User*)));
94
95     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
96             this, SLOT(friendsPositionsUpdated()));
97
98     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
99             this, SIGNAL(locationItemClicked(QList<QString>)));
100
101     m_scroller = &MapScroller::getInstance();
102
103     connect(m_scroller, SIGNAL(coordinateUpdated(SceneCoordinate)),
104             this, SLOT(setCenterPosition(SceneCoordinate)));
105
106     connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
107             this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
108 }
109
110 MapEngine::~MapEngine()
111 {
112     qDebug() << __PRETTY_FUNCTION__;
113
114     QSettings settings(DIRECTORY_NAME, FILE_NAME);
115
116     settings.setValue(MAP_LAST_POSITION, QVariant::fromValue(centerGeoCoordinate()));
117     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
118 }
119
120 QRect MapEngine::calculateTileGrid(SceneCoordinate coordinate)
121 {
122     qDebug() << __PRETTY_FUNCTION__;
123
124     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
125
126     QPoint topLeft;
127     topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
128     topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
129
130     return QRect(topLeft, m_tilesGridSize);
131 }
132
133 void MapEngine::centerAndZoomTo(QRect rect)
134 {
135     const int MARGIN_HORIZONTAL = 50;
136     const int MARGIN_VERTICAL = 5;
137
138     // calculate the usable size of the view
139     int viewUsableHeight = m_viewSize.height() - 2 * MARGIN_VERTICAL;
140     int viewUsableWidth = m_viewSize.width() - 2 * MARGIN_HORIZONTAL;
141
142     // calculate how many levels must be zoomed out from the closest zoom level to get the rect
143     // fit inside the usable view area
144     int shift = 0;
145     while ((rect.height() > (viewUsableHeight * (1 << shift)))
146            || (rect.width() > (viewUsableWidth * (1 << shift))))
147         shift++;
148
149     scrollToPosition(SceneCoordinate(double(rect.center().x()), double(rect.center().y())));
150
151     int zoomLevel = qBound(OSM_MIN_ZOOM_LEVEL, OSM_MAX_ZOOM_LEVEL - shift, OSM_MAX_ZOOM_LEVEL);
152     setZoomLevel(zoomLevel);
153 }
154
155 GeoCoordinate MapEngine::centerGeoCoordinate()
156 {
157     qDebug() << __PRETTY_FUNCTION__;
158
159     return GeoCoordinate(m_sceneCoordinate);
160 }
161
162 void MapEngine::centerToCoordinates(GeoCoordinate coordinate)
163 {
164     qDebug() << __PRETTY_FUNCTION__;
165
166     scrollToPosition(SceneCoordinate(coordinate));
167 }
168
169 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, SceneCoordinate coordinate)
170 {
171     qDebug() << __PRETTY_FUNCTION__;
172
173     int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
174     int x = static_cast<int>(coordinate.x() / (OSM_TILE_SIZE_X * pow));
175     int y = static_cast<int>(coordinate.y() / (OSM_TILE_SIZE_Y * pow));
176
177     return QPoint(x, y);
178 }
179
180 SceneCoordinate MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
181 {
182     qDebug() << __PRETTY_FUNCTION__;
183
184     int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
185     int x = tileNumber.x() * OSM_TILE_SIZE_X * pow;
186     int y = tileNumber.y() * OSM_TILE_SIZE_Y * pow;
187
188     return SceneCoordinate(x, y);
189 }
190
191 QRectF MapEngine::currentViewSceneRect() const
192 {
193     qDebug() << __PRETTY_FUNCTION__;
194
195     const QPoint ONE_PIXEL = QPoint(1, 1);
196
197     QGraphicsView *view = m_mapScene->views().at(0);
198     QPointF sceneTopLeft = view->mapToScene(0, 0);
199     QPoint viewBottomRight = QPoint(view->size().width(), view->size().height()) - ONE_PIXEL;
200     QPointF sceneBottomRight = view->mapToScene(viewBottomRight);
201
202     return QRectF(sceneTopLeft, sceneBottomRight);
203 }
204
205 void MapEngine::disableAutoCenteringIfRequired(SceneCoordinate coordinate)
206 {
207     if (isAutoCenteringEnabled()) {
208         int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
209
210         SceneCoordinate oldPixelValue(m_lastAutomaticPosition.x() / zoomFactor,
211                                       m_lastAutomaticPosition.y() / zoomFactor);
212
213         SceneCoordinate newPixelValue(coordinate.x() / zoomFactor,
214                                       coordinate.y() / zoomFactor);
215
216         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
217             || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
218
219             emit mapScrolledManually();
220         }
221     }
222 }
223
224 void MapEngine::friendsPositionsUpdated()
225 {
226     qDebug() << __PRETTY_FUNCTION__;
227
228     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
229 }
230
231 void MapEngine::getTiles(SceneCoordinate coordinate)
232 {
233     qDebug() << __PRETTY_FUNCTION__;
234
235     m_viewTilesGrid = calculateTileGrid(coordinate);
236     updateViewTilesSceneRect();
237     m_mapScene->setTilesGrid(m_viewTilesGrid);
238
239     int topLeftX = m_viewTilesGrid.topLeft().x();
240     int topLeftY = m_viewTilesGrid.topLeft().y();
241     int bottomRightX = m_viewTilesGrid.bottomRight().x();
242     int bottomRightY = m_viewTilesGrid.bottomRight().y();
243
244     int tileMaxVal = tileMaxIndex(m_zoomLevel);
245
246     for (int x = topLeftX; x <= bottomRightX; ++x) {
247         for (int y = topLeftY; y <= bottomRightY; ++y) {
248
249             // map doesn't span in vertical direction, so y index must be inside the limits
250             if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
251                 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
252                     emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
253             }
254         }
255     }
256 }
257
258 void MapEngine::gpsPositionUpdate(GeoCoordinate position, qreal accuracy)
259 {
260     qDebug() << __PRETTY_FUNCTION__;
261
262     m_gpsLocationItem->updatePosition(SceneCoordinate(position), accuracy);
263     m_gpsPosition = position;
264     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
265
266     if (m_autoCenteringEnabled) {
267         m_lastAutomaticPosition = SceneCoordinate(position);
268         m_scrollStartedByGps = true;
269         scrollToPosition(m_lastAutomaticPosition);
270     }
271
272     updateDirectionIndicator();
273 }
274
275 qreal MapEngine::greatCircleDistance(GeoCoordinate firstLocation, GeoCoordinate secondLocation)
276 {
277     qDebug() << __PRETTY_FUNCTION__;
278
279     const qreal TO_RAD = (M_PI / 180);
280
281     qreal dLat = (secondLocation.latitude() - firstLocation.latitude()) * TO_RAD;
282     qreal dLon = (secondLocation.longitude() - firstLocation.longitude()) * TO_RAD;
283     qreal a = pow(sin(dLat / 2), 2)
284               + cos(firstLocation.latitude() * TO_RAD)
285                 * cos(secondLocation.latitude() * TO_RAD)
286                 * pow(sin(dLon / 2), 2);
287     qreal c = 2 * atan2(sqrt(a), sqrt(1 - a));
288
289     return (EARTH_RADIUS * c);
290 }
291
292 void MapEngine::init()
293 {
294     qDebug() << __PRETTY_FUNCTION__;
295
296     QSettings settings(DIRECTORY_NAME, FILE_NAME);
297
298     // init can be only done if both values exists in the settings
299     if (settings.contains(MAP_LAST_POSITION) && settings.contains(MAP_LAST_ZOOMLEVEL)) {
300         QVariant zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL);
301         QVariant location = settings.value(MAP_LAST_POSITION);
302
303         // also the init can be only done if we are able to convert variants into target data types
304         if (zoomLevel.canConvert<int>() && location.canConvert<GeoCoordinate>()) {
305             m_zoomLevel = zoomLevel.toInt();
306             m_sceneCoordinate = SceneCoordinate(location.value<GeoCoordinate>());
307         }
308     }
309
310     // emit zoom level and center coordinate so that all parts of the map system gets initialized
311     // NOTE: emit is also done even if we weren't able to read initial valuef from the settings
312     //       so that the default values set in the constructor are used
313     emit zoomLevelChanged(m_zoomLevel);
314     scrollToPosition(m_sceneCoordinate);
315 }
316
317 bool MapEngine::isAutoCenteringEnabled()
318 {
319     return m_autoCenteringEnabled;
320 }
321
322 bool MapEngine::isCenterTileChanged(SceneCoordinate coordinate)
323 {
324     qDebug() << __PRETTY_FUNCTION__;
325
326     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
327     QPoint temp = m_centerTile;
328     m_centerTile = centerTile;
329
330     return (centerTile != temp);
331 }
332
333 qreal MapEngine::sceneResolution()
334 {
335     qDebug() << __PRETTY_FUNCTION__;
336
337     const int SHIFT = 200;
338     const int KM_TO_M = 1000;
339     qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
340     GeoCoordinate centerCoordinate = centerGeoCoordinate();
341     SceneCoordinate shiftedSceneCoordinate(m_sceneCoordinate.x() + SHIFT * scale,
342                                            m_sceneCoordinate.y());
343     GeoCoordinate shiftedCoordinate(shiftedSceneCoordinate);
344     qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
345     return (dist / SHIFT);
346 }
347
348 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
349 {
350     qDebug() << __PRETTY_FUNCTION__;
351
352     // add normal tile inside the world
353     QPoint tileNumber(x, y);
354     m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
355
356     // note: add 1 so odd width is rounded up and even is rounded down
357     int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
358
359     // duplicate to east side? (don't need to duplicate over padding)
360     if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
361         QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
362         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
363     }
364
365     // duplicate to west side? (don't need to duplicate over padding)
366     if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + MAP_GRID_PADDING)) {
367         QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
368         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
369     }
370 }
371
372 int MapEngine::normalize(int value, int min, int max)
373 {
374     qDebug() << __PRETTY_FUNCTION__;
375     Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
376
377     while (value < min)
378         value += max - min + 1;
379
380     while (value > max)
381         value -= max - min + 1;
382
383     return value;
384 }
385
386 void MapEngine::receiveOwnLocation(User *user)
387 {
388     qDebug() << __PRETTY_FUNCTION__;
389
390     if(user) {
391         m_ownLocation->setPos(SceneCoordinate(user->coordinates()).toPointF());
392         if (!m_ownLocation->isVisible())
393             m_ownLocation->show();
394     } else {
395         m_ownLocation->hide();
396     }
397
398     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
399 }
400
401 QGraphicsScene* MapEngine::scene()
402 {
403     qDebug() << __PRETTY_FUNCTION__;
404
405     return m_mapScene;
406 }
407
408 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
409 {
410     qDebug() << __PRETTY_FUNCTION__;
411
412     if (m_smoothScrollRunning
413         && newState != QAbstractAnimation::Running) {
414             m_smoothScrollRunning = false;
415
416             // don't disable auto centering if current animation was stopped by new update from GPS
417             if (!m_scrollStartedByGps)
418                 disableAutoCenteringIfRequired(m_sceneCoordinate);
419     }
420
421     m_scrollStartedByGps = false;
422 }
423
424 void MapEngine::scrollToPosition(SceneCoordinate coordinate)
425 {
426     qDebug() << __PRETTY_FUNCTION__;
427
428     m_scroller->stop();
429     m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
430     m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
431     m_scroller->setStartValue(m_sceneCoordinate);
432     m_scroller->setEndValue(coordinate);
433     m_smoothScrollRunning = true;
434     m_scroller->start();
435 }
436
437 void MapEngine::setAutoCentering(bool enabled)
438 {
439     qDebug() << __PRETTY_FUNCTION__;
440
441     m_autoCenteringEnabled = enabled;
442 }
443
444 void MapEngine::setCenterPosition(SceneCoordinate coordinate)
445 {
446     qDebug() << __PRETTY_FUNCTION__;
447
448     // jump to opposite side of the world if world horizontal limit is exceeded
449     coordinate.setX(normalize(coordinate.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
450
451     // don't allow vertical scene coordinates go out of the map
452     coordinate.setY(qBound(double(OSM_MAP_MIN_PIXEL_Y),
453                               coordinate.y(),
454                               double(OSM_MAP_MAX_PIXEL_Y)));
455
456     if (!m_smoothScrollRunning)
457         disableAutoCenteringIfRequired(coordinate);
458
459     m_sceneCoordinate = coordinate;
460     emit locationChanged(m_sceneCoordinate);
461
462     if (isCenterTileChanged(coordinate)) {
463         getTiles(coordinate);
464         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
465     }
466
467     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
468     emit newMapResolution(sceneResolution());
469
470     updateDirectionIndicator();
471 }
472
473 void MapEngine::setGPSEnabled(bool enabled)
474 {
475     qDebug() << __PRETTY_FUNCTION__;
476
477     m_gpsLocationItem->setEnabled(enabled);
478 }
479
480 void MapEngine::setRoute(Route &route)
481 {
482     qDebug() << __PRETTY_FUNCTION__;
483
484     m_route = route;
485
486     qDebug() << __PRETTY_FUNCTION__ << "from:" << m_route.startPointName();
487     qDebug() << __PRETTY_FUNCTION__ << "to:" << m_route.endPointName();
488     qDebug() << __PRETTY_FUNCTION__ << "distance:" << m_route.totalDistance();
489     qDebug() << __PRETTY_FUNCTION__ << "estimated time:" << m_route.totalTime();
490
491     foreach (GeoCoordinate point, m_route.geometryPoints())
492         qDebug() << __PRETTY_FUNCTION__ << "geometry point:" << point;
493
494     foreach (RouteSegment segment, m_route.segments()) {
495         qDebug() << __PRETTY_FUNCTION__ << "segment:" << segment.instruction();
496     }
497
498     // delete old route track (if exists)
499     if (m_mapRouteItem) {
500         m_mapScene->removeItem(m_mapRouteItem);
501         delete m_mapRouteItem;
502     }
503
504     // create new route track
505     m_mapRouteItem = new MapRouteItem(&m_route);
506     m_mapScene->addItem(m_mapRouteItem);
507
508     centerAndZoomTo(m_mapRouteItem->boundingRect().toRect());
509 }
510
511 void MapEngine::setZoomLevel(int newZoomLevel)
512 {
513     qDebug() << __PRETTY_FUNCTION__;
514
515     m_zoomLevel = newZoomLevel;
516     zoomed();
517 }
518
519 void MapEngine::setTilesGridSize(const QSize &viewSize)
520 {
521     qDebug() << __PRETTY_FUNCTION__;
522
523     // there must be scrolling reserve of at least half tile added to tile amount
524     // calculated from view size
525     const qreal SCROLLING_RESERVE = 0.5;
526
527     // converting scene tile to tile number does cause grid centering inaccuracy of one tile
528     const int CENTER_TILE_INACCURACY = 1;
529
530     int gridWidth = ceil(qreal(viewSize.width()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
531                     + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
532     int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
533                      + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
534
535     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
536
537     m_tilesGridSize.setHeight(gridHeight);
538     m_tilesGridSize.setWidth(gridWidth);
539 }
540
541 int MapEngine::tileMaxIndex(int zoomLevel)
542 {
543     qDebug() << __PRETTY_FUNCTION__;
544
545     // subtract one because first tile index is zero
546     return tilesPerSide(zoomLevel) - 1;
547 }
548
549 QString MapEngine::tilePath(int zoomLevel, int x, int y)
550 {
551     qDebug() << __PRETTY_FUNCTION__;
552
553     QString tilePathString(QString::number(zoomLevel) + "/");
554     tilePathString.append(QString::number(x) + "/");
555     tilePathString.append(QString::number(y));
556
557     return tilePathString;
558 }
559
560 int MapEngine::tilesPerSide(int zoomLevel)
561 {
562     return (1 << zoomLevel);
563 }
564
565 void MapEngine::updateDirectionIndicator()
566 {
567     qDebug() << __PRETTY_FUNCTION__;
568
569     /// @todo implement distance calculation
570     qreal distance = 0;
571
572     qreal direction = m_sceneCoordinate.azimuthTo(SceneCoordinate(m_gpsPosition));
573
574     // direction indicator triangle should be drawn only if the gps location item is not currently
575     // visible on the view
576     bool drawDirectionIndicatorTriangle = true;
577     if (currentViewSceneRect().contains(m_gpsLocationItem->pos()))
578         drawDirectionIndicatorTriangle = false;
579
580     emit directionIndicatorValuesUpdate(direction, distance, drawDirectionIndicatorTriangle);
581 }
582
583 void MapEngine::updateViewTilesSceneRect()
584 {
585     qDebug() << __PRETTY_FUNCTION__;
586
587     const QPoint ONE_TILE = QPoint(1, 1);
588     const double ONE_PIXEL = 1;
589
590     SceneCoordinate topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel,
591                                                         m_viewTilesGrid.topLeft());
592
593     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
594     // of the last tile.
595     SceneCoordinate bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
596                                                             m_viewTilesGrid.bottomRight()
597                                                              + ONE_TILE);
598     bottomRight.setX(bottomRight.x() - ONE_PIXEL);
599     bottomRight.setY(bottomRight.y() - ONE_PIXEL);
600
601     m_mapScene->tilesSceneRectUpdated(QRect(topLeft.toPointF().toPoint(),
602                                             bottomRight.toPointF().toPoint()));
603 }
604
605 void MapEngine::viewResized(const QSize &size)
606 {
607     qDebug() << __PRETTY_FUNCTION__;
608
609     m_viewSize = size;
610     setTilesGridSize(m_viewSize);
611
612     emit locationChanged(m_sceneCoordinate);
613     getTiles(m_sceneCoordinate);
614     m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
615     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
616 }
617
618 void MapEngine::viewZoomFinished()
619 {
620     qDebug() << __PRETTY_FUNCTION__;
621
622     if (m_zoomedIn) {
623         m_zoomedIn = false;
624         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
625     }
626
627     if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
628         emit maxZoomLevelReached();
629     else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
630         emit minZoomLevelReached();
631 }
632
633 void MapEngine::zoomed()
634 {
635     emit zoomLevelChanged(m_zoomLevel);
636     m_mapScene->setTilesDrawingLevels(m_zoomLevel);
637     m_mapScene->setZoomLevel(m_zoomLevel);
638     getTiles(m_sceneCoordinate);
639     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
640     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
641     emit newMapResolution(sceneResolution());
642 }
643
644 void MapEngine::zoomIn()
645 {
646     qDebug() << __PRETTY_FUNCTION__;
647
648     if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
649         m_zoomLevel++;
650         m_zoomedIn = true;
651         zoomed();
652     }
653 }
654
655 void MapEngine::zoomOut()
656 {
657     qDebug() << __PRETTY_FUNCTION__;
658
659     if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {
660         m_zoomLevel--;
661         zoomed();
662     }
663 }