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
10 Situare is free software; you can redistribute it and/or
11 modify it under the terms of the GNU General Public License
12 version 2 as published by the Free Software Foundation.
14 Situare is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with Situare; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25 #include <QtAlgorithms>
28 #include <QStringList>
31 #include <QHashIterator>
35 #include "frienditemshandler.h"
36 #include "gpslocationitem.h"
37 #include "mapcommon.h"
38 #include "mapfetcher.h"
40 #include "mapscroller.h"
42 #include "network/networkaccessmanager.h"
43 #include "ownlocationitem.h"
44 #include "user/user.h"
46 #include "mapengine.h"
48 MapEngine::MapEngine(QObject *parent)
50 m_autoCenteringEnabled(false),
52 m_zoomLevel(DEFAULT_ZOOM_LEVEL),
53 m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
54 m_lastManualPosition(QPoint(0, 0)),
55 m_tilesGridSize(QSize(0, 0)),
56 m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
58 qDebug() << __PRETTY_FUNCTION__;
60 m_mapScene = new MapScene(this);
62 m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
63 connect(this, SIGNAL(fetchImage(int, int, int)),
64 m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
65 connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
66 this, SLOT(mapImageReceived(int, int, int, QPixmap)));
67 connect(m_mapFetcher, SIGNAL(error(int)),
68 this, SIGNAL(error(int)));
70 m_ownLocation = new OwnLocationItem();
71 m_ownLocation->hide(); // hide until first location info is received
72 m_mapScene->addItem(m_ownLocation);
74 m_gpsLocationItem = new GPSLocationItem();
75 m_mapScene->addItem(m_gpsLocationItem);
77 m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
78 connect(this, SIGNAL(zoomLevelChanged(int)),
79 m_friendItemsHandler, SLOT(refactorFriendItems(int)));
81 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
82 m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
84 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
85 this, SLOT(friendsPositionsUpdated()));
87 connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
88 this, SIGNAL(locationItemClicked(QList<QString>)));
90 m_scroller = &MapScroller::getInstance();
92 connect(m_scroller, SIGNAL(coordinateUpdated(QPoint)),
93 this, SLOT(setLocation(QPoint)));
96 MapEngine::~MapEngine()
98 qDebug() << __PRETTY_FUNCTION__;
100 QSettings settings(DIRECTORY_NAME, FILE_NAME);
101 settings.setValue(MAP_LAST_POSITION,
102 convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
103 settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
106 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
108 qDebug() << __PRETTY_FUNCTION__;
110 QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
113 topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
114 topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
116 return QRect(topLeft, m_tilesGridSize);
119 QPointF MapEngine::centerGeoCoordinate()
121 qDebug() << __PRETTY_FUNCTION__;
123 return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
126 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
128 qDebug() << __PRETTY_FUNCTION__;
130 qreal longitude = latLonCoordinate.x();
131 qreal latitude = latLonCoordinate.y();
133 if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
134 return QPoint(UNDEFINED, UNDEFINED);
135 if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
136 return QPoint(UNDEFINED, UNDEFINED);
138 qreal z = static_cast<qreal>(MapEngine::tilesPerSide(MAX_MAP_ZOOM_LEVEL));
140 qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
141 qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
142 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
144 return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
147 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
149 qDebug() << __PRETTY_FUNCTION__;
151 double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
152 double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
153 double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
155 tileFactor = 1 << zoomLevel;
156 double longitude = xFactor / tileFactor * 360.0 - 180;
158 double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
159 double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
161 return QPointF(longitude, latitude);
164 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
166 qDebug() << __PRETTY_FUNCTION__;
168 int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
169 int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
170 int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
175 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
177 qDebug() << __PRETTY_FUNCTION__;
179 int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
180 int x = tileNumber.x() * TILE_SIZE_X * pow;
181 int y = tileNumber.y() * TILE_SIZE_Y * pow;
186 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
188 if (isAutoCenteringEnabled()) {
189 int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
191 QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
192 m_lastManualPosition.y() / zoomFactor);
194 QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
195 sceneCoordinate.y() / zoomFactor);
197 if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
198 (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
205 void MapEngine::friendsPositionsUpdated()
207 qDebug() << __PRETTY_FUNCTION__;
209 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
212 void MapEngine::getTiles(QPoint sceneCoordinate)
214 qDebug() << __PRETTY_FUNCTION__;
216 m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
217 updateViewTilesSceneRect();
218 m_mapScene->setTilesGrid(m_viewTilesGrid);
220 int topLeftX = m_viewTilesGrid.topLeft().x();
221 int topLeftY = m_viewTilesGrid.topLeft().y();
222 int bottomRightX = m_viewTilesGrid.bottomRight().x();
223 int bottomRightY = m_viewTilesGrid.bottomRight().y();
225 int tileMaxVal = tileMaxIndex(m_zoomLevel);
227 for (int x = topLeftX; x <= bottomRightX; ++x) {
228 for (int y = topLeftY; y <= bottomRightY; ++y) {
230 // map doesn't span in vertical direction, so y index must be inside the limits
231 if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
232 if (!m_mapScene->tileInScene(tilePath(m_zoomLevel, x, y)))
233 emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
239 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
241 qDebug() << __PRETTY_FUNCTION__;
243 m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
244 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
246 if (m_autoCenteringEnabled)
247 setViewLocation(position);
250 qreal MapEngine::greatCircleDistance(QPointF firstLocation, QPointF secondLocation)
252 qDebug() << __PRETTY_FUNCTION__;
254 const qreal TORAD = (M_PI/180);
256 qreal dLat = (secondLocation.y() - firstLocation.y())*TORAD;
257 qreal dLon = (secondLocation.x() - firstLocation.x())*TORAD;
258 qreal a = pow(sin(dLat/2),2) + cos(firstLocation.y()*TORAD) * cos(secondLocation.y()*TORAD)
259 * pow(sin(dLon/2),2);
260 qreal c = 2 * atan2(sqrt(a), sqrt(1-a));
262 return (EARTH_RADIUS * c);
265 void MapEngine::init()
267 qDebug() << __PRETTY_FUNCTION__;
269 QPointF startLocation;
270 QSettings settings(DIRECTORY_NAME, FILE_NAME);
272 if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
273 == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
274 ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
276 startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
277 m_zoomLevel = qBound(MIN_VIEW_ZOOM_LEVEL, DEFAULT_START_ZOOM_LEVEL, MAX_MAP_ZOOM_LEVEL);
279 m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
280 startLocation = settings.value(MAP_LAST_POSITION,
281 ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
284 emit zoomLevelChanged(m_zoomLevel);
285 setViewLocation(QPointF(startLocation.x(), startLocation.y()));
288 bool MapEngine::isAutoCenteringEnabled()
290 return m_autoCenteringEnabled;
293 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
295 qDebug() << __PRETTY_FUNCTION__;
297 QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
298 QPoint temp = m_centerTile;
299 m_centerTile = centerTile;
301 return (centerTile != temp);
304 qreal MapEngine::sceneResolution()
306 qDebug() << __PRETTY_FUNCTION__;
308 const int SHIFT = 200;
309 const int KM_TO_M = 1000;
310 qreal scale = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
311 QPointF centerCoordinate = centerGeoCoordinate();
312 QPoint shiftedSceneCoordinate = QPoint(m_sceneCoordinate.x() + SHIFT*scale
313 , m_sceneCoordinate.y());
314 QPointF shiftedCoordinate = convertSceneCoordinateToLatLon(m_zoomLevel, shiftedSceneCoordinate);
315 qreal dist = greatCircleDistance(centerCoordinate, shiftedCoordinate) * KM_TO_M;
316 return (dist / SHIFT);
319 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
321 qDebug() << __PRETTY_FUNCTION__;
323 // add normal tile inside the world
324 QPoint tileNumber(x, y);
325 m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
327 // note: add 1 so odd width is rounded up and even is rounded down
328 int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
330 // duplicate to east side? (don't need to duplicate over padding)
331 if (tileNumber.x() < (tilesGridWidthHalf - GRID_PADDING)) {
332 QPoint adjustedTileNumber(tileNumber.x() + tileMaxIndex(zoomLevel) + 1, tileNumber.y());
333 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
336 // duplicate to west side? (don't need to duplicate over padding)
337 if (tileNumber.x() > (tileMaxIndex(zoomLevel) - tilesGridWidthHalf + GRID_PADDING)) {
338 QPoint adjustedTileNumber(tileNumber.x() - tileMaxIndex(zoomLevel) - 1, tileNumber.y());
339 m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
343 int MapEngine::normalize(int value, int min, int max)
345 qDebug() << __PRETTY_FUNCTION__;
346 Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
349 value += max - min + 1;
352 value -= max - min + 1;
357 void MapEngine::receiveOwnLocation(User *user)
359 qDebug() << __PRETTY_FUNCTION__;
362 QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
363 if (m_ownLocation->pos().toPoint() != newPosition) {
364 m_ownLocation->setPos(newPosition);
367 if (!m_ownLocation->isVisible())
368 m_ownLocation->show();
370 m_ownLocation->hide();
373 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
376 QGraphicsScene* MapEngine::scene()
378 qDebug() << __PRETTY_FUNCTION__;
383 void MapEngine::setAutoCentering(bool enabled)
385 m_autoCenteringEnabled = enabled;
388 void MapEngine::setGPSEnabled(bool enabled)
390 m_gpsLocationItem->setEnabled(enabled);
393 void MapEngine::setLocation(QPoint sceneCoordinate)
395 qDebug() << __PRETTY_FUNCTION__;
397 // jump to opposite side of the world if world horizontal limit is exceeded
398 sceneCoordinate.setX(normalize(sceneCoordinate.x(), MAP_MIN_PIXEL_X, MAP_MAX_PIXEL_X));
400 // don't allow vertical scene coordinates go out of the map
401 sceneCoordinate.setY(qBound(MAP_MIN_PIXEL_Y, sceneCoordinate.y(), MAP_MAX_PIXEL_Y));
403 if (disableAutoCentering(sceneCoordinate))
404 emit mapScrolledManually();
406 m_sceneCoordinate = sceneCoordinate;
407 emit locationChanged(m_sceneCoordinate);
409 if (isCenterTileChanged(sceneCoordinate)) {
410 getTiles(sceneCoordinate);
411 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
414 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
415 emit newMapResolution(sceneResolution());
418 void MapEngine::setZoomLevel(int newZoomLevel)
420 qDebug() << __PRETTY_FUNCTION__;
422 m_zoomLevel = newZoomLevel;
426 void MapEngine::setTilesGridSize(const QSize &viewSize)
428 qDebug() << __PRETTY_FUNCTION__;
430 // there must be scrolling reserve of at least half tile added to tile amount
431 // calculated from view size
432 const qreal SCROLLING_RESERVE = 0.5;
434 // converting scene tile to tile number does cause grid centering inaccuracy of one tile
435 const int CENTER_TILE_INACCURACY = 1;
437 int gridWidth = ceil(qreal(viewSize.width()) / TILE_SIZE_X + SCROLLING_RESERVE)
438 + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
439 int gridHeight = ceil(qreal(viewSize.height()) / TILE_SIZE_Y + SCROLLING_RESERVE)
440 + CENTER_TILE_INACCURACY + (GRID_PADDING * 2);
442 m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
444 m_tilesGridSize.setHeight(gridHeight);
445 m_tilesGridSize.setWidth(gridWidth);
448 void MapEngine::setViewLocation(QPointF latLonCoordinate)
450 qDebug() << __PRETTY_FUNCTION__;
452 QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
454 m_lastManualPosition = sceneCoordinate;
456 setLocation(sceneCoordinate);
459 int MapEngine::tileMaxIndex(int zoomLevel)
461 qDebug() << __PRETTY_FUNCTION__;
463 // subtract one because first tile index is zero
464 return tilesPerSide(zoomLevel) - 1;
467 QString MapEngine::tilePath(int zoomLevel, int x, int y)
469 qDebug() << __PRETTY_FUNCTION__;
471 QString tilePathString(QString::number(zoomLevel) + "/");
472 tilePathString.append(QString::number(x) + "/");
473 tilePathString.append(QString::number(y));
475 return tilePathString;
478 int MapEngine::tilesPerSide(int zoomLevel)
480 return (1 << zoomLevel);
483 void MapEngine::updateViewTilesSceneRect()
485 qDebug() << __PRETTY_FUNCTION__;
487 const QPoint ONE_TILE = QPoint(1, 1);
488 const QPoint ONE_PIXEL = QPoint(1, 1);
490 QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
491 // one tile - one pixel is added because returned coordinates are pointing to upper left corner
493 QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
494 m_viewTilesGrid.bottomRight()
495 + ONE_TILE) - ONE_PIXEL;
497 m_mapScene->tilesSceneRectUpdated(QRect(topLeft, bottomRight));
500 void MapEngine::viewResized(const QSize &size)
502 qDebug() << __PRETTY_FUNCTION__;
505 setTilesGridSize(m_viewSize);
507 emit locationChanged(m_sceneCoordinate);
508 getTiles(m_sceneCoordinate);
509 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
510 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
513 void MapEngine::viewZoomFinished()
515 qDebug() << __PRETTY_FUNCTION__;
519 m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
522 if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
523 emit maxZoomLevelReached();
524 else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
525 emit minZoomLevelReached();
528 void MapEngine::zoomed()
530 emit zoomLevelChanged(m_zoomLevel);
531 m_mapScene->setTilesDrawingLevels(m_zoomLevel);
532 m_mapScene->setZoomLevel(m_zoomLevel);
533 getTiles(m_sceneCoordinate);
534 m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
535 m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
536 emit newMapResolution(sceneResolution());
539 void MapEngine::zoomIn()
541 qDebug() << __PRETTY_FUNCTION__;
543 if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
550 void MapEngine::zoomOut()
552 qDebug() << __PRETTY_FUNCTION__;
554 if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {