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
10 Situare is free software; you can redistribute it and/or
11 modify it under the terms of the GNU General Public License
12 version 2 as published by the Free Software Foundation.
14 Situare is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with Situare; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25 #include <QtAlgorithms>
28 #include <QStringList>
31 #include <QHashIterator>
35 #include "frienditemshandler.h"
36 #include "gpslocationitem.h"
37 #include "mapcommon.h"
38 #include "mapfetcher.h"
40 #include "mapscroller.h"
42 #include "network/networkaccessmanager.h"
43 #include "ownlocationitem.h"
44 #include "user/user.h"
46 #include "mapengine.h"
48 const int SMOOTH_CENTERING_TIME_MS = 1000;
50 MapEngine::MapEngine(QObject *parent)
52 m_autoCenteringEnabled(false),
53 m_scrollStartedByGps(false),
54 m_smoothScrollRunning(false),
56 m_zoomLevel(DEFAULT_ZOOM_LEVEL),
57 m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
58 m_lastAutomaticPosition(QPoint(0, 0)),
59 m_tilesGridSize(QSize(0, 0)),
60 m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
62 qDebug() << __PRETTY_FUNCTION__;
64 m_mapScene = new MapScene(this);
66 m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
67 connect(this, SIGNAL(fetchImage(int, int, int)),
68 m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
69 connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
70 this, SLOT(mapImageReceived(int, int, int, QPixmap)));
71 connect(m_mapFetcher, SIGNAL(error(int, int)),
72 this, SIGNAL(error(int, int)));
74 m_ownLocation = new OwnLocationItem();
75 m_ownLocation->hide(); // hide until first location info is received
76 m_mapScene->addItem(m_ownLocation);
78 m_gpsLocationItem = new GPSLocationItem();
79 m_mapScene->addItem(m_gpsLocationItem);
81 m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
82 connect(this, SIGNAL(zoomLevelChanged(int)),
83 m_friendItemsHandler, SLOT(refactorFriendItems(int)));
85 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
86 m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
88 connect(this, SIGNAL(friendImageReady(User*)),
89 m_friendItemsHandler, SLOT(friendImageReady(User*)));
91 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
92 this, SLOT(friendsPositionsUpdated()));
94 connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
95 this, SIGNAL(locationItemClicked(QList<QString>)));
97 m_scroller = &MapScroller::getInstance();
99 connect(m_scroller, SIGNAL(coordinateUpdated(QPoint)),
100 this, SLOT(setCenterPosition(QPoint)));
102 connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
103 this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
106 MapEngine::~MapEngine()
108 qDebug() << __PRETTY_FUNCTION__;
110 QSettings settings(DIRECTORY_NAME, FILE_NAME);
111 settings.setValue(MAP_LAST_POSITION,
112 convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
113 settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
116 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
118 qDebug() << __PRETTY_FUNCTION__;
120 QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
123 topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
124 topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
126 return QRect(topLeft, m_tilesGridSize);
129 QPointF MapEngine::centerGeoCoordinate()
131 qDebug() << __PRETTY_FUNCTION__;
133 return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
136 void MapEngine::centerToCoordinates(QPointF latLonCoordinate)
138 qDebug() << __PRETTY_FUNCTION__;
140 scrollToPosition(convertLatLonToSceneCoordinate(latLonCoordinate));
143 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
145 qDebug() << __PRETTY_FUNCTION__;
147 qreal longitude = latLonCoordinate.x();
148 qreal latitude = latLonCoordinate.y();
150 if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
151 return QPoint(UNDEFINED, UNDEFINED);
152 if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
153 return QPoint(UNDEFINED, UNDEFINED);
155 qreal z = static_cast<qreal>(MapEngine::tilesPerSide(MAX_MAP_ZOOM_LEVEL));
157 qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
158 qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
159 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
161 return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
164 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
166 qDebug() << __PRETTY_FUNCTION__;
168 double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
169 double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
170 double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
172 tileFactor = 1 << zoomLevel;
173 double longitude = xFactor / tileFactor * 360.0 - 180;
175 double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
176 double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
178 return QPointF(longitude, latitude);
181 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
183 qDebug() << __PRETTY_FUNCTION__;
185 int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
186 int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
187 int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
192 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
194 qDebug() << __PRETTY_FUNCTION__;
196 int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
197 int x = tileNumber.x() * TILE_SIZE_X * pow;
198 int y = tileNumber.y() * TILE_SIZE_Y * pow;
203 void MapEngine::disableAutoCenteringIfRequired(QPoint sceneCoordinate)
205 if (isAutoCenteringEnabled()) {
206 int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
208 QPoint oldPixelValue = QPoint(m_lastAutomaticPosition.x() / zoomFactor,
209 m_lastAutomaticPosition.y() / zoomFactor);
211 QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
212 sceneCoordinate.y() / zoomFactor);
214 if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
215 || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
217 emit mapScrolledManually();
222 void MapEngine::friendsPositionsUpdated()
224 qDebug() << __PRETTY_FUNCTION__;
226 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
229 void MapEngine::getTiles(QPoint sceneCoordinate)
231 qDebug() << __PRETTY_FUNCTION__;
233 m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
234 updateViewTilesSceneRect();
235 m_mapScene->setTilesGrid(m_viewTilesGrid);
237 int topLeftX = m_viewTilesGrid.topLeft().x();
238 int topLeftY = m_viewTilesGrid.topLeft().y();
239 int bottomRightX = m_viewTilesGrid.bottomRight().x();
240 int bottomRightY = m_viewTilesGrid.bottomRight().y();
242 int tileMaxVal = tileMaxIndex(m_zoomLevel);
244 for (int x = topLeftX; x <= bottomRightX; ++x) {
245 for (int y = topLeftY; y <= bottomRightY; ++y) {
247 // map doesn't span in vertical direction, so y index must be inside the limits
248 if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
249 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
250 emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
256 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
258 qDebug() << __PRETTY_FUNCTION__;
260 m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
261 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
263 if (m_autoCenteringEnabled) {
264 m_lastAutomaticPosition = convertLatLonToSceneCoordinate(position);
265 m_scrollStartedByGps = true;
266 scrollToPosition(m_lastAutomaticPosition);
270 qreal MapEngine::greatCircleDistance(QPointF firstLocation, QPointF secondLocation)
272 qDebug() << __PRETTY_FUNCTION__;
274 const qreal TORAD = (M_PI/180);
276 qreal dLat = (secondLocation.y() - firstLocation.y())*TORAD;
277 qreal dLon = (secondLocation.x() - firstLocation.x())*TORAD;
278 qreal a = pow(sin(dLat/2),2) + cos(firstLocation.y()*TORAD) * cos(secondLocation.y()*TORAD)
279 * pow(sin(dLon/2),2);
280 qreal c = 2 * atan2(sqrt(a), sqrt(1-a));
282 return (EARTH_RADIUS * c);
285 void MapEngine::init()
287 qDebug() << __PRETTY_FUNCTION__;
289 QPointF startLocation;
290 QSettings settings(DIRECTORY_NAME, FILE_NAME);
292 if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
293 == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
294 ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
296 startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
297 m_zoomLevel = qBound(MIN_VIEW_ZOOM_LEVEL, DEFAULT_START_ZOOM_LEVEL, MAX_MAP_ZOOM_LEVEL);
299 m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
300 startLocation = settings.value(MAP_LAST_POSITION,
301 ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
304 emit zoomLevelChanged(m_zoomLevel);
305 centerToCoordinates(QPointF(startLocation.x(), startLocation.y()));
308 bool MapEngine::isAutoCenteringEnabled()
310 return m_autoCenteringEnabled;
313 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
315 qDebug() << __PRETTY_FUNCTION__;
317 QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
318 QPoint temp = m_centerTile;
319 m_centerTile = centerTile;
321 return (centerTile != temp);
324 qreal MapEngine::sceneResolution()
326 qDebug() << __PRETTY_FUNCTION__;
328 const int SHIFT = 200;
329 const int KM_TO_M = 1000;
330 qreal scale = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
331 QPointF centerCoordinate = centerGeoCoordinate();
332 QPoint shiftedSceneCoordinate = QPoint(m_sceneCoordinate.x() + SHIFT*scale
333 , m_sceneCoordinate.y());
334 QPointF shiftedCoordinate = convertSceneCoordinateToLatLon(m_zoomLevel, shiftedSceneCoordinate);
335 qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
336 return (dist / SHIFT);
339 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
341 qDebug() << __PRETTY_FUNCTION__;
343 // add normal tile inside the world
344 QPoint tileNumber(x, y);
345 m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
347 // note: add 1 so odd width is rounded up and even is rounded down
348 int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
350 // duplicate to east side? (don't need to duplicate over padding)
351 if (tileNumber.x() < (tilesGridWidthHalf - GRID_PADDING)) {
352 QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
353 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
356 // duplicate to west side? (don't need to duplicate over padding)
357 if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + GRID_PADDING)) {
358 QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
359 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
363 int MapEngine::normalize(int value, int min, int max)
365 qDebug() << __PRETTY_FUNCTION__;
366 Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
369 value += max - min + 1;
372 value -= max - min + 1;
377 void MapEngine::receiveOwnLocation(User *user)
379 qDebug() << __PRETTY_FUNCTION__;
382 QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
383 if (m_ownLocation->pos().toPoint() != newPosition) {
384 m_ownLocation->setPos(newPosition);
387 if (!m_ownLocation->isVisible())
388 m_ownLocation->show();
390 m_ownLocation->hide();
393 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
396 QGraphicsScene* MapEngine::scene()
398 qDebug() << __PRETTY_FUNCTION__;
403 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
405 qDebug() << __PRETTY_FUNCTION__;
407 if (m_smoothScrollRunning
408 && newState != QAbstractAnimation::Running) {
409 m_smoothScrollRunning = false;
411 // don't disable auto centering if current animation was stopped by new update from GPS
412 if (!m_scrollStartedByGps)
413 disableAutoCenteringIfRequired(m_sceneCoordinate);
416 m_scrollStartedByGps = false;
419 void MapEngine::scrollToPosition(QPoint scenePosition)
421 qDebug() << __PRETTY_FUNCTION__;
424 m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
425 m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
426 m_scroller->setStartValue(m_sceneCoordinate);
427 m_scroller->setEndValue(scenePosition);
428 m_smoothScrollRunning = true;
432 void MapEngine::setAutoCentering(bool enabled)
434 qDebug() << __PRETTY_FUNCTION__;
436 m_autoCenteringEnabled = enabled;
439 void MapEngine::setCenterPosition(QPoint scenePosition)
441 qDebug() << __PRETTY_FUNCTION__;
443 // jump to opposite side of the world if world horizontal limit is exceeded
444 scenePosition.setX(normalize(scenePosition.x(), MAP_MIN_PIXEL_X, MAP_MAX_PIXEL_X));
446 // don't allow vertical scene coordinates go out of the map
447 scenePosition.setY(qBound(MAP_MIN_PIXEL_Y, scenePosition.y(), MAP_MAX_PIXEL_Y));
449 if (!m_smoothScrollRunning)
450 disableAutoCenteringIfRequired(scenePosition);
452 m_sceneCoordinate = scenePosition;
453 emit locationChanged(m_sceneCoordinate);
455 if (isCenterTileChanged(scenePosition)) {
456 getTiles(scenePosition);
457 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
460 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
461 emit newMapResolution(sceneResolution());
464 void MapEngine::setGPSEnabled(bool enabled)
466 qDebug() << __PRETTY_FUNCTION__;
468 m_gpsLocationItem->setEnabled(enabled);
471 void MapEngine::setZoomLevel(int newZoomLevel)
473 qDebug() << __PRETTY_FUNCTION__;
475 m_zoomLevel = newZoomLevel;
479 void MapEngine::setTilesGridSize(const QSize &viewSize)
481 qDebug() << __PRETTY_FUNCTION__;
483 // there must be scrolling reserve of at least half tile added to tile amount
484 // calculated from view size
485 const qreal SCROLLING_RESERVE = 0.5;
487 // converting scene tile to tile number does cause grid centering inaccuracy of one tile
488 const int CENTER_TILE_INACCURACY = 1;
490 int gridWidth = ceil(qreal(viewSize.width()) / TILE_SIZE_X + SCROLLING_RESERVE)
491 + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
492 int gridHeight = ceil(qreal(viewSize.height()) / TILE_SIZE_Y + SCROLLING_RESERVE)
493 + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
495 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
497 m_tilesGridSize.setHeight(gridHeight);
498 m_tilesGridSize.setWidth(gridWidth);
501 int MapEngine::tileMaxIndex(int zoomLevel)
503 qDebug() << __PRETTY_FUNCTION__;
505 // subtract one because first tile index is zero
506 return tilesPerSide(zoomLevel) - 1;
509 QString MapEngine::tilePath(int zoomLevel, int x, int y)
511 qDebug() << __PRETTY_FUNCTION__;
513 QString tilePathString(QString::number(zoomLevel) + "/");
514 tilePathString.append(QString::number(x) + "/");
515 tilePathString.append(QString::number(y));
517 return tilePathString;
520 int MapEngine::tilesPerSide(int zoomLevel)
522 return (1 << zoomLevel);
525 void MapEngine::updateViewTilesSceneRect()
527 qDebug() << __PRETTY_FUNCTION__;
529 const QPoint ONE_TILE = QPoint(1, 1);
530 const QPoint ONE_PIXEL = QPoint(1, 1);
532 QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
533 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
535 QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
536 m_viewTilesGrid.bottomRight()
537 + ONE_TILE) - ONE_PIXEL;
539 m_mapScene->tilesSceneRectUpdated(QRect(topLeft, bottomRight));
542 void MapEngine::viewResized(const QSize &size)
544 qDebug() << __PRETTY_FUNCTION__;
547 setTilesGridSize(m_viewSize);
549 emit locationChanged(m_sceneCoordinate);
550 getTiles(m_sceneCoordinate);
551 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
552 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
555 void MapEngine::viewZoomFinished()
557 qDebug() << __PRETTY_FUNCTION__;
561 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
564 if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
565 emit maxZoomLevelReached();
566 else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
567 emit minZoomLevelReached();
570 void MapEngine::zoomed()
572 emit zoomLevelChanged(m_zoomLevel);
573 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
574 m_mapScene->setZoomLevel(m_zoomLevel);
575 getTiles(m_sceneCoordinate);
576 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
577 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
578 emit newMapResolution(sceneResolution());
581 void MapEngine::zoomIn()
583 qDebug() << __PRETTY_FUNCTION__;
585 if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
592 void MapEngine::zoomOut()
594 qDebug() << __PRETTY_FUNCTION__;
596 if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {