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_lastAutomaticPosition(QPoint(0, 0)),
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(QPoint)),
101 this, SLOT(setCenterPosition(QPoint)));
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);
112 settings.setValue(MAP_LAST_POSITION,
113 convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
114 settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
117 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
119 qDebug() << __PRETTY_FUNCTION__;
121 QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
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 QPointF MapEngine::centerGeoCoordinate()
132 qDebug() << __PRETTY_FUNCTION__;
134 return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
137 void MapEngine::centerToCoordinates(QPointF latLonCoordinate)
139 qDebug() << __PRETTY_FUNCTION__;
141 scrollToPosition(convertLatLonToSceneCoordinate(latLonCoordinate));
144 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
146 qDebug() << __PRETTY_FUNCTION__;
148 qreal longitude = latLonCoordinate.x();
149 qreal latitude = latLonCoordinate.y();
151 if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
152 return QPoint(UNDEFINED, UNDEFINED);
153 if ((latitude > OSM_MAX_LATITUDE) || (latitude < OSM_MIN_LATITUDE))
154 return QPoint(UNDEFINED, UNDEFINED);
156 qreal z = static_cast<qreal>(MapEngine::tilesPerSide(OSM_MAX_ZOOM_LEVEL));
158 qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
159 qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
160 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
162 return QPointF(x * z * OSM_TILE_SIZE_X, y * z * OSM_TILE_SIZE_Y).toPoint();
165 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
167 qDebug() << __PRETTY_FUNCTION__;
169 double tileFactor = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
170 double xFactor = (sceneCoordinate.x() / (OSM_TILE_SIZE_X*tileFactor));
171 double yFactor = (sceneCoordinate.y() / (OSM_TILE_SIZE_Y*tileFactor));
173 tileFactor = 1 << zoomLevel;
174 double longitude = xFactor / tileFactor * 360.0 - 180;
176 double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
177 double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
179 return QPointF(longitude, latitude);
182 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
184 qDebug() << __PRETTY_FUNCTION__;
186 int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
187 int x = static_cast<int>(sceneCoordinate.x() / (OSM_TILE_SIZE_X * pow));
188 int y = static_cast<int>(sceneCoordinate.y() / (OSM_TILE_SIZE_Y * pow));
193 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
195 qDebug() << __PRETTY_FUNCTION__;
197 int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
198 int x = tileNumber.x() * OSM_TILE_SIZE_X * pow;
199 int y = tileNumber.y() * OSM_TILE_SIZE_Y * pow;
204 void MapEngine::disableAutoCenteringIfRequired(QPoint sceneCoordinate)
206 if (isAutoCenteringEnabled()) {
207 int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
209 QPoint oldPixelValue = QPoint(m_lastAutomaticPosition.x() / zoomFactor,
210 m_lastAutomaticPosition.y() / zoomFactor);
212 QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
213 sceneCoordinate.y() / zoomFactor);
215 if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
216 || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
218 emit mapScrolledManually();
223 void MapEngine::friendsPositionsUpdated()
225 qDebug() << __PRETTY_FUNCTION__;
227 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
230 void MapEngine::getTiles(QPoint sceneCoordinate)
232 qDebug() << __PRETTY_FUNCTION__;
234 m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
235 updateViewTilesSceneRect();
236 m_mapScene->setTilesGrid(m_viewTilesGrid);
238 int topLeftX = m_viewTilesGrid.topLeft().x();
239 int topLeftY = m_viewTilesGrid.topLeft().y();
240 int bottomRightX = m_viewTilesGrid.bottomRight().x();
241 int bottomRightY = m_viewTilesGrid.bottomRight().y();
243 int tileMaxVal = tileMaxIndex(m_zoomLevel);
245 for (int x = topLeftX; x <= bottomRightX; ++x) {
246 for (int y = topLeftY; y <= bottomRightY; ++y) {
248 // map doesn't span in vertical direction, so y index must be inside the limits
249 if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
250 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
251 emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
257 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
259 qDebug() << __PRETTY_FUNCTION__;
261 m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
262 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
264 if (m_autoCenteringEnabled) {
265 m_lastAutomaticPosition = convertLatLonToSceneCoordinate(position);
266 m_scrollStartedByGps = true;
267 scrollToPosition(m_lastAutomaticPosition);
271 qreal MapEngine::greatCircleDistance(QPointF firstLocation, QPointF secondLocation)
273 qDebug() << __PRETTY_FUNCTION__;
275 const qreal TORAD = (M_PI/180);
277 qreal dLat = (secondLocation.y() - firstLocation.y())*TORAD;
278 qreal dLon = (secondLocation.x() - firstLocation.x())*TORAD;
279 qreal a = pow(sin(dLat/2),2) + cos(firstLocation.y()*TORAD) * cos(secondLocation.y()*TORAD)
280 * pow(sin(dLon/2),2);
281 qreal c = 2 * atan2(sqrt(a), sqrt(1-a));
283 return (EARTH_RADIUS * c);
286 void MapEngine::init()
288 qDebug() << __PRETTY_FUNCTION__;
290 QPointF startLocation;
291 QSettings settings(DIRECTORY_NAME, FILE_NAME);
293 if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
294 == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
295 ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
297 startLocation = QPointF(MAP_DEFAULT_LONGITUDE, MAP_DEFAULT_LATITUDE);
298 m_zoomLevel = qBound(MAP_VIEW_MIN_ZOOM_LEVEL, MAP_DEFAULT_ZOOM_LEVEL, OSM_MAX_ZOOM_LEVEL);
300 m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
301 startLocation = settings.value(MAP_LAST_POSITION,
302 ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
305 emit zoomLevelChanged(m_zoomLevel);
306 centerToCoordinates(QPointF(startLocation.x(), startLocation.y()));
309 bool MapEngine::isAutoCenteringEnabled()
311 return m_autoCenteringEnabled;
314 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
316 qDebug() << __PRETTY_FUNCTION__;
318 QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
319 QPoint temp = m_centerTile;
320 m_centerTile = centerTile;
322 return (centerTile != temp);
325 qreal MapEngine::sceneResolution()
327 qDebug() << __PRETTY_FUNCTION__;
329 const int SHIFT = 200;
330 const int KM_TO_M = 1000;
331 qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
332 QPointF centerCoordinate = centerGeoCoordinate();
333 QPoint shiftedSceneCoordinate = QPoint(m_sceneCoordinate.x() + SHIFT*scale
334 , m_sceneCoordinate.y());
335 QPointF shiftedCoordinate = convertSceneCoordinateToLatLon(m_zoomLevel, shiftedSceneCoordinate);
336 qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
337 return (dist / SHIFT);
340 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
342 qDebug() << __PRETTY_FUNCTION__;
344 // add normal tile inside the world
345 QPoint tileNumber(x, y);
346 m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
348 // note: add 1 so odd width is rounded up and even is rounded down
349 int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
351 // duplicate to east side? (don't need to duplicate over padding)
352 if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
353 QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
354 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
357 // duplicate to west side? (don't need to duplicate over padding)
358 if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + MAP_GRID_PADDING)) {
359 QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
360 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
364 int MapEngine::normalize(int value, int min, int max)
366 qDebug() << __PRETTY_FUNCTION__;
367 Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
370 value += max - min + 1;
373 value -= max - min + 1;
378 void MapEngine::receiveOwnLocation(User *user)
380 qDebug() << __PRETTY_FUNCTION__;
383 QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
384 if (m_ownLocation->pos().toPoint() != newPosition) {
385 m_ownLocation->setPos(newPosition);
388 if (!m_ownLocation->isVisible())
389 m_ownLocation->show();
391 m_ownLocation->hide();
394 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
397 QGraphicsScene* MapEngine::scene()
399 qDebug() << __PRETTY_FUNCTION__;
404 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
406 qDebug() << __PRETTY_FUNCTION__;
408 if (m_smoothScrollRunning
409 && newState != QAbstractAnimation::Running) {
410 m_smoothScrollRunning = false;
412 // don't disable auto centering if current animation was stopped by new update from GPS
413 if (!m_scrollStartedByGps)
414 disableAutoCenteringIfRequired(m_sceneCoordinate);
417 m_scrollStartedByGps = false;
420 void MapEngine::scrollToPosition(QPoint scenePosition)
422 qDebug() << __PRETTY_FUNCTION__;
425 m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
426 m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
427 m_scroller->setStartValue(m_sceneCoordinate);
428 m_scroller->setEndValue(scenePosition);
429 m_smoothScrollRunning = true;
433 void MapEngine::setAutoCentering(bool enabled)
435 qDebug() << __PRETTY_FUNCTION__;
437 m_autoCenteringEnabled = enabled;
440 void MapEngine::setCenterPosition(QPoint scenePosition)
442 qDebug() << __PRETTY_FUNCTION__;
444 // jump to opposite side of the world if world horizontal limit is exceeded
445 scenePosition.setX(normalize(scenePosition.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
447 // don't allow vertical scene coordinates go out of the map
448 scenePosition.setY(qBound(OSM_MAP_MIN_PIXEL_Y, scenePosition.y(), OSM_MAP_MAX_PIXEL_Y));
450 if (!m_smoothScrollRunning)
451 disableAutoCenteringIfRequired(scenePosition);
453 m_sceneCoordinate = scenePosition;
454 emit locationChanged(m_sceneCoordinate);
456 if (isCenterTileChanged(scenePosition)) {
457 getTiles(scenePosition);
458 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
461 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
462 emit newMapResolution(sceneResolution());
465 void MapEngine::setGPSEnabled(bool enabled)
467 qDebug() << __PRETTY_FUNCTION__;
469 m_gpsLocationItem->setEnabled(enabled);
472 void MapEngine::setZoomLevel(int newZoomLevel)
474 qDebug() << __PRETTY_FUNCTION__;
476 m_zoomLevel = newZoomLevel;
480 void MapEngine::setTilesGridSize(const QSize &viewSize)
482 qDebug() << __PRETTY_FUNCTION__;
484 // there must be scrolling reserve of at least half tile added to tile amount
485 // calculated from view size
486 const qreal SCROLLING_RESERVE = 0.5;
488 // converting scene tile to tile number does cause grid centering inaccuracy of one tile
489 const int CENTER_TILE_INACCURACY = 1;
491 int gridWidth = ceil(qreal(viewSize.width()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
492 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
493 int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
494 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
496 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
498 m_tilesGridSize.setHeight(gridHeight);
499 m_tilesGridSize.setWidth(gridWidth);
502 int MapEngine::tileMaxIndex(int zoomLevel)
504 qDebug() << __PRETTY_FUNCTION__;
506 // subtract one because first tile index is zero
507 return tilesPerSide(zoomLevel) - 1;
510 QString MapEngine::tilePath(int zoomLevel, int x, int y)
512 qDebug() << __PRETTY_FUNCTION__;
514 QString tilePathString(QString::number(zoomLevel) + "/");
515 tilePathString.append(QString::number(x) + "/");
516 tilePathString.append(QString::number(y));
518 return tilePathString;
521 int MapEngine::tilesPerSide(int zoomLevel)
523 return (1 << zoomLevel);
526 void MapEngine::updateViewTilesSceneRect()
528 qDebug() << __PRETTY_FUNCTION__;
530 const QPoint ONE_TILE = QPoint(1, 1);
531 const QPoint ONE_PIXEL = QPoint(1, 1);
533 QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
534 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
536 QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
537 m_viewTilesGrid.bottomRight()
538 + ONE_TILE) - ONE_PIXEL;
540 m_mapScene->tilesSceneRectUpdated(QRect(topLeft, bottomRight));
543 void MapEngine::viewResized(const QSize &size)
545 qDebug() << __PRETTY_FUNCTION__;
548 setTilesGridSize(m_viewSize);
550 emit locationChanged(m_sceneCoordinate);
551 getTiles(m_sceneCoordinate);
552 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
553 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
556 void MapEngine::viewZoomFinished()
558 qDebug() << __PRETTY_FUNCTION__;
562 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
565 if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
566 emit maxZoomLevelReached();
567 else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
568 emit minZoomLevelReached();
571 void MapEngine::zoomed()
573 emit zoomLevelChanged(m_zoomLevel);
574 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
575 m_mapScene->setZoomLevel(m_zoomLevel);
576 getTiles(m_sceneCoordinate);
577 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
578 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
579 emit newMapResolution(sceneResolution());
582 void MapEngine::zoomIn()
584 qDebug() << __PRETTY_FUNCTION__;
586 if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
593 void MapEngine::zoomOut()
595 qDebug() << __PRETTY_FUNCTION__;
597 if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {