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"
40 #include "maprouteitem.h"
42 #include "mapscroller.h"
44 #include "network/networkaccessmanager.h"
45 #include "ownlocationitem.h"
46 #include "user/user.h"
48 #include "mapengine.h"
50 const int SMOOTH_CENTERING_TIME_MS = 1000;
52 MapEngine::MapEngine(QObject *parent)
54 m_autoCenteringEnabled(false),
55 m_scrollStartedByGps(false),
56 m_smoothScrollRunning(false),
58 m_zoomLevel(MAP_DEFAULT_ZOOM_LEVEL),
59 m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
60 m_sceneCoordinate(SceneCoordinate(GeoCoordinate(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE))),
61 m_tilesGridSize(QSize(0, 0)),
62 m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT)),
65 qDebug() << __PRETTY_FUNCTION__;
67 m_mapScene = new MapScene(this);
69 m_mapFetcher = new MapFetcher(new NetworkAccessManager(this), this);
70 connect(this, SIGNAL(fetchImage(int, int, int)),
71 m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
72 connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
73 this, SLOT(mapImageReceived(int, int, int, QPixmap)));
74 connect(m_mapFetcher, SIGNAL(error(int, int)),
75 this, SIGNAL(error(int, int)));
77 m_ownLocation = new OwnLocationItem();
78 m_ownLocation->hide(); // hide until first location info is received
79 m_mapScene->addItem(m_ownLocation);
81 m_gpsLocationItem = new GPSLocationItem();
82 m_mapScene->addItem(m_gpsLocationItem);
84 m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
85 connect(this, SIGNAL(zoomLevelChanged(int)),
86 m_friendItemsHandler, SLOT(refactorFriendItems(int)));
88 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
89 m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
91 connect(this, SIGNAL(friendImageReady(User*)),
92 m_friendItemsHandler, SLOT(friendImageReady(User*)));
94 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
95 this, SLOT(friendsPositionsUpdated()));
97 connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
98 this, SIGNAL(locationItemClicked(QList<QString>)));
100 m_scroller = &MapScroller::getInstance();
102 connect(m_scroller, SIGNAL(coordinateUpdated(SceneCoordinate)),
103 this, SLOT(setCenterPosition(SceneCoordinate)));
105 connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
106 this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
109 MapEngine::~MapEngine()
111 qDebug() << __PRETTY_FUNCTION__;
113 QSettings settings(DIRECTORY_NAME, FILE_NAME);
115 settings.setValue(MAP_LAST_POSITION, QVariant::fromValue(centerGeoCoordinate()));
116 settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
119 QRect MapEngine::calculateTileGrid(SceneCoordinate coordinate)
121 qDebug() << __PRETTY_FUNCTION__;
123 QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
126 topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
127 topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
129 return QRect(topLeft, m_tilesGridSize);
132 void MapEngine::centerAndZoomTo(QRect rect)
134 const int MARGIN_HORIZONTAL = 50;
135 const int MARGIN_VERTICAL = 5;
137 // calculate the usable size of the view
138 int viewUsableHeight = m_viewSize.height() - 2 * MARGIN_VERTICAL;
139 int viewUsableWidth = m_viewSize.width() - 2 * MARGIN_HORIZONTAL;
141 // calculate how many levels must be zoomed out from the closest zoom level to get the rect
142 // fit inside the usable view area
144 while ((rect.height() > (viewUsableHeight * (1 << shift)))
145 || (rect.width() > (viewUsableWidth * (1 << shift))))
148 scrollToPosition(SceneCoordinate(double(rect.center().x()), double(rect.center().y())));
150 int zoomLevel = qBound(OSM_MIN_ZOOM_LEVEL, OSM_MAX_ZOOM_LEVEL - shift, OSM_MAX_ZOOM_LEVEL);
151 setZoomLevel(zoomLevel);
154 GeoCoordinate MapEngine::centerGeoCoordinate()
156 qDebug() << __PRETTY_FUNCTION__;
158 return GeoCoordinate(m_sceneCoordinate);
161 void MapEngine::centerToCoordinates(GeoCoordinate coordinate)
163 qDebug() << __PRETTY_FUNCTION__;
165 scrollToPosition(SceneCoordinate(coordinate));
168 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, SceneCoordinate coordinate)
170 qDebug() << __PRETTY_FUNCTION__;
172 int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
173 int x = static_cast<int>(coordinate.x() / (OSM_TILE_SIZE_X * pow));
174 int y = static_cast<int>(coordinate.y() / (OSM_TILE_SIZE_Y * pow));
179 SceneCoordinate MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
181 qDebug() << __PRETTY_FUNCTION__;
183 int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
184 int x = tileNumber.x() * OSM_TILE_SIZE_X * pow;
185 int y = tileNumber.y() * OSM_TILE_SIZE_Y * pow;
187 return SceneCoordinate(x, y);
190 void MapEngine::disableAutoCenteringIfRequired(SceneCoordinate coordinate)
192 if (isAutoCenteringEnabled()) {
193 int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
195 SceneCoordinate oldPixelValue(m_lastAutomaticPosition.x() / zoomFactor,
196 m_lastAutomaticPosition.y() / zoomFactor);
198 SceneCoordinate newPixelValue(coordinate.x() / zoomFactor,
199 coordinate.y() / zoomFactor);
201 if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
202 || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
204 emit mapScrolledManually();
209 void MapEngine::friendsPositionsUpdated()
211 qDebug() << __PRETTY_FUNCTION__;
213 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
216 void MapEngine::getTiles(SceneCoordinate coordinate)
218 qDebug() << __PRETTY_FUNCTION__;
220 m_viewTilesGrid = calculateTileGrid(coordinate);
221 updateViewTilesSceneRect();
222 m_mapScene->setTilesGrid(m_viewTilesGrid);
224 int topLeftX = m_viewTilesGrid.topLeft().x();
225 int topLeftY = m_viewTilesGrid.topLeft().y();
226 int bottomRightX = m_viewTilesGrid.bottomRight().x();
227 int bottomRightY = m_viewTilesGrid.bottomRight().y();
229 int tileMaxVal = tileMaxIndex(m_zoomLevel);
231 for (int x = topLeftX; x <= bottomRightX; ++x) {
232 for (int y = topLeftY; y <= bottomRightY; ++y) {
234 // map doesn't span in vertical direction, so y index must be inside the limits
235 if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
236 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
237 emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
243 void MapEngine::gpsPositionUpdate(GeoCoordinate position, qreal accuracy)
245 qDebug() << __PRETTY_FUNCTION__;
247 m_gpsLocationItem->updatePosition(SceneCoordinate(position), accuracy);
248 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
250 if (m_autoCenteringEnabled) {
251 m_lastAutomaticPosition = SceneCoordinate(position);
252 m_scrollStartedByGps = true;
253 scrollToPosition(m_lastAutomaticPosition);
257 qreal MapEngine::greatCircleDistance(GeoCoordinate firstLocation, GeoCoordinate secondLocation)
259 qDebug() << __PRETTY_FUNCTION__;
261 const qreal TO_RAD = (M_PI / 180);
263 qreal dLat = (secondLocation.latitude() - firstLocation.latitude()) * TO_RAD;
264 qreal dLon = (secondLocation.longitude() - firstLocation.longitude()) * TO_RAD;
265 qreal a = pow(sin(dLat / 2), 2)
266 + cos(firstLocation.latitude() * TO_RAD)
267 * cos(secondLocation.latitude() * TO_RAD)
268 * pow(sin(dLon / 2), 2);
269 qreal c = 2 * atan2(sqrt(a), sqrt(1 - a));
271 return (EARTH_RADIUS * c);
274 void MapEngine::init()
276 qDebug() << __PRETTY_FUNCTION__;
278 QSettings settings(DIRECTORY_NAME, FILE_NAME);
280 // init can be only done if both values exists in the settings
281 if (settings.contains(MAP_LAST_POSITION) && settings.contains(MAP_LAST_ZOOMLEVEL)) {
282 QVariant zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL);
283 QVariant location = settings.value(MAP_LAST_POSITION);
285 // also the init can be only done if we are able to convert variants into target data types
286 if (zoomLevel.canConvert<int>() && location.canConvert<GeoCoordinate>()) {
287 m_zoomLevel = zoomLevel.toInt();
288 m_sceneCoordinate = SceneCoordinate(location.value<GeoCoordinate>());
292 // emit zoom level and center coordinate so that all parts of the map system gets initialized
293 // NOTE: emit is also done even if we weren't able to read initial valuef from the settings
294 // so that the default values set in the constructor are used
295 emit zoomLevelChanged(m_zoomLevel);
296 scrollToPosition(m_sceneCoordinate);
299 bool MapEngine::isAutoCenteringEnabled()
301 return m_autoCenteringEnabled;
304 bool MapEngine::isCenterTileChanged(SceneCoordinate coordinate)
306 qDebug() << __PRETTY_FUNCTION__;
308 QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
309 QPoint temp = m_centerTile;
310 m_centerTile = centerTile;
312 return (centerTile != temp);
315 qreal MapEngine::sceneResolution()
317 qDebug() << __PRETTY_FUNCTION__;
319 const int SHIFT = 200;
320 const int KM_TO_M = 1000;
321 qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
322 GeoCoordinate centerCoordinate = centerGeoCoordinate();
323 SceneCoordinate shiftedSceneCoordinate(m_sceneCoordinate.x() + SHIFT * scale,
324 m_sceneCoordinate.y());
325 GeoCoordinate shiftedCoordinate(shiftedSceneCoordinate);
326 qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
327 return (dist / SHIFT);
330 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
332 qDebug() << __PRETTY_FUNCTION__;
334 // add normal tile inside the world
335 QPoint tileNumber(x, y);
336 m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
338 // note: add 1 so odd width is rounded up and even is rounded down
339 int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
341 // duplicate to east side? (don't need to duplicate over padding)
342 if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
343 QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
344 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
347 // duplicate to west side? (don't need to duplicate over padding)
348 if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + MAP_GRID_PADDING)) {
349 QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
350 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
354 int MapEngine::normalize(int value, int min, int max)
356 qDebug() << __PRETTY_FUNCTION__;
357 Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
360 value += max - min + 1;
363 value -= max - min + 1;
368 void MapEngine::receiveOwnLocation(User *user)
370 qDebug() << __PRETTY_FUNCTION__;
373 m_ownLocation->setPos(SceneCoordinate(user->coordinates()).toPointF());
374 if (!m_ownLocation->isVisible())
375 m_ownLocation->show();
377 m_ownLocation->hide();
380 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
383 QGraphicsScene* MapEngine::scene()
385 qDebug() << __PRETTY_FUNCTION__;
390 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
392 qDebug() << __PRETTY_FUNCTION__;
394 if (m_smoothScrollRunning
395 && newState != QAbstractAnimation::Running) {
396 m_smoothScrollRunning = false;
398 // don't disable auto centering if current animation was stopped by new update from GPS
399 if (!m_scrollStartedByGps)
400 disableAutoCenteringIfRequired(m_sceneCoordinate);
403 m_scrollStartedByGps = false;
406 void MapEngine::scrollToPosition(SceneCoordinate coordinate)
408 qDebug() << __PRETTY_FUNCTION__;
411 m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
412 m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
413 m_scroller->setStartValue(m_sceneCoordinate);
414 m_scroller->setEndValue(coordinate);
415 m_smoothScrollRunning = true;
419 void MapEngine::setAutoCentering(bool enabled)
421 qDebug() << __PRETTY_FUNCTION__;
423 m_autoCenteringEnabled = enabled;
426 void MapEngine::setCenterPosition(SceneCoordinate coordinate)
428 qDebug() << __PRETTY_FUNCTION__;
430 // jump to opposite side of the world if world horizontal limit is exceeded
431 coordinate.setX(normalize(coordinate.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
433 // don't allow vertical scene coordinates go out of the map
434 coordinate.setY(qBound(double(OSM_MAP_MIN_PIXEL_Y),
436 double(OSM_MAP_MAX_PIXEL_Y)));
438 if (!m_smoothScrollRunning)
439 disableAutoCenteringIfRequired(coordinate);
441 m_sceneCoordinate = coordinate;
442 emit locationChanged(m_sceneCoordinate);
444 if (isCenterTileChanged(coordinate)) {
445 getTiles(coordinate);
446 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
449 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
450 emit newMapResolution(sceneResolution());
453 void MapEngine::setGPSEnabled(bool enabled)
455 qDebug() << __PRETTY_FUNCTION__;
457 m_gpsLocationItem->setEnabled(enabled);
460 void MapEngine::setRoute(Route &route)
462 qDebug() << __PRETTY_FUNCTION__;
466 qDebug() << __PRETTY_FUNCTION__ << "from:" << m_route.startPointName();
467 qDebug() << __PRETTY_FUNCTION__ << "to:" << m_route.endPointName();
468 qDebug() << __PRETTY_FUNCTION__ << "distance:" << m_route.totalDistance();
469 qDebug() << __PRETTY_FUNCTION__ << "estimated time:" << m_route.totalTime();
471 foreach (GeoCoordinate point, m_route.geometryPoints())
472 qDebug() << __PRETTY_FUNCTION__ << "geometry point:" << point;
474 foreach (RouteSegment segment, m_route.segments()) {
475 qDebug() << __PRETTY_FUNCTION__ << "segment:" << segment.instruction();
478 // delete old route track (if exists)
479 if (m_mapRouteItem) {
480 m_mapScene->removeItem(m_mapRouteItem);
481 delete m_mapRouteItem;
484 // create new route track
485 m_mapRouteItem = new MapRouteItem(&m_route);
486 m_mapScene->addItem(m_mapRouteItem);
488 centerAndZoomTo(m_mapRouteItem->boundingRect().toRect());
491 void MapEngine::setZoomLevel(int newZoomLevel)
493 qDebug() << __PRETTY_FUNCTION__;
495 m_zoomLevel = newZoomLevel;
499 void MapEngine::setTilesGridSize(const QSize &viewSize)
501 qDebug() << __PRETTY_FUNCTION__;
503 // there must be scrolling reserve of at least half tile added to tile amount
504 // calculated from view size
505 const qreal SCROLLING_RESERVE = 0.5;
507 // converting scene tile to tile number does cause grid centering inaccuracy of one tile
508 const int CENTER_TILE_INACCURACY = 1;
510 int gridWidth = ceil(qreal(viewSize.width()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
511 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
512 int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
513 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
515 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
517 m_tilesGridSize.setHeight(gridHeight);
518 m_tilesGridSize.setWidth(gridWidth);
521 int MapEngine::tileMaxIndex(int zoomLevel)
523 qDebug() << __PRETTY_FUNCTION__;
525 // subtract one because first tile index is zero
526 return tilesPerSide(zoomLevel) - 1;
529 QString MapEngine::tilePath(int zoomLevel, int x, int y)
531 qDebug() << __PRETTY_FUNCTION__;
533 QString tilePathString(QString::number(zoomLevel) + "/");
534 tilePathString.append(QString::number(x) + "/");
535 tilePathString.append(QString::number(y));
537 return tilePathString;
540 int MapEngine::tilesPerSide(int zoomLevel)
542 return (1 << zoomLevel);
545 void MapEngine::updateViewTilesSceneRect()
547 qDebug() << __PRETTY_FUNCTION__;
549 const QPoint ONE_TILE = QPoint(1, 1);
550 const double ONE_PIXEL = 1;
552 SceneCoordinate topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel,
553 m_viewTilesGrid.topLeft());
555 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
557 SceneCoordinate bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
558 m_viewTilesGrid.bottomRight()
560 bottomRight.setX(bottomRight.x() - ONE_PIXEL);
561 bottomRight.setY(bottomRight.y() - ONE_PIXEL);
563 m_mapScene->tilesSceneRectUpdated(QRect(topLeft.toPointF().toPoint(),
564 bottomRight.toPointF().toPoint()));
567 void MapEngine::viewResized(const QSize &size)
569 qDebug() << __PRETTY_FUNCTION__;
572 setTilesGridSize(m_viewSize);
574 emit locationChanged(m_sceneCoordinate);
575 getTiles(m_sceneCoordinate);
576 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
577 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
580 void MapEngine::viewZoomFinished()
582 qDebug() << __PRETTY_FUNCTION__;
586 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
589 if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
590 emit maxZoomLevelReached();
591 else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
592 emit minZoomLevelReached();
595 void MapEngine::zoomed()
597 emit zoomLevelChanged(m_zoomLevel);
598 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
599 m_mapScene->setZoomLevel(m_zoomLevel);
600 getTiles(m_sceneCoordinate);
601 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
602 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
603 emit newMapResolution(sceneResolution());
606 void MapEngine::zoomIn()
608 qDebug() << __PRETTY_FUNCTION__;
610 if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
617 void MapEngine::zoomOut()
619 qDebug() << __PRETTY_FUNCTION__;
621 if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {
627 void MapEngine::locationItemClicked(GeoCoordinate &swBound, GeoCoordinate &neBound)
629 qDebug() << __PRETTY_FUNCTION__;
631 centerAndZoomTo(QRect(SceneCoordinate(swBound).toPointF().toPoint(),
632 SceneCoordinate(neBound).toPointF().toPoint()));