Re-factored the source to use the new coordinate classes
[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 <QString>
29 #include <QStringList>
30 #include <QUrl>
31 #include <QHash>
32 #include <QHashIterator>
33 #include <QRect>
34
35 #include "common.h"
36 #include "frienditemshandler.h"
37 #include "gpslocationitem.h"
38 #include "mapcommon.h"
39 #include "mapfetcher.h"
40 #include "mapscene.h"
41 #include "mapscroller.h"
42 #include "maptile.h"
43 #include "network/networkaccessmanager.h"
44 #include "ownlocationitem.h"
45 #include "user/user.h"
46
47 #include "mapengine.h"
48
49 const int SMOOTH_CENTERING_TIME_MS = 1000;
50
51 MapEngine::MapEngine(QObject *parent)
52     : QObject(parent),
53       m_autoCenteringEnabled(false),
54       m_scrollStartedByGps(false),
55       m_smoothScrollRunning(false),
56       m_zoomedIn(false),
57       m_zoomLevel(MAP_DEFAULT_ZOOM_LEVEL),
58       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
59       /// @todo remove, automatic init to zero // m_lastAutomaticPosition(QPoint(0, 0)),
60       m_sceneCoordinate(SceneCoordinate(GeoCoordinate(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE))),
61       m_tilesGridSize(QSize(0, 0)),
62       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
63 {
64     qDebug() << __PRETTY_FUNCTION__;
65
66     m_mapScene = new MapScene(this);
67
68     m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
69     connect(this, SIGNAL(fetchImage(int, int, int)),
70             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
71     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
72             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
73     connect(m_mapFetcher, SIGNAL(error(int, int)),
74             this, SIGNAL(error(int, int)));
75
76     m_ownLocation = new OwnLocationItem();
77     m_ownLocation->hide(); // hide until first location info is received
78     m_mapScene->addItem(m_ownLocation);
79
80     m_gpsLocationItem = new GPSLocationItem();
81     m_mapScene->addItem(m_gpsLocationItem);
82
83     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
84     connect(this, SIGNAL(zoomLevelChanged(int)),
85             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
86
87     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
88             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
89
90     connect(this, SIGNAL(friendImageReady(User*)),
91             m_friendItemsHandler, SLOT(friendImageReady(User*)));
92
93     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
94             this, SLOT(friendsPositionsUpdated()));
95
96     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
97             this, SIGNAL(locationItemClicked(QList<QString>)));
98
99     m_scroller = &MapScroller::getInstance();
100
101     connect(m_scroller, SIGNAL(coordinateUpdated(SceneCoordinate)),
102             this, SLOT(setCenterPosition(SceneCoordinate)));
103
104     connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
105             this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
106 }
107
108 MapEngine::~MapEngine()
109 {
110     qDebug() << __PRETTY_FUNCTION__;
111
112     QSettings settings(DIRECTORY_NAME, FILE_NAME);
113
114     // register meta type for custom GeoCoordinate class so that saving the settings does work
115     qRegisterMetaType<GeoCoordinate>("GeoCoordinate");
116     qRegisterMetaTypeStreamOperators<GeoCoordinate>("GeoCoordinate");
117
118     settings.setValue(MAP_LAST_POSITION, QVariant::fromValue(centerGeoCoordinate()));
119     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
120 }
121
122 QRect MapEngine::calculateTileGrid(SceneCoordinate sceneCoordinate)
123 {
124     qDebug() << __PRETTY_FUNCTION__;
125
126     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
127
128     QPoint topLeft;
129     topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
130     topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
131
132     return QRect(topLeft, m_tilesGridSize);
133 }
134
135 GeoCoordinate MapEngine::centerGeoCoordinate()
136 {
137     qDebug() << __PRETTY_FUNCTION__;
138
139     return GeoCoordinate(m_sceneCoordinate);
140 }
141
142 void MapEngine::centerToCoordinates(GeoCoordinate latLonCoordinate)
143 {
144     qDebug() << __PRETTY_FUNCTION__;
145
146     scrollToPosition(SceneCoordinate(latLonCoordinate));
147 }
148
149 /// @todo remove
150 //QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
151 //{
152 //    qDebug() << __PRETTY_FUNCTION__;
153
154 //    qreal longitude = latLonCoordinate.x();
155 //    qreal latitude = latLonCoordinate.y();
156
157 //    if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
158 //        return QPoint(UNDEFINED, UNDEFINED);
159 //    if ((latitude > OSM_MAX_LATITUDE) || (latitude < OSM_MIN_LATITUDE))
160 //        return QPoint(UNDEFINED, UNDEFINED);
161
162 //    qreal z = static_cast<qreal>(MapEngine::tilesPerSide(OSM_MAX_ZOOM_LEVEL));
163
164 //    qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
165 //    qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
166 //                                / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
167
168 //    return QPointF(x * z * OSM_TILE_SIZE_X, y * z * OSM_TILE_SIZE_Y).toPoint();
169 //}
170
171 //QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
172 //{
173 //    qDebug() << __PRETTY_FUNCTION__;
174
175 //    double tileFactor = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
176 //    double xFactor = (sceneCoordinate.x() / (OSM_TILE_SIZE_X*tileFactor));
177 //    double yFactor = (sceneCoordinate.y() / (OSM_TILE_SIZE_Y*tileFactor));
178
179 //    tileFactor = 1 << zoomLevel;
180 //    double longitude = xFactor / tileFactor * 360.0 - 180;
181
182 //    double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
183 //    double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
184
185 //    return QPointF(longitude, latitude);
186 //}
187
188 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, SceneCoordinate sceneCoordinate)
189 {
190     qDebug() << __PRETTY_FUNCTION__;
191
192     int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
193     int x = static_cast<int>(sceneCoordinate.x() / (OSM_TILE_SIZE_X * pow));
194     int y = static_cast<int>(sceneCoordinate.y() / (OSM_TILE_SIZE_Y * pow));
195
196     return QPoint(x, y);
197 }
198
199 SceneCoordinate MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
200 {
201     qDebug() << __PRETTY_FUNCTION__;
202
203     int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
204     int x = tileNumber.x() * OSM_TILE_SIZE_X * pow;
205     int y = tileNumber.y() * OSM_TILE_SIZE_Y * pow;
206
207     return SceneCoordinate(x, y);
208 }
209
210 void MapEngine::disableAutoCenteringIfRequired(SceneCoordinate sceneCoordinate)
211 {
212     if (isAutoCenteringEnabled()) {
213         int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
214
215         SceneCoordinate oldPixelValue(m_lastAutomaticPosition.x() / zoomFactor,
216                                       m_lastAutomaticPosition.y() / zoomFactor);
217
218         SceneCoordinate newPixelValue(sceneCoordinate.x() / zoomFactor,
219                                       sceneCoordinate.y() / zoomFactor);
220
221         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
222             || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
223
224             emit mapScrolledManually();
225         }
226     }
227 }
228
229 void MapEngine::friendsPositionsUpdated()
230 {
231     qDebug() << __PRETTY_FUNCTION__;
232
233     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
234 }
235
236 void MapEngine::getTiles(SceneCoordinate sceneCoordinate)
237 {
238     qDebug() << __PRETTY_FUNCTION__;
239
240     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
241     updateViewTilesSceneRect();
242     m_mapScene->setTilesGrid(m_viewTilesGrid);
243
244     int topLeftX = m_viewTilesGrid.topLeft().x();
245     int topLeftY = m_viewTilesGrid.topLeft().y();
246     int bottomRightX = m_viewTilesGrid.bottomRight().x();
247     int bottomRightY = m_viewTilesGrid.bottomRight().y();
248
249     int tileMaxVal = tileMaxIndex(m_zoomLevel);
250
251     for (int x = topLeftX; x <= bottomRightX; ++x) {
252         for (int y = topLeftY; y <= bottomRightY; ++y) {
253
254             // map doesn't span in vertical direction, so y index must be inside the limits
255             if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
256                 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
257                     emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
258             }
259         }
260     }
261 }
262
263 void MapEngine::gpsPositionUpdate(GeoCoordinate position, qreal accuracy)
264 {
265     qDebug() << __PRETTY_FUNCTION__;
266
267     m_gpsLocationItem->updatePosition(SceneCoordinate(position), accuracy);
268     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
269
270     if (m_autoCenteringEnabled) {
271         m_lastAutomaticPosition = SceneCoordinate(position);
272         m_scrollStartedByGps = true;
273         scrollToPosition(m_lastAutomaticPosition);
274     }
275 }
276
277 qreal MapEngine::greatCircleDistance(GeoCoordinate firstLocation, GeoCoordinate secondLocation)
278 {
279     qDebug() << __PRETTY_FUNCTION__;
280
281     const qreal TO_RAD = (M_PI / 180);
282
283     qreal dLat = (secondLocation.latitude() - firstLocation.latitude()) * TO_RAD;
284     qreal dLon = (secondLocation.longitude() - firstLocation.longitude()) * TO_RAD;
285     qreal a = pow(sin(dLat / 2), 2)
286               + cos(firstLocation.latitude() * TO_RAD)
287                 * cos(secondLocation.latitude() * TO_RAD)
288                 * pow(sin(dLon / 2), 2);
289     qreal c = 2 * atan2(sqrt(a), sqrt(1 - a));
290
291     return (EARTH_RADIUS * c);
292 }
293
294 void MapEngine::init()
295 {
296     qDebug() << __PRETTY_FUNCTION__;
297
298     QSettings settings(DIRECTORY_NAME, FILE_NAME);
299
300     /// @todo remove
301 //    if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
302 //        == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
303 //        ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
304
305 //        startLocation = GeoCoordinate(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE);
306 //        m_zoomLevel = qBound(MAP_VIEW_MIN_ZOOM_LEVEL, MAP_DEFAULT_ZOOM_LEVEL, OSM_MAX_ZOOM_LEVEL);
307 //    } else {
308 //        m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
309 //        startLocation = settings.value(MAP_LAST_POSITION,
310 //                                       ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
311 //    }
312
313     // init can be only done if both values exists in the settings
314     if (settings.contains(MAP_LAST_POSITION) && settings.contains(MAP_LAST_ZOOMLEVEL)) {
315         qWarning() << __PRETTY_FUNCTION__ << "both settings found";
316         QVariant zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL);
317         QVariant location = settings.value(MAP_LAST_POSITION);
318         // init can be only done if we are able to convert variants into target data types
319         if (zoomLevel.canConvert<int>() && location.canConvert<GeoCoordinate>()) {
320             qWarning() << __PRETTY_FUNCTION__ << "both settings can be converted";
321             m_zoomLevel = zoomLevel.toInt();
322             m_sceneCoordinate = SceneCoordinate(location.value<GeoCoordinate>());
323         }
324     }
325
326     emit zoomLevelChanged(m_zoomLevel);
327     scrollToPosition(m_sceneCoordinate);
328 }
329
330 bool MapEngine::isAutoCenteringEnabled()
331 {
332     return m_autoCenteringEnabled;
333 }
334
335 bool MapEngine::isCenterTileChanged(SceneCoordinate sceneCoordinate)
336 {
337     qDebug() << __PRETTY_FUNCTION__;
338
339     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
340     QPoint temp = m_centerTile;
341     m_centerTile = centerTile;
342
343     return (centerTile != temp);
344 }
345
346 qreal MapEngine::sceneResolution()
347 {
348     qDebug() << __PRETTY_FUNCTION__;
349
350     const int SHIFT = 200;
351     const int KM_TO_M = 1000;
352     qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
353     GeoCoordinate centerCoordinate = centerGeoCoordinate();
354     SceneCoordinate shiftedSceneCoordinate(m_sceneCoordinate.x() + SHIFT * scale,
355                                            m_sceneCoordinate.y());
356     GeoCoordinate shiftedCoordinate(shiftedSceneCoordinate);
357     qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
358     return (dist / SHIFT);
359 }
360
361 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
362 {
363     qDebug() << __PRETTY_FUNCTION__;
364
365     // add normal tile inside the world
366     QPoint tileNumber(x, y);
367     m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
368
369     // note: add 1 so odd width is rounded up and even is rounded down
370     int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
371
372     // duplicate to east side? (don't need to duplicate over padding)
373     if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
374         QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
375         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
376     }
377
378     // duplicate to west side? (don't need to duplicate over padding)
379     if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + MAP_GRID_PADDING)) {
380         QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
381         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
382     }
383 }
384
385 int MapEngine::normalize(int value, int min, int max)
386 {
387     qDebug() << __PRETTY_FUNCTION__;
388     Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
389
390     while (value < min)
391         value += max - min + 1;
392
393     while (value > max)
394         value -= max - min + 1;
395
396     return value;
397 }
398
399 void MapEngine::receiveOwnLocation(User *user)
400 {
401     qDebug() << __PRETTY_FUNCTION__;
402
403     if(user) {
404         m_ownLocation->setPos(SceneCoordinate(user->coordinates()).toPointF());
405         if (!m_ownLocation->isVisible())
406             m_ownLocation->show();
407     } else {
408         m_ownLocation->hide();
409     }
410
411     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
412 }
413
414 QGraphicsScene* MapEngine::scene()
415 {
416     qDebug() << __PRETTY_FUNCTION__;
417
418     return m_mapScene;
419 }
420
421 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
422 {
423     qDebug() << __PRETTY_FUNCTION__;
424
425     if (m_smoothScrollRunning
426         && newState != QAbstractAnimation::Running) {
427             m_smoothScrollRunning = false;
428
429             // don't disable auto centering if current animation was stopped by new update from GPS
430             if (!m_scrollStartedByGps)
431                 disableAutoCenteringIfRequired(m_sceneCoordinate);
432     }
433
434     m_scrollStartedByGps = false;
435 }
436
437 void MapEngine::scrollToPosition(SceneCoordinate scenePosition)
438 {
439     qDebug() << __PRETTY_FUNCTION__;
440
441     m_scroller->stop();
442     m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
443     m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
444     m_scroller->setStartValue(m_sceneCoordinate.toPointF());
445     m_scroller->setEndValue(scenePosition.toPointF());
446     m_smoothScrollRunning = true;
447     m_scroller->start();
448 }
449
450 void MapEngine::setAutoCentering(bool enabled)
451 {
452     qDebug() << __PRETTY_FUNCTION__;
453
454     m_autoCenteringEnabled = enabled;
455 }
456
457 void MapEngine::setCenterPosition(SceneCoordinate scenePosition)
458 {
459     qDebug() << __PRETTY_FUNCTION__;
460
461     // jump to opposite side of the world if world horizontal limit is exceeded
462     scenePosition.setX(normalize(scenePosition.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
463
464     // don't allow vertical scene coordinates go out of the map
465     scenePosition.setY(qBound(double(OSM_MAP_MIN_PIXEL_Y),
466                               scenePosition.y(),
467                               double(OSM_MAP_MAX_PIXEL_Y)));
468
469     if (!m_smoothScrollRunning)
470         disableAutoCenteringIfRequired(scenePosition);
471
472     m_sceneCoordinate = scenePosition;
473     emit locationChanged(m_sceneCoordinate);
474
475     if (isCenterTileChanged(scenePosition)) {
476         getTiles(scenePosition);
477         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
478     }
479
480     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
481     emit newMapResolution(sceneResolution());
482 }
483
484 void MapEngine::setGPSEnabled(bool enabled)
485 {
486     qDebug() << __PRETTY_FUNCTION__;
487
488     m_gpsLocationItem->setEnabled(enabled);
489 }
490
491 void MapEngine::setZoomLevel(int newZoomLevel)
492 {
493     qDebug() << __PRETTY_FUNCTION__;
494
495     m_zoomLevel = newZoomLevel;
496     zoomed();
497 }
498
499 void MapEngine::setTilesGridSize(const QSize &viewSize)
500 {
501     qDebug() << __PRETTY_FUNCTION__;
502
503     // there must be scrolling reserve of at least half tile added to tile amount
504     // calculated from view size
505     const qreal SCROLLING_RESERVE = 0.5;
506
507     // converting scene tile to tile number does cause grid centering inaccuracy of one tile
508     const int CENTER_TILE_INACCURACY = 1;
509
510     int gridWidth = ceil(qreal(viewSize.width()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
511                     + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
512     int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
513                      + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
514
515     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
516
517     m_tilesGridSize.setHeight(gridHeight);
518     m_tilesGridSize.setWidth(gridWidth);
519 }
520
521 int MapEngine::tileMaxIndex(int zoomLevel)
522 {
523     qDebug() << __PRETTY_FUNCTION__;
524
525     // subtract one because first tile index is zero
526     return tilesPerSide(zoomLevel) - 1;
527 }
528
529 QString MapEngine::tilePath(int zoomLevel, int x, int y)
530 {
531     qDebug() << __PRETTY_FUNCTION__;
532
533     QString tilePathString(QString::number(zoomLevel) + "/");
534     tilePathString.append(QString::number(x) + "/");
535     tilePathString.append(QString::number(y));
536
537     return tilePathString;
538 }
539
540 int MapEngine::tilesPerSide(int zoomLevel)
541 {
542     return (1 << zoomLevel);
543 }
544
545 void MapEngine::updateViewTilesSceneRect()
546 {
547     qDebug() << __PRETTY_FUNCTION__;
548
549     const QPoint ONE_TILE = QPoint(1, 1);
550     const double ONE_PIXEL = 1;
551
552     SceneCoordinate topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel,
553                                                         m_viewTilesGrid.topLeft());
554
555     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
556     // of the last tile.
557     SceneCoordinate bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
558                                                             m_viewTilesGrid.bottomRight()
559                                                              + ONE_TILE);
560     bottomRight.setX(bottomRight.x() - ONE_PIXEL);
561     bottomRight.setY(bottomRight.y() - ONE_PIXEL);
562
563     m_mapScene->tilesSceneRectUpdated(QRect(topLeft.toPointF().toPoint(),
564                                             bottomRight.toPointF().toPoint()));
565 }
566
567 void MapEngine::viewResized(const QSize &size)
568 {
569     qDebug() << __PRETTY_FUNCTION__;
570
571     m_viewSize = size;
572     setTilesGridSize(m_viewSize);
573
574     emit locationChanged(m_sceneCoordinate);
575     getTiles(m_sceneCoordinate);
576     m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
577     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
578 }
579
580 void MapEngine::viewZoomFinished()
581 {
582     qDebug() << __PRETTY_FUNCTION__;
583
584     if (m_zoomedIn) {
585         m_zoomedIn = false;
586         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
587     }
588
589     if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
590         emit maxZoomLevelReached();
591     else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
592         emit minZoomLevelReached();
593 }
594
595 void MapEngine::zoomed()
596 {
597     emit zoomLevelChanged(m_zoomLevel);
598     m_mapScene->setTilesDrawingLevels(m_zoomLevel);
599     m_mapScene->setZoomLevel(m_zoomLevel);
600     getTiles(m_sceneCoordinate);
601     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
602     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
603     emit newMapResolution(sceneResolution());
604 }
605
606 void MapEngine::zoomIn()
607 {
608     qDebug() << __PRETTY_FUNCTION__;
609
610     if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
611         m_zoomLevel++;
612         m_zoomedIn = true;
613         zoomed();
614     }
615 }
616
617 void MapEngine::zoomOut()
618 {
619     qDebug() << __PRETTY_FUNCTION__;
620
621     if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {
622         m_zoomLevel--;
623         zoomed();
624     }
625 }