2 Situare - A location system for Facebook
3 Copyright (C) 2010 Ixonos Plc. Authors:
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
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.
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.
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,
26 #include <QtAlgorithms>
29 #include <QStringList>
32 #include <QHashIterator>
36 #include "frienditemshandler.h"
37 #include "gpslocationitem.h"
38 #include "mapcommon.h"
39 #include "mapfetcher.h"
41 #include "mapscroller.h"
43 #include "network/networkaccessmanager.h"
44 #include "ownlocationitem.h"
45 #include "user/user.h"
47 #include "mapengine.h"
49 const int SMOOTH_CENTERING_TIME_MS = 1000;
51 MapEngine::MapEngine(QObject *parent)
53 m_autoCenteringEnabled(false),
54 m_scrollStartedByGps(false),
55 m_smoothScrollRunning(false),
57 m_zoomLevel(MAP_DEFAULT_ZOOM_LEVEL),
58 m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
59 m_sceneCoordinate(SceneCoordinate(GeoCoordinate(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE))),
60 m_tilesGridSize(QSize(0, 0)),
61 m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
63 qDebug() << __PRETTY_FUNCTION__;
65 m_mapScene = new MapScene(this);
67 m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
68 connect(this, SIGNAL(fetchImage(int, int, int)),
69 m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
70 connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
71 this, SLOT(mapImageReceived(int, int, int, QPixmap)));
72 connect(m_mapFetcher, SIGNAL(error(int, int)),
73 this, SIGNAL(error(int, int)));
75 m_ownLocation = new OwnLocationItem();
76 m_ownLocation->hide(); // hide until first location info is received
77 m_mapScene->addItem(m_ownLocation);
79 m_gpsLocationItem = new GPSLocationItem();
80 m_mapScene->addItem(m_gpsLocationItem);
82 m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
83 connect(this, SIGNAL(zoomLevelChanged(int)),
84 m_friendItemsHandler, SLOT(refactorFriendItems(int)));
86 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
87 m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
89 connect(this, SIGNAL(friendImageReady(User*)),
90 m_friendItemsHandler, SLOT(friendImageReady(User*)));
92 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
93 this, SLOT(friendsPositionsUpdated()));
95 connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
96 this, SIGNAL(locationItemClicked(QList<QString>)));
98 m_scroller = &MapScroller::getInstance();
100 connect(m_scroller, SIGNAL(coordinateUpdated(SceneCoordinate)),
101 this, SLOT(setCenterPosition(SceneCoordinate)));
103 connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
104 this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
107 MapEngine::~MapEngine()
109 qDebug() << __PRETTY_FUNCTION__;
111 QSettings settings(DIRECTORY_NAME, FILE_NAME);
113 settings.setValue(MAP_LAST_POSITION, QVariant::fromValue(centerGeoCoordinate()));
114 settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
117 QRect MapEngine::calculateTileGrid(SceneCoordinate coordinate)
119 qDebug() << __PRETTY_FUNCTION__;
121 QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
124 topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
125 topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
127 return QRect(topLeft, m_tilesGridSize);
130 GeoCoordinate MapEngine::centerGeoCoordinate()
132 qDebug() << __PRETTY_FUNCTION__;
134 return GeoCoordinate(m_sceneCoordinate);
137 void MapEngine::centerToCoordinates(GeoCoordinate coordinate)
139 qDebug() << __PRETTY_FUNCTION__;
141 scrollToPosition(SceneCoordinate(coordinate));
144 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, SceneCoordinate coordinate)
146 qDebug() << __PRETTY_FUNCTION__;
148 int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
149 int x = static_cast<int>(coordinate.x() / (OSM_TILE_SIZE_X * pow));
150 int y = static_cast<int>(coordinate.y() / (OSM_TILE_SIZE_Y * pow));
155 SceneCoordinate MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
157 qDebug() << __PRETTY_FUNCTION__;
159 int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
160 int x = tileNumber.x() * OSM_TILE_SIZE_X * pow;
161 int y = tileNumber.y() * OSM_TILE_SIZE_Y * pow;
163 return SceneCoordinate(x, y);
166 void MapEngine::disableAutoCenteringIfRequired(SceneCoordinate coordinate)
168 if (isAutoCenteringEnabled()) {
169 int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
171 SceneCoordinate oldPixelValue(m_lastAutomaticPosition.x() / zoomFactor,
172 m_lastAutomaticPosition.y() / zoomFactor);
174 SceneCoordinate newPixelValue(coordinate.x() / zoomFactor,
175 coordinate.y() / zoomFactor);
177 if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
178 || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
180 emit mapScrolledManually();
185 void MapEngine::friendsPositionsUpdated()
187 qDebug() << __PRETTY_FUNCTION__;
189 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
192 void MapEngine::getTiles(SceneCoordinate coordinate)
194 qDebug() << __PRETTY_FUNCTION__;
196 m_viewTilesGrid = calculateTileGrid(coordinate);
197 updateViewTilesSceneRect();
198 m_mapScene->setTilesGrid(m_viewTilesGrid);
200 int topLeftX = m_viewTilesGrid.topLeft().x();
201 int topLeftY = m_viewTilesGrid.topLeft().y();
202 int bottomRightX = m_viewTilesGrid.bottomRight().x();
203 int bottomRightY = m_viewTilesGrid.bottomRight().y();
205 int tileMaxVal = tileMaxIndex(m_zoomLevel);
207 for (int x = topLeftX; x <= bottomRightX; ++x) {
208 for (int y = topLeftY; y <= bottomRightY; ++y) {
210 // map doesn't span in vertical direction, so y index must be inside the limits
211 if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
212 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
213 emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
219 void MapEngine::gpsPositionUpdate(GeoCoordinate position, qreal accuracy)
221 qDebug() << __PRETTY_FUNCTION__;
223 m_gpsLocationItem->updatePosition(SceneCoordinate(position), accuracy);
224 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
226 if (m_autoCenteringEnabled) {
227 m_lastAutomaticPosition = SceneCoordinate(position);
228 m_scrollStartedByGps = true;
229 scrollToPosition(m_lastAutomaticPosition);
233 qreal MapEngine::greatCircleDistance(GeoCoordinate firstLocation, GeoCoordinate secondLocation)
235 qDebug() << __PRETTY_FUNCTION__;
237 const qreal TO_RAD = (M_PI / 180);
239 qreal dLat = (secondLocation.latitude() - firstLocation.latitude()) * TO_RAD;
240 qreal dLon = (secondLocation.longitude() - firstLocation.longitude()) * TO_RAD;
241 qreal a = pow(sin(dLat / 2), 2)
242 + cos(firstLocation.latitude() * TO_RAD)
243 * cos(secondLocation.latitude() * TO_RAD)
244 * pow(sin(dLon / 2), 2);
245 qreal c = 2 * atan2(sqrt(a), sqrt(1 - a));
247 return (EARTH_RADIUS * c);
250 void MapEngine::init()
252 qDebug() << __PRETTY_FUNCTION__;
254 QSettings settings(DIRECTORY_NAME, FILE_NAME);
256 // init can be only done if both values exists in the settings
257 if (settings.contains(MAP_LAST_POSITION) && settings.contains(MAP_LAST_ZOOMLEVEL)) {
258 QVariant zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL);
259 QVariant location = settings.value(MAP_LAST_POSITION);
261 // also the init can be only done if we are able to convert variants into target data types
262 if (zoomLevel.canConvert<int>() && location.canConvert<GeoCoordinate>()) {
263 m_zoomLevel = zoomLevel.toInt();
264 m_sceneCoordinate = SceneCoordinate(location.value<GeoCoordinate>());
268 // emit zoom level and center coordinate so that all parts of the map system gets initialized
269 // NOTE: emit is also done even if we weren't able to read initial valuef from the settings
270 // so that the default values set in the constructor are used
271 emit zoomLevelChanged(m_zoomLevel);
272 scrollToPosition(m_sceneCoordinate);
275 bool MapEngine::isAutoCenteringEnabled()
277 return m_autoCenteringEnabled;
280 bool MapEngine::isCenterTileChanged(SceneCoordinate coordinate)
282 qDebug() << __PRETTY_FUNCTION__;
284 QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
285 QPoint temp = m_centerTile;
286 m_centerTile = centerTile;
288 return (centerTile != temp);
291 qreal MapEngine::sceneResolution()
293 qDebug() << __PRETTY_FUNCTION__;
295 const int SHIFT = 200;
296 const int KM_TO_M = 1000;
297 qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
298 GeoCoordinate centerCoordinate = centerGeoCoordinate();
299 SceneCoordinate shiftedSceneCoordinate(m_sceneCoordinate.x() + SHIFT * scale,
300 m_sceneCoordinate.y());
301 GeoCoordinate shiftedCoordinate(shiftedSceneCoordinate);
302 qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
303 return (dist / SHIFT);
306 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
308 qDebug() << __PRETTY_FUNCTION__;
310 // add normal tile inside the world
311 QPoint tileNumber(x, y);
312 m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
314 // note: add 1 so odd width is rounded up and even is rounded down
315 int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
317 // duplicate to east side? (don't need to duplicate over padding)
318 if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
319 QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
320 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
323 // duplicate to west side? (don't need to duplicate over padding)
324 if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + MAP_GRID_PADDING)) {
325 QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
326 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
330 int MapEngine::normalize(int value, int min, int max)
332 qDebug() << __PRETTY_FUNCTION__;
333 Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
336 value += max - min + 1;
339 value -= max - min + 1;
344 void MapEngine::receiveOwnLocation(User *user)
346 qDebug() << __PRETTY_FUNCTION__;
349 m_ownLocation->setPos(SceneCoordinate(user->coordinates()).toPointF());
350 if (!m_ownLocation->isVisible())
351 m_ownLocation->show();
353 m_ownLocation->hide();
356 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
359 QGraphicsScene* MapEngine::scene()
361 qDebug() << __PRETTY_FUNCTION__;
366 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
368 qDebug() << __PRETTY_FUNCTION__;
370 if (m_smoothScrollRunning
371 && newState != QAbstractAnimation::Running) {
372 m_smoothScrollRunning = false;
374 // don't disable auto centering if current animation was stopped by new update from GPS
375 if (!m_scrollStartedByGps)
376 disableAutoCenteringIfRequired(m_sceneCoordinate);
379 m_scrollStartedByGps = false;
382 void MapEngine::scrollToPosition(SceneCoordinate coordinate)
384 qDebug() << __PRETTY_FUNCTION__;
387 m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
388 m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
389 m_scroller->setStartValue(m_sceneCoordinate);
390 m_scroller->setEndValue(coordinate);
391 m_smoothScrollRunning = true;
395 void MapEngine::setAutoCentering(bool enabled)
397 qDebug() << __PRETTY_FUNCTION__;
399 m_autoCenteringEnabled = enabled;
402 void MapEngine::setCenterPosition(SceneCoordinate coordinate)
404 qDebug() << __PRETTY_FUNCTION__;
406 // jump to opposite side of the world if world horizontal limit is exceeded
407 coordinate.setX(normalize(coordinate.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
409 // don't allow vertical scene coordinates go out of the map
410 coordinate.setY(qBound(double(OSM_MAP_MIN_PIXEL_Y),
412 double(OSM_MAP_MAX_PIXEL_Y)));
414 if (!m_smoothScrollRunning)
415 disableAutoCenteringIfRequired(coordinate);
417 m_sceneCoordinate = coordinate;
418 emit locationChanged(m_sceneCoordinate);
420 if (isCenterTileChanged(coordinate)) {
421 getTiles(coordinate);
422 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
425 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
426 emit newMapResolution(sceneResolution());
429 void MapEngine::setGPSEnabled(bool enabled)
431 qDebug() << __PRETTY_FUNCTION__;
433 m_gpsLocationItem->setEnabled(enabled);
436 void MapEngine::setZoomLevel(int newZoomLevel)
438 qDebug() << __PRETTY_FUNCTION__;
440 m_zoomLevel = newZoomLevel;
444 void MapEngine::setTilesGridSize(const QSize &viewSize)
446 qDebug() << __PRETTY_FUNCTION__;
448 // there must be scrolling reserve of at least half tile added to tile amount
449 // calculated from view size
450 const qreal SCROLLING_RESERVE = 0.5;
452 // converting scene tile to tile number does cause grid centering inaccuracy of one tile
453 const int CENTER_TILE_INACCURACY = 1;
455 int gridWidth = ceil(qreal(viewSize.width()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
456 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
457 int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
458 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
460 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
462 m_tilesGridSize.setHeight(gridHeight);
463 m_tilesGridSize.setWidth(gridWidth);
466 int MapEngine::tileMaxIndex(int zoomLevel)
468 qDebug() << __PRETTY_FUNCTION__;
470 // subtract one because first tile index is zero
471 return tilesPerSide(zoomLevel) - 1;
474 QString MapEngine::tilePath(int zoomLevel, int x, int y)
476 qDebug() << __PRETTY_FUNCTION__;
478 QString tilePathString(QString::number(zoomLevel) + "/");
479 tilePathString.append(QString::number(x) + "/");
480 tilePathString.append(QString::number(y));
482 return tilePathString;
485 int MapEngine::tilesPerSide(int zoomLevel)
487 return (1 << zoomLevel);
490 void MapEngine::updateViewTilesSceneRect()
492 qDebug() << __PRETTY_FUNCTION__;
494 const QPoint ONE_TILE = QPoint(1, 1);
495 const double ONE_PIXEL = 1;
497 SceneCoordinate topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel,
498 m_viewTilesGrid.topLeft());
500 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
502 SceneCoordinate bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
503 m_viewTilesGrid.bottomRight()
505 bottomRight.setX(bottomRight.x() - ONE_PIXEL);
506 bottomRight.setY(bottomRight.y() - ONE_PIXEL);
508 m_mapScene->tilesSceneRectUpdated(QRect(topLeft.toPointF().toPoint(),
509 bottomRight.toPointF().toPoint()));
512 void MapEngine::viewResized(const QSize &size)
514 qDebug() << __PRETTY_FUNCTION__;
517 setTilesGridSize(m_viewSize);
519 emit locationChanged(m_sceneCoordinate);
520 getTiles(m_sceneCoordinate);
521 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
522 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
525 void MapEngine::viewZoomFinished()
527 qDebug() << __PRETTY_FUNCTION__;
531 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
534 if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
535 emit maxZoomLevelReached();
536 else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
537 emit minZoomLevelReached();
540 void MapEngine::zoomed()
542 emit zoomLevelChanged(m_zoomLevel);
543 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
544 m_mapScene->setZoomLevel(m_zoomLevel);
545 getTiles(m_sceneCoordinate);
546 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
547 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
548 emit newMapResolution(sceneResolution());
551 void MapEngine::zoomIn()
553 qDebug() << __PRETTY_FUNCTION__;
555 if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
562 void MapEngine::zoomOut()
564 qDebug() << __PRETTY_FUNCTION__;
566 if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {