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(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 > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
154 return QPoint(UNDEFINED, UNDEFINED);
156 qreal z = static_cast<qreal>(MapEngine::tilesPerSide(MAX_MAP_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 * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
165 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
167 qDebug() << __PRETTY_FUNCTION__;
169 double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
170 double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
171 double yFactor = (sceneCoordinate.y() / (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 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
187 int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
188 int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
193 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
195 qDebug() << __PRETTY_FUNCTION__;
197 int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
198 int x = tileNumber.x() * TILE_SIZE_X * pow;
199 int y = tileNumber.y() * TILE_SIZE_Y * pow;
204 void MapEngine::disableAutoCenteringIfRequired(QPoint sceneCoordinate)
206 if (isAutoCenteringEnabled()) {
207 int zoomFactor = (1 << (MAX_MAP_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(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
298 m_zoomLevel = qBound(MIN_VIEW_ZOOM_LEVEL, DEFAULT_START_ZOOM_LEVEL, MAX_MAP_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 << (MAX_MAP_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 - 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 + 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(), MAP_MIN_PIXEL_X, MAP_MAX_PIXEL_X));
447 // don't allow vertical scene coordinates go out of the map
448 scenePosition.setY(qBound(MAP_MIN_PIXEL_Y, scenePosition.y(), 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::setRoute(Route route)
474 qWarning() << __PRETTY_FUNCTION__;
478 qWarning() << __PRETTY_FUNCTION__ << "from:" << route.startPointName();
479 qWarning() << __PRETTY_FUNCTION__ << "to:" << route.endPointName();
480 qWarning() << __PRETTY_FUNCTION__ << "distance:" << route.totalDistance();
481 qWarning() << __PRETTY_FUNCTION__ << "estimated time:" << route.totalTime();
483 foreach (QPointF point, route.geometryPoints())
484 qWarning() << __PRETTY_FUNCTION__ << "geometry point:" << point.x() << point.y();
486 foreach (RouteSegment segment, route.segments()) {
487 qWarning() << __PRETTY_FUNCTION__ << "segment:" << segment.instruction();
491 /// @todo calculate bounding box for the track, add margins, ensure visible (zoom, center)
494 void MapEngine::setZoomLevel(int newZoomLevel)
496 qDebug() << __PRETTY_FUNCTION__;
498 m_zoomLevel = newZoomLevel;
502 void MapEngine::setTilesGridSize(const QSize &viewSize)
504 qDebug() << __PRETTY_FUNCTION__;
506 // there must be scrolling reserve of at least half tile added to tile amount
507 // calculated from view size
508 const qreal SCROLLING_RESERVE = 0.5;
510 // converting scene tile to tile number does cause grid centering inaccuracy of one tile
511 const int CENTER_TILE_INACCURACY = 1;
513 int gridWidth = ceil(qreal(viewSize.width()) / TILE_SIZE_X + SCROLLING_RESERVE)
514 + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
515 int gridHeight = ceil(qreal(viewSize.height()) / TILE_SIZE_Y + SCROLLING_RESERVE)
516 + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
518 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
520 m_tilesGridSize.setHeight(gridHeight);
521 m_tilesGridSize.setWidth(gridWidth);
524 int MapEngine::tileMaxIndex(int zoomLevel)
526 qDebug() << __PRETTY_FUNCTION__;
528 // subtract one because first tile index is zero
529 return tilesPerSide(zoomLevel) - 1;
532 QString MapEngine::tilePath(int zoomLevel, int x, int y)
534 qDebug() << __PRETTY_FUNCTION__;
536 QString tilePathString(QString::number(zoomLevel) + "/");
537 tilePathString.append(QString::number(x) + "/");
538 tilePathString.append(QString::number(y));
540 return tilePathString;
543 int MapEngine::tilesPerSide(int zoomLevel)
545 return (1 << zoomLevel);
548 void MapEngine::updateViewTilesSceneRect()
550 qDebug() << __PRETTY_FUNCTION__;
552 const QPoint ONE_TILE = QPoint(1, 1);
553 const QPoint ONE_PIXEL = QPoint(1, 1);
555 QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
556 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
558 QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
559 m_viewTilesGrid.bottomRight()
560 + ONE_TILE) - ONE_PIXEL;
562 m_mapScene->tilesSceneRectUpdated(QRect(topLeft, bottomRight));
565 void MapEngine::viewResized(const QSize &size)
567 qDebug() << __PRETTY_FUNCTION__;
570 setTilesGridSize(m_viewSize);
572 emit locationChanged(m_sceneCoordinate);
573 getTiles(m_sceneCoordinate);
574 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
575 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
578 void MapEngine::viewZoomFinished()
580 qDebug() << __PRETTY_FUNCTION__;
584 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
587 if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
588 emit maxZoomLevelReached();
589 else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
590 emit minZoomLevelReached();
593 void MapEngine::zoomed()
595 emit zoomLevelChanged(m_zoomLevel);
596 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
597 m_mapScene->setZoomLevel(m_zoomLevel);
598 getTiles(m_sceneCoordinate);
599 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
600 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
601 emit newMapResolution(sceneResolution());
604 void MapEngine::zoomIn()
606 qDebug() << __PRETTY_FUNCTION__;
608 if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
615 void MapEngine::zoomOut()
617 qDebug() << __PRETTY_FUNCTION__;
619 if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {