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>
28 #include <QGraphicsView>
30 #include <QStringList>
33 #include <QHashIterator>
37 #include "coordinates/geocoordinate.h"
38 #include "frienditemshandler.h"
39 #include "gpslocationitem.h"
40 #include "mapcommon.h"
41 #include "mapfetcher.h"
42 #include "maprouteitem.h"
44 #include "mapscroller.h"
46 #include "network/networkaccessmanager.h"
47 #include "ownlocationitem.h"
48 #include "user/user.h"
50 #include "mapengine.h"
52 const int SMOOTH_CENTERING_TIME_MS = 1000;
54 MapEngine::MapEngine(QObject *parent)
56 m_autoCenteringEnabled(false),
57 m_scrollStartedByGps(false),
58 m_smoothScrollRunning(false),
60 m_zoomLevel(MAP_DEFAULT_ZOOM_LEVEL),
61 m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
62 m_sceneCoordinate(SceneCoordinate(GeoCoordinate(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE))),
63 m_tilesGridSize(QSize(0, 0)),
64 m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT)),
67 qDebug() << __PRETTY_FUNCTION__;
69 m_mapScene = new MapScene(this);
71 m_mapFetcher = new MapFetcher(new NetworkAccessManager(this), this);
72 connect(this, SIGNAL(fetchImage(int, int, int)),
73 m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
74 connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
75 this, SLOT(mapImageReceived(int, int, int, QPixmap)));
76 connect(m_mapFetcher, SIGNAL(error(int, int)),
77 this, SIGNAL(error(int, int)));
79 m_ownLocation = new OwnLocationItem();
80 m_ownLocation->hide(); // hide until first location info is received
81 m_mapScene->addItem(m_ownLocation);
83 m_gpsLocationItem = new GPSLocationItem();
84 m_mapScene->addItem(m_gpsLocationItem);
86 m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
87 connect(this, SIGNAL(zoomLevelChanged(int)),
88 m_friendItemsHandler, SLOT(refactorFriendItems(int)));
90 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
91 m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
93 connect(this, SIGNAL(friendImageReady(User*)),
94 m_friendItemsHandler, SLOT(friendImageReady(User*)));
96 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
97 this, SLOT(friendsPositionsUpdated()));
99 connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
100 this, SIGNAL(locationItemClicked(QList<QString>)));
102 m_scroller = &MapScroller::getInstance();
104 connect(m_scroller, SIGNAL(coordinateUpdated(SceneCoordinate)),
105 this, SLOT(setCenterPosition(SceneCoordinate)));
107 connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
108 this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
111 MapEngine::~MapEngine()
113 qDebug() << __PRETTY_FUNCTION__;
115 QSettings settings(DIRECTORY_NAME, FILE_NAME);
117 settings.setValue(MAP_LAST_POSITION, QVariant::fromValue(centerGeoCoordinate()));
118 settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
121 QRect MapEngine::calculateTileGrid(SceneCoordinate coordinate)
123 qDebug() << __PRETTY_FUNCTION__;
125 QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
128 topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
129 topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
131 return QRect(topLeft, m_tilesGridSize);
134 void MapEngine::centerAndZoomTo(QRect rect)
136 const int MARGIN_HORIZONTAL = 50;
137 const int MARGIN_VERTICAL = 5;
139 // calculate the usable size of the view
140 int viewUsableHeight = m_viewSize.height() - 2 * MARGIN_VERTICAL;
141 int viewUsableWidth = m_viewSize.width() - 2 * MARGIN_HORIZONTAL;
143 // calculate how many levels must be zoomed out from the closest zoom level to get the rect
144 // fit inside the usable view area
146 while ((rect.height() > (viewUsableHeight * (1 << shift)))
147 || (rect.width() > (viewUsableWidth * (1 << shift))))
150 scrollToPosition(SceneCoordinate(double(rect.center().x()), double(rect.center().y())));
152 int zoomLevel = qBound(OSM_MIN_ZOOM_LEVEL, OSM_MAX_ZOOM_LEVEL - shift, OSM_MAX_ZOOM_LEVEL);
153 setZoomLevel(zoomLevel);
156 GeoCoordinate MapEngine::centerGeoCoordinate()
158 qDebug() << __PRETTY_FUNCTION__;
160 return GeoCoordinate(m_sceneCoordinate);
163 void MapEngine::centerToCoordinates(GeoCoordinate coordinate)
165 qDebug() << __PRETTY_FUNCTION__;
167 scrollToPosition(SceneCoordinate(coordinate));
170 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, SceneCoordinate coordinate)
172 qDebug() << __PRETTY_FUNCTION__;
174 int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
175 int x = static_cast<int>(coordinate.x() / (OSM_TILE_SIZE_X * pow));
176 int y = static_cast<int>(coordinate.y() / (OSM_TILE_SIZE_Y * pow));
181 QRectF MapEngine::currentViewSceneRect() const
183 qDebug() << __PRETTY_FUNCTION__;
185 const QPoint ONE_PIXEL = QPoint(1, 1);
187 QGraphicsView *view = m_mapScene->views().at(0);
188 QPointF sceneTopLeft = view->mapToScene(0, 0);
189 QPoint viewBottomRight = QPoint(view->size().width(), view->size().height()) - ONE_PIXEL;
190 QPointF sceneBottomRight = view->mapToScene(viewBottomRight);
192 return QRectF(sceneTopLeft, sceneBottomRight);
195 void MapEngine::disableAutoCenteringIfRequired(SceneCoordinate coordinate)
197 if (isAutoCenteringEnabled()) {
198 int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
200 SceneCoordinate oldPixelValue(m_lastAutomaticPosition.x() / zoomFactor,
201 m_lastAutomaticPosition.y() / zoomFactor);
203 SceneCoordinate newPixelValue(coordinate.x() / zoomFactor,
204 coordinate.y() / zoomFactor);
206 if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
207 || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
209 emit mapScrolledManually();
214 void MapEngine::friendsPositionsUpdated()
216 qDebug() << __PRETTY_FUNCTION__;
218 m_mapScene->spanItems(currentViewSceneRect());
221 void MapEngine::getTiles(SceneCoordinate coordinate)
223 qDebug() << __PRETTY_FUNCTION__;
225 m_viewTilesGrid = calculateTileGrid(coordinate);
226 updateViewTilesSceneRect();
227 m_mapScene->setTilesGrid(m_viewTilesGrid);
229 int topLeftX = m_viewTilesGrid.topLeft().x();
230 int topLeftY = m_viewTilesGrid.topLeft().y();
231 int bottomRightX = m_viewTilesGrid.bottomRight().x();
232 int bottomRightY = m_viewTilesGrid.bottomRight().y();
234 int tileMaxVal = MapTile::lastTileIndex(m_zoomLevel);
236 for (int x = topLeftX; x <= bottomRightX; ++x) {
237 for (int y = topLeftY; y <= bottomRightY; ++y) {
239 // map doesn't span in vertical direction, so y index must be inside the limits
240 if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
241 if (!m_mapScene->tileInScene(MapTile::tilePath(m_zoomLevel, x, y)))
242 emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
248 void MapEngine::gpsPositionUpdate(GeoCoordinate position, qreal accuracy)
250 qDebug() << __PRETTY_FUNCTION__;
252 // update GPS location item (but only if accuracy is a valid number)
253 if (!isnan(accuracy)) {
254 qreal resolution = MapScene::horizontalResolutionAtLatitude(position.latitude());
255 m_gpsLocationItem->updateItem(SceneCoordinate(position).toPointF(), accuracy, resolution);
258 m_mapScene->spanItems(currentViewSceneRect());
260 // do automatic centering (if enabled)
261 if (m_autoCenteringEnabled) {
262 m_lastAutomaticPosition = SceneCoordinate(position);
263 m_scrollStartedByGps = true;
264 scrollToPosition(m_lastAutomaticPosition);
267 updateDirectionIndicator();
270 void MapEngine::init()
272 qDebug() << __PRETTY_FUNCTION__;
274 QSettings settings(DIRECTORY_NAME, FILE_NAME);
276 // init can be only done if both values exists in the settings
277 if (settings.contains(MAP_LAST_POSITION) && settings.contains(MAP_LAST_ZOOMLEVEL)) {
278 QVariant zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL);
279 QVariant location = settings.value(MAP_LAST_POSITION);
281 // also the init can be only done if we are able to convert variants into target data types
282 if (zoomLevel.canConvert<int>() && location.canConvert<GeoCoordinate>()) {
283 m_zoomLevel = zoomLevel.toInt();
284 m_sceneCoordinate = SceneCoordinate(location.value<GeoCoordinate>());
288 // emit zoom level and center coordinate so that all parts of the map system gets initialized
289 // NOTE: emit is also done even if we weren't able to read initial valuef from the settings
290 // so that the default values set in the constructor are used
291 emit zoomLevelChanged(m_zoomLevel);
292 scrollToPosition(m_sceneCoordinate);
295 bool MapEngine::isAutoCenteringEnabled()
297 return m_autoCenteringEnabled;
300 bool MapEngine::isCenterTileChanged(SceneCoordinate coordinate)
302 qDebug() << __PRETTY_FUNCTION__;
304 QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
305 QPoint temp = m_centerTile;
306 m_centerTile = centerTile;
308 return (centerTile != temp);
311 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
313 qDebug() << __PRETTY_FUNCTION__;
315 // add normal tile inside the world
316 QPoint tileNumber(x, y);
317 m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
319 // note: add 1 so odd width is rounded up and even is rounded down
320 int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
322 // duplicate to east side? (don't need to duplicate over padding)
323 if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
324 QPoint adjustedTileNumber(tileNumber.x() + MapTile::lastTileIndex(zoomLevel) + 1,
326 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
329 // duplicate to west side? (don't need to duplicate over padding)
330 if (tileNumber.x() > (MapTile::lastTileIndex(zoomLevel)
332 + MAP_GRID_PADDING)) {
333 QPoint adjustedTileNumber(tileNumber.x() - MapTile::lastTileIndex(zoomLevel) - 1,
335 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
339 int MapEngine::normalize(int value, int min, int max)
341 qDebug() << __PRETTY_FUNCTION__;
342 Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
345 value += max - min + 1;
348 value -= max - min + 1;
353 void MapEngine::receiveOwnLocation(User *user)
355 qDebug() << __PRETTY_FUNCTION__;
358 m_ownLocation->setPos(SceneCoordinate(user->coordinates()).toPointF());
359 if (!m_ownLocation->isVisible())
360 m_ownLocation->show();
362 m_ownLocation->hide();
365 m_mapScene->spanItems(currentViewSceneRect());
368 QGraphicsScene* MapEngine::scene()
370 qDebug() << __PRETTY_FUNCTION__;
375 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
377 qDebug() << __PRETTY_FUNCTION__;
379 if (m_smoothScrollRunning
380 && newState != QAbstractAnimation::Running) {
381 m_smoothScrollRunning = false;
383 // don't disable auto centering if current animation was stopped by new update from GPS
384 if (!m_scrollStartedByGps)
385 disableAutoCenteringIfRequired(m_sceneCoordinate);
388 m_scrollStartedByGps = false;
391 void MapEngine::scrollToPosition(SceneCoordinate coordinate)
393 qDebug() << __PRETTY_FUNCTION__;
396 m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
397 m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
398 m_scroller->setStartValue(m_sceneCoordinate);
399 m_scroller->setEndValue(coordinate);
400 m_smoothScrollRunning = true;
404 void MapEngine::setAutoCentering(bool enabled)
406 qDebug() << __PRETTY_FUNCTION__;
408 m_autoCenteringEnabled = enabled;
411 void MapEngine::setCenterPosition(SceneCoordinate coordinate)
413 qDebug() << __PRETTY_FUNCTION__;
415 // jump to opposite side of the world if world horizontal limit is exceeded
416 coordinate.setX(normalize(coordinate.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
418 // don't allow vertical scene coordinates go out of the map
419 coordinate.setY(qBound(double(OSM_MAP_MIN_PIXEL_Y),
421 double(OSM_MAP_MAX_PIXEL_Y)));
423 if (!m_smoothScrollRunning)
424 disableAutoCenteringIfRequired(coordinate);
426 m_sceneCoordinate = coordinate;
427 emit locationChanged(m_sceneCoordinate);
429 if (isCenterTileChanged(coordinate)) {
430 getTiles(coordinate);
431 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
434 m_mapScene->spanItems(currentViewSceneRect());
435 emit newMapResolution(viewResolution());
437 updateDirectionIndicator();
440 void MapEngine::setGPSEnabled(bool enabled)
442 qDebug() << __PRETTY_FUNCTION__;
444 m_gpsLocationItem->setEnabled(enabled);
447 void MapEngine::setRoute(Route &route)
449 qDebug() << __PRETTY_FUNCTION__;
453 qDebug() << __PRETTY_FUNCTION__ << "from:" << m_route.startPointName();
454 qDebug() << __PRETTY_FUNCTION__ << "to:" << m_route.endPointName();
455 qDebug() << __PRETTY_FUNCTION__ << "distance:" << m_route.totalDistance();
456 qDebug() << __PRETTY_FUNCTION__ << "estimated time:" << m_route.totalTime();
458 foreach (GeoCoordinate point, m_route.geometryPoints())
459 qDebug() << __PRETTY_FUNCTION__ << "geometry point:" << point;
461 foreach (RouteSegment segment, m_route.segments()) {
462 qDebug() << __PRETTY_FUNCTION__ << "segment:" << segment.instruction();
465 // delete old route track (if exists)
466 if (m_mapRouteItem) {
467 m_mapScene->removeItem(m_mapRouteItem);
468 delete m_mapRouteItem;
471 // create new route track
472 m_mapRouteItem = new MapRouteItem(&m_route);
473 m_mapScene->addItem(m_mapRouteItem);
475 centerAndZoomTo(m_mapRouteItem->boundingRect().toRect());
478 void MapEngine::setZoomLevel(int newZoomLevel)
480 qDebug() << __PRETTY_FUNCTION__;
482 m_zoomLevel = newZoomLevel;
486 void MapEngine::setTilesGridSize(const QSize &viewSize)
488 qDebug() << __PRETTY_FUNCTION__;
490 // there must be scrolling reserve of at least half tile added to tile amount
491 // calculated from view size
492 const qreal SCROLLING_RESERVE = 0.5;
494 // converting scene tile to tile number does cause grid centering inaccuracy of one tile
495 const int CENTER_TILE_INACCURACY = 1;
497 int gridWidth = ceil(qreal(viewSize.width()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
498 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
499 int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
500 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
502 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
504 m_tilesGridSize.setHeight(gridHeight);
505 m_tilesGridSize.setWidth(gridWidth);
508 void MapEngine::updateDirectionIndicator()
510 qDebug() << __PRETTY_FUNCTION__;
512 /// @todo implement distance calculation
513 qreal distance = m_gpsPosition.distanceTo(m_sceneCoordinate);
515 qreal direction = m_sceneCoordinate.azimuthTo(SceneCoordinate(m_gpsPosition));
517 // direction indicator triangle should be drawn only if the gps location item is not currently
518 // visible on the view
519 bool drawDirectionIndicatorTriangle = true;
520 if (currentViewSceneRect().contains(m_gpsLocationItem->pos()))
521 drawDirectionIndicatorTriangle = false;
523 emit directionIndicatorValuesUpdate(direction, distance, drawDirectionIndicatorTriangle);
526 void MapEngine::updateViewTilesSceneRect()
528 qDebug() << __PRETTY_FUNCTION__;
530 const QPoint ONE_TILE = QPoint(1, 1);
531 const double ONE_PIXEL = 1;
533 SceneCoordinate topLeft = MapTile::convertTileNumberToSceneCoordinate(m_zoomLevel,
534 m_viewTilesGrid.topLeft());
536 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
538 SceneCoordinate bottomRight
539 = MapTile::convertTileNumberToSceneCoordinate(m_zoomLevel,
540 m_viewTilesGrid.bottomRight() + ONE_TILE);
541 bottomRight.setX(bottomRight.x() - ONE_PIXEL);
542 bottomRight.setY(bottomRight.y() - ONE_PIXEL);
544 m_mapScene->tilesSceneRectUpdated(QRect(topLeft.toPointF().toPoint(),
545 bottomRight.toPointF().toPoint()));
548 void MapEngine::viewResized(const QSize &size)
550 qDebug() << __PRETTY_FUNCTION__;
553 setTilesGridSize(m_viewSize);
555 emit locationChanged(m_sceneCoordinate);
556 getTiles(m_sceneCoordinate);
557 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
558 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
561 qreal MapEngine::viewResolution()
563 qDebug() << __PRETTY_FUNCTION__;
565 qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
567 return MapScene::horizontalResolutionAtLatitude(centerGeoCoordinate().latitude()) * scale;
570 void MapEngine::viewZoomFinished()
572 qDebug() << __PRETTY_FUNCTION__;
574 updateDirectionIndicator();
578 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
581 if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
582 emit maxZoomLevelReached();
583 else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
584 emit minZoomLevelReached();
587 void MapEngine::zoomed()
589 emit zoomLevelChanged(m_zoomLevel);
590 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
591 m_mapScene->setZoomLevel(m_zoomLevel);
592 getTiles(m_sceneCoordinate);
593 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
594 m_mapScene->spanItems(currentViewSceneRect());
595 emit newMapResolution(viewResolution());
598 void MapEngine::zoomIn()
600 qDebug() << __PRETTY_FUNCTION__;
602 if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
609 void MapEngine::zoomOut()
611 qDebug() << __PRETTY_FUNCTION__;
613 if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {