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, bool useMargins)
134 qDebug() << __PRETTY_FUNCTION__;
136 int marginHorizontal = 50;
137 int marginVertical = 5;
140 marginHorizontal = 0;
144 // calculate the usable size of the view
145 int viewUsableHeight = m_viewSize.height() - 2 * marginHorizontal;
146 int viewUsableWidth = m_viewSize.width() - 2 * marginVertical;
148 // calculate how many levels must be zoomed out from the closest zoom level to get the rect
149 // fit inside the usable view area
151 while ((rect.height() > (viewUsableHeight * (1 << shift)))
152 || (rect.width() > (viewUsableWidth * (1 << shift)))) {
158 scrollToPosition(SceneCoordinate(double(rect.center().x()), double(rect.center().y())));
160 int zoomLevel = qBound(OSM_MIN_ZOOM_LEVEL, OSM_MAX_ZOOM_LEVEL - shift, OSM_MAX_ZOOM_LEVEL);
161 setZoomLevel(zoomLevel);
164 GeoCoordinate MapEngine::centerGeoCoordinate()
166 qDebug() << __PRETTY_FUNCTION__;
168 return GeoCoordinate(m_sceneCoordinate);
171 void MapEngine::centerToCoordinates(GeoCoordinate coordinate)
173 qDebug() << __PRETTY_FUNCTION__;
175 scrollToPosition(SceneCoordinate(coordinate));
178 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, SceneCoordinate coordinate)
180 qDebug() << __PRETTY_FUNCTION__;
182 int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
183 int x = static_cast<int>(coordinate.x() / (OSM_TILE_SIZE_X * pow));
184 int y = static_cast<int>(coordinate.y() / (OSM_TILE_SIZE_Y * pow));
189 void MapEngine::disableAutoCenteringIfRequired(SceneCoordinate coordinate)
191 if (isAutoCenteringEnabled()) {
192 int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
194 SceneCoordinate oldPixelValue(m_lastAutomaticPosition.x() / zoomFactor,
195 m_lastAutomaticPosition.y() / zoomFactor);
197 SceneCoordinate newPixelValue(coordinate.x() / zoomFactor,
198 coordinate.y() / zoomFactor);
200 if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
201 || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
203 emit mapScrolledManually();
208 void MapEngine::friendsPositionsUpdated()
210 qDebug() << __PRETTY_FUNCTION__;
212 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
215 void MapEngine::getTiles(SceneCoordinate coordinate)
217 qDebug() << __PRETTY_FUNCTION__;
219 m_viewTilesGrid = calculateTileGrid(coordinate);
220 updateViewTilesSceneRect();
221 m_mapScene->setTilesGrid(m_viewTilesGrid);
223 int topLeftX = m_viewTilesGrid.topLeft().x();
224 int topLeftY = m_viewTilesGrid.topLeft().y();
225 int bottomRightX = m_viewTilesGrid.bottomRight().x();
226 int bottomRightY = m_viewTilesGrid.bottomRight().y();
228 int tileMaxVal = MapTile::lastTileIndex(m_zoomLevel);
230 for (int x = topLeftX; x <= bottomRightX; ++x) {
231 for (int y = topLeftY; y <= bottomRightY; ++y) {
233 // map doesn't span in vertical direction, so y index must be inside the limits
234 if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
235 if (!m_mapScene->tileInScene(MapTile::tilePath(m_zoomLevel, x, y)))
236 emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
242 void MapEngine::gpsPositionUpdate(GeoCoordinate position, qreal accuracy)
244 qDebug() << __PRETTY_FUNCTION__;
246 // update GPS location item (but only if accuracy is a valid number)
247 if (!isnan(accuracy)) {
248 qreal resolution = MapScene::horizontalResolutionAtLatitude(position.latitude());
249 m_gpsLocationItem->updateItem(SceneCoordinate(position).toPointF(), accuracy, resolution);
252 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
254 // do automatic centering (if enabled)
255 if (m_autoCenteringEnabled) {
256 m_lastAutomaticPosition = SceneCoordinate(position);
257 m_scrollStartedByGps = true;
258 scrollToPosition(m_lastAutomaticPosition);
262 void MapEngine::init()
264 qDebug() << __PRETTY_FUNCTION__;
266 QSettings settings(DIRECTORY_NAME, FILE_NAME);
268 // init can be only done if both values exists in the settings
269 if (settings.contains(MAP_LAST_POSITION) && settings.contains(MAP_LAST_ZOOMLEVEL)) {
270 QVariant zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL);
271 QVariant location = settings.value(MAP_LAST_POSITION);
273 // also the init can be only done if we are able to convert variants into target data types
274 if (zoomLevel.canConvert<int>() && location.canConvert<GeoCoordinate>()) {
275 m_zoomLevel = zoomLevel.toInt();
276 m_sceneCoordinate = SceneCoordinate(location.value<GeoCoordinate>());
280 // emit zoom level and center coordinate so that all parts of the map system gets initialized
281 // NOTE: emit is also done even if we weren't able to read initial valuef from the settings
282 // so that the default values set in the constructor are used
283 emit zoomLevelChanged(m_zoomLevel);
284 scrollToPosition(m_sceneCoordinate);
287 bool MapEngine::isAutoCenteringEnabled()
289 return m_autoCenteringEnabled;
292 bool MapEngine::isCenterTileChanged(SceneCoordinate coordinate)
294 qDebug() << __PRETTY_FUNCTION__;
296 QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
297 QPoint temp = m_centerTile;
298 m_centerTile = centerTile;
300 return (centerTile != temp);
303 void MapEngine::locationItemClicked(GeoCoordinate &swBound, GeoCoordinate &neBound)
305 qDebug() << __PRETTY_FUNCTION__;
308 area.setTopRight(SceneCoordinate(neBound).toPointF().toPoint());
309 area.setBottomLeft(SceneCoordinate(swBound).toPointF().toPoint());
311 centerAndZoomTo(area, false);
314 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
316 qDebug() << __PRETTY_FUNCTION__;
318 // add normal tile inside the world
319 QPoint tileNumber(x, y);
320 m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
322 // note: add 1 so odd width is rounded up and even is rounded down
323 int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
325 // duplicate to east side? (don't need to duplicate over padding)
326 if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
327 QPoint adjustedTileNumber(tileNumber.x() + MapTile::lastTileIndex(zoomLevel) + 1,
329 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
332 // duplicate to west side? (don't need to duplicate over padding)
333 if (tileNumber.x() > (MapTile::lastTileIndex(zoomLevel)
335 + MAP_GRID_PADDING)) {
336 QPoint adjustedTileNumber(tileNumber.x() - MapTile::lastTileIndex(zoomLevel) - 1,
338 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
342 int MapEngine::normalize(int value, int min, int max)
344 qDebug() << __PRETTY_FUNCTION__;
345 Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
348 value += max - min + 1;
351 value -= max - min + 1;
356 void MapEngine::receiveOwnLocation(User *user)
358 qDebug() << __PRETTY_FUNCTION__;
361 m_ownLocation->setPos(SceneCoordinate(user->coordinates()).toPointF());
362 if (!m_ownLocation->isVisible())
363 m_ownLocation->show();
365 m_ownLocation->hide();
368 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
371 QGraphicsScene* MapEngine::scene()
373 qDebug() << __PRETTY_FUNCTION__;
378 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
380 qDebug() << __PRETTY_FUNCTION__;
382 if (m_smoothScrollRunning
383 && newState != QAbstractAnimation::Running) {
384 m_smoothScrollRunning = false;
386 // don't disable auto centering if current animation was stopped by new update from GPS
387 if (!m_scrollStartedByGps)
388 disableAutoCenteringIfRequired(m_sceneCoordinate);
391 m_scrollStartedByGps = false;
394 void MapEngine::scrollToPosition(SceneCoordinate coordinate)
396 qDebug() << __PRETTY_FUNCTION__;
399 m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
400 m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
401 m_scroller->setStartValue(m_sceneCoordinate);
402 m_scroller->setEndValue(coordinate);
403 m_smoothScrollRunning = true;
407 void MapEngine::setAutoCentering(bool enabled)
409 qDebug() << __PRETTY_FUNCTION__;
411 m_autoCenteringEnabled = enabled;
414 void MapEngine::setCenterPosition(SceneCoordinate coordinate)
416 qDebug() << __PRETTY_FUNCTION__;
418 // jump to opposite side of the world if world horizontal limit is exceeded
419 coordinate.setX(normalize(coordinate.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
421 // don't allow vertical scene coordinates go out of the map
422 coordinate.setY(qBound(double(OSM_MAP_MIN_PIXEL_Y),
424 double(OSM_MAP_MAX_PIXEL_Y)));
426 if (!m_smoothScrollRunning)
427 disableAutoCenteringIfRequired(coordinate);
429 m_sceneCoordinate = coordinate;
430 emit locationChanged(m_sceneCoordinate);
432 if (isCenterTileChanged(coordinate)) {
433 getTiles(coordinate);
434 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
437 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
438 emit newMapResolution(viewResolution());
441 void MapEngine::setGPSEnabled(bool enabled)
443 qDebug() << __PRETTY_FUNCTION__;
445 m_gpsLocationItem->setEnabled(enabled);
448 void MapEngine::setRoute(Route &route)
450 qDebug() << __PRETTY_FUNCTION__;
454 // delete old route track (if exists)
455 if (m_mapRouteItem) {
456 m_mapScene->removeItem(m_mapRouteItem);
457 delete m_mapRouteItem;
461 // create new route track
462 m_mapRouteItem = new MapRouteItem(&m_route);
463 m_mapScene->addItem(m_mapRouteItem);
465 centerAndZoomTo(m_mapRouteItem->boundingRect().toRect());
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()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
488 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
489 int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
490 + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
492 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
494 m_tilesGridSize.setHeight(gridHeight);
495 m_tilesGridSize.setWidth(gridWidth);
498 void MapEngine::updateViewTilesSceneRect()
500 qDebug() << __PRETTY_FUNCTION__;
502 const QPoint ONE_TILE = QPoint(1, 1);
503 const double ONE_PIXEL = 1;
505 SceneCoordinate topLeft = MapTile::convertTileNumberToSceneCoordinate(m_zoomLevel,
506 m_viewTilesGrid.topLeft());
508 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
510 SceneCoordinate bottomRight
511 = MapTile::convertTileNumberToSceneCoordinate(m_zoomLevel,
512 m_viewTilesGrid.bottomRight() + ONE_TILE);
513 bottomRight.setX(bottomRight.x() - ONE_PIXEL);
514 bottomRight.setY(bottomRight.y() - ONE_PIXEL);
516 m_mapScene->tilesSceneRectUpdated(QRect(topLeft.toPointF().toPoint(),
517 bottomRight.toPointF().toPoint()));
520 void MapEngine::viewResized(const QSize &size)
522 qDebug() << __PRETTY_FUNCTION__;
525 setTilesGridSize(m_viewSize);
527 emit locationChanged(m_sceneCoordinate);
528 getTiles(m_sceneCoordinate);
529 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
530 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
533 qreal MapEngine::viewResolution()
535 qDebug() << __PRETTY_FUNCTION__;
537 qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
539 return MapScene::horizontalResolutionAtLatitude(centerGeoCoordinate().latitude()) * scale;
542 void MapEngine::viewZoomFinished()
544 qDebug() << __PRETTY_FUNCTION__;
548 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
551 if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
552 emit maxZoomLevelReached();
553 else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
554 emit minZoomLevelReached();
557 void MapEngine::zoomed()
559 emit zoomLevelChanged(m_zoomLevel);
560 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
561 m_mapScene->setZoomLevel(m_zoomLevel);
562 getTiles(m_sceneCoordinate);
563 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
564 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
565 emit newMapResolution(viewResolution());
568 void MapEngine::zoomIn()
570 qDebug() << __PRETTY_FUNCTION__;
572 if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
579 void MapEngine::zoomOut()
581 qDebug() << __PRETTY_FUNCTION__;
583 if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {