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(friendsLocationsReady(QList<User*>&)),
89 this, SLOT(friendsPositionsUpdated()));
91 connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
92 this, SIGNAL(locationItemClicked(QList<QString>)));
94 m_scroller = &MapScroller::getInstance();
96 connect(m_scroller, SIGNAL(coordinateUpdated(QPoint)),
97 this, SLOT(setCenterPosition(QPoint)));
99 connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
100 this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
103 MapEngine::~MapEngine()
105 qDebug() << __PRETTY_FUNCTION__;
107 QSettings settings(DIRECTORY_NAME, FILE_NAME);
108 settings.setValue(MAP_LAST_POSITION,
109 convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
110 settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
113 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
115 qDebug() << __PRETTY_FUNCTION__;
117 QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
120 topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
121 topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
123 return QRect(topLeft, m_tilesGridSize);
126 QPointF MapEngine::centerGeoCoordinate()
128 qDebug() << __PRETTY_FUNCTION__;
130 return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
133 void MapEngine::centerToCoordinates(QPointF latLonCoordinate)
135 qDebug() << __PRETTY_FUNCTION__;
137 scrollToPosition(convertLatLonToSceneCoordinate(latLonCoordinate));
140 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
142 qDebug() << __PRETTY_FUNCTION__;
144 qreal longitude = latLonCoordinate.x();
145 qreal latitude = latLonCoordinate.y();
147 if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
148 return QPoint(UNDEFINED, UNDEFINED);
149 if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
150 return QPoint(UNDEFINED, UNDEFINED);
152 qreal z = static_cast<qreal>(MapEngine::tilesPerSide(MAX_MAP_ZOOM_LEVEL));
154 qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
155 qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
156 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
158 return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
161 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
163 qDebug() << __PRETTY_FUNCTION__;
165 double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
166 double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
167 double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
169 tileFactor = 1 << zoomLevel;
170 double longitude = xFactor / tileFactor * 360.0 - 180;
172 double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
173 double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
175 return QPointF(longitude, latitude);
178 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
180 qDebug() << __PRETTY_FUNCTION__;
182 int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
183 int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
184 int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
189 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
191 qDebug() << __PRETTY_FUNCTION__;
193 int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
194 int x = tileNumber.x() * TILE_SIZE_X * pow;
195 int y = tileNumber.y() * TILE_SIZE_Y * pow;
200 void MapEngine::disableAutoCenteringIfRequired(QPoint sceneCoordinate)
202 if (isAutoCenteringEnabled()) {
203 int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
205 QPoint oldPixelValue = QPoint(m_lastAutomaticPosition.x() / zoomFactor,
206 m_lastAutomaticPosition.y() / zoomFactor);
208 QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
209 sceneCoordinate.y() / zoomFactor);
211 if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
212 || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
214 emit mapScrolledManually();
219 void MapEngine::friendsPositionsUpdated()
221 qDebug() << __PRETTY_FUNCTION__;
223 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
226 void MapEngine::getTiles(QPoint sceneCoordinate)
228 qDebug() << __PRETTY_FUNCTION__;
230 m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
231 updateViewTilesSceneRect();
232 m_mapScene->setTilesGrid(m_viewTilesGrid);
234 int topLeftX = m_viewTilesGrid.topLeft().x();
235 int topLeftY = m_viewTilesGrid.topLeft().y();
236 int bottomRightX = m_viewTilesGrid.bottomRight().x();
237 int bottomRightY = m_viewTilesGrid.bottomRight().y();
239 int tileMaxVal = tileMaxIndex(m_zoomLevel);
241 for (int x = topLeftX; x <= bottomRightX; ++x) {
242 for (int y = topLeftY; y <= bottomRightY; ++y) {
244 // map doesn't span in vertical direction, so y index must be inside the limits
245 if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
246 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
247 emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
253 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
255 qDebug() << __PRETTY_FUNCTION__;
257 m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
258 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
260 if (m_autoCenteringEnabled) {
261 m_lastAutomaticPosition = convertLatLonToSceneCoordinate(position);
262 m_scrollStartedByGps = true;
263 scrollToPosition(m_lastAutomaticPosition);
267 qreal MapEngine::greatCircleDistance(QPointF firstLocation, QPointF secondLocation)
269 qDebug() << __PRETTY_FUNCTION__;
271 const qreal TORAD = (M_PI/180);
273 qreal dLat = (secondLocation.y() - firstLocation.y())*TORAD;
274 qreal dLon = (secondLocation.x() - firstLocation.x())*TORAD;
275 qreal a = pow(sin(dLat/2),2) + cos(firstLocation.y()*TORAD) * cos(secondLocation.y()*TORAD)
276 * pow(sin(dLon/2),2);
277 qreal c = 2 * atan2(sqrt(a), sqrt(1-a));
279 return (EARTH_RADIUS * c);
282 void MapEngine::init()
284 qDebug() << __PRETTY_FUNCTION__;
286 QPointF startLocation;
287 QSettings settings(DIRECTORY_NAME, FILE_NAME);
289 if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
290 == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
291 ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
293 startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
294 m_zoomLevel = qBound(MIN_VIEW_ZOOM_LEVEL, DEFAULT_START_ZOOM_LEVEL, MAX_MAP_ZOOM_LEVEL);
296 m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
297 startLocation = settings.value(MAP_LAST_POSITION,
298 ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
301 emit zoomLevelChanged(m_zoomLevel);
302 centerToCoordinates(QPointF(startLocation.x(), startLocation.y()));
305 bool MapEngine::isAutoCenteringEnabled()
307 return m_autoCenteringEnabled;
310 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
312 qDebug() << __PRETTY_FUNCTION__;
314 QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
315 QPoint temp = m_centerTile;
316 m_centerTile = centerTile;
318 return (centerTile != temp);
321 qreal MapEngine::sceneResolution()
323 qDebug() << __PRETTY_FUNCTION__;
325 const int SHIFT = 200;
326 const int KM_TO_M = 1000;
327 qreal scale = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
328 QPointF centerCoordinate = centerGeoCoordinate();
329 QPoint shiftedSceneCoordinate = QPoint(m_sceneCoordinate.x() + SHIFT*scale
330 , m_sceneCoordinate.y());
331 QPointF shiftedCoordinate = convertSceneCoordinateToLatLon(m_zoomLevel, shiftedSceneCoordinate);
332 qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
333 return (dist / SHIFT);
336 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
338 qDebug() << __PRETTY_FUNCTION__;
340 // add normal tile inside the world
341 QPoint tileNumber(x, y);
342 m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
344 // note: add 1 so odd width is rounded up and even is rounded down
345 int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
347 // duplicate to east side? (don't need to duplicate over padding)
348 if (tileNumber.x() < (tilesGridWidthHalf - GRID_PADDING)) {
349 QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
350 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
353 // duplicate to west side? (don't need to duplicate over padding)
354 if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + GRID_PADDING)) {
355 QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
356 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
360 int MapEngine::normalize(int value, int min, int max)
362 qDebug() << __PRETTY_FUNCTION__;
363 Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
366 value += max - min + 1;
369 value -= max - min + 1;
374 void MapEngine::receiveOwnLocation(User *user)
376 qDebug() << __PRETTY_FUNCTION__;
379 QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
380 if (m_ownLocation->pos().toPoint() != newPosition) {
381 m_ownLocation->setPos(newPosition);
384 if (!m_ownLocation->isVisible())
385 m_ownLocation->show();
387 m_ownLocation->hide();
390 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
393 QGraphicsScene* MapEngine::scene()
395 qDebug() << __PRETTY_FUNCTION__;
400 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
402 qDebug() << __PRETTY_FUNCTION__;
404 if (m_smoothScrollRunning
405 && newState != QAbstractAnimation::Running) {
406 m_smoothScrollRunning = false;
408 // don't disable auto centering if current animation was stopped by new update from GPS
409 if (!m_scrollStartedByGps)
410 disableAutoCenteringIfRequired(m_sceneCoordinate);
413 m_scrollStartedByGps = false;
416 void MapEngine::scrollToPosition(QPoint scenePosition)
418 qDebug() << __PRETTY_FUNCTION__;
421 m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
422 m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
423 m_scroller->setStartValue(m_sceneCoordinate);
424 m_scroller->setEndValue(scenePosition);
425 m_smoothScrollRunning = true;
429 void MapEngine::setAutoCentering(bool enabled)
431 qDebug() << __PRETTY_FUNCTION__;
433 m_autoCenteringEnabled = enabled;
436 void MapEngine::setCenterPosition(QPoint scenePosition)
438 qDebug() << __PRETTY_FUNCTION__;
440 // jump to opposite side of the world if world horizontal limit is exceeded
441 scenePosition.setX(normalize(scenePosition.x(), MAP_MIN_PIXEL_X, MAP_MAX_PIXEL_X));
443 // don't allow vertical scene coordinates go out of the map
444 scenePosition.setY(qBound(MAP_MIN_PIXEL_Y, scenePosition.y(), MAP_MAX_PIXEL_Y));
446 if (!m_smoothScrollRunning)
447 disableAutoCenteringIfRequired(scenePosition);
449 m_sceneCoordinate = scenePosition;
450 emit locationChanged(m_sceneCoordinate);
452 if (isCenterTileChanged(scenePosition)) {
453 getTiles(scenePosition);
454 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
457 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
458 emit newMapResolution(sceneResolution());
461 void MapEngine::setGPSEnabled(bool enabled)
463 qDebug() << __PRETTY_FUNCTION__;
465 m_gpsLocationItem->setEnabled(enabled);
468 void MapEngine::setZoomLevel(int newZoomLevel)
470 qDebug() << __PRETTY_FUNCTION__;
472 m_zoomLevel = newZoomLevel;
476 void MapEngine::setTilesGridSize(const QSize &viewSize)
478 qDebug() << __PRETTY_FUNCTION__;
480 // there must be scrolling reserve of at least half tile added to tile amount
481 // calculated from view size
482 const qreal SCROLLING_RESERVE = 0.5;
484 // converting scene tile to tile number does cause grid centering inaccuracy of one tile
485 const int CENTER_TILE_INACCURACY = 1;
487 int gridWidth = ceil(qreal(viewSize.width()) / TILE_SIZE_X + SCROLLING_RESERVE)
488 + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
489 int gridHeight = ceil(qreal(viewSize.height()) / TILE_SIZE_Y + SCROLLING_RESERVE)
490 + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
492 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
494 m_tilesGridSize.setHeight(gridHeight);
495 m_tilesGridSize.setWidth(gridWidth);
498 int MapEngine::tileMaxIndex(int zoomLevel)
500 qDebug() << __PRETTY_FUNCTION__;
502 // subtract one because first tile index is zero
503 return tilesPerSide(zoomLevel) - 1;
506 QString MapEngine::tilePath(int zoomLevel, int x, int y)
508 qDebug() << __PRETTY_FUNCTION__;
510 QString tilePathString(QString::number(zoomLevel) + "/");
511 tilePathString.append(QString::number(x) + "/");
512 tilePathString.append(QString::number(y));
514 return tilePathString;
517 int MapEngine::tilesPerSide(int zoomLevel)
519 return (1 << zoomLevel);
522 void MapEngine::updateViewTilesSceneRect()
524 qDebug() << __PRETTY_FUNCTION__;
526 const QPoint ONE_TILE = QPoint(1, 1);
527 const QPoint ONE_PIXEL = QPoint(1, 1);
529 QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
530 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
532 QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
533 m_viewTilesGrid.bottomRight()
534 + ONE_TILE) - ONE_PIXEL;
536 m_mapScene->tilesSceneRectUpdated(QRect(topLeft, bottomRight));
539 void MapEngine::viewResized(const QSize &size)
541 qDebug() << __PRETTY_FUNCTION__;
544 setTilesGridSize(m_viewSize);
546 emit locationChanged(m_sceneCoordinate);
547 getTiles(m_sceneCoordinate);
548 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
549 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
552 void MapEngine::viewZoomFinished()
554 qDebug() << __PRETTY_FUNCTION__;
558 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
561 if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
562 emit maxZoomLevelReached();
563 else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
564 emit minZoomLevelReached();
567 void MapEngine::zoomed()
569 emit zoomLevelChanged(m_zoomLevel);
570 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
571 m_mapScene->setZoomLevel(m_zoomLevel);
572 getTiles(m_sceneCoordinate);
573 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
574 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
575 emit newMapResolution(sceneResolution());
578 void MapEngine::zoomIn()
580 qDebug() << __PRETTY_FUNCTION__;
582 if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
589 void MapEngine::zoomOut()
591 qDebug() << __PRETTY_FUNCTION__;
593 if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {