Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qdeclarativegeomap.cpp
Go to the documentation of this file.
1// Copyright (C) 2015 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
11#include "qgeomap_p.h"
13#include <QtPositioning/QGeoCircle>
14#include <QtPositioning/QGeoRectangle>
15#include <QtPositioning/QGeoPath>
16#include <QtPositioning/QGeoPolygon>
17#include <QtQuick/QQuickWindow>
18#include <QtQuick/QSGRectangleNode>
19#include <QtQml/qqmlinfo.h>
20#include <QtQuick/private/qquickitem_p.h>
21#include <cmath>
22
23QT_BEGIN_NAMESPACE
24
25static qreal sanitizeBearing(qreal bearing)
26{
27 bearing = std::fmod(bearing, qreal(360.0));
28 if (bearing < 0.0)
29 bearing += 360.0;
30
31 return bearing;
32}
33
34/*!
35 \qmltype Map
36 \nativetype QDeclarativeGeoMap
37 \inqmlmodule QtLocation
38 \ingroup qml-QtLocation5-maps
39 \since QtLocation 5.0
40
41 \brief The Map type displays a map.
42
43 The Map type is used to display a map or image of the Earth, with
44 the capability to also display interactive objects tied to the map's
45 surface.
46
47 There are a variety of different ways to visualize the Earth's surface
48 in a 2-dimensional manner, but all of them involve some kind of projection:
49 a mathematical relationship between the 3D coordinates (latitude, longitude
50 and altitude) and 2D coordinates (X and Y in pixels) on the screen.
51
52 Different sources of map data can use different projections, and from the
53 point of view of the Map type, we treat these as one replaceable unit:
54 the Map plugin. A Map plugin consists of a data source, as well as all other
55 details needed to display its data on-screen.
56
57 The current Map plugin in use is contained in the \l plugin property of
58 the Map item. In order to display any image in a Map item, you will need
59 to set this property. See the \l Plugin type for a description of how
60 to retrieve an appropriate plugin for use.
61
62 The geographic region displayed in the Map item is referred to as its
63 viewport, and this is defined by the properties \l center, and
64 \l zoomLevel. The \l center property contains a
65 \l [QtPositioning]{geoCoordinate} specifying the center of the viewport,
66 while \l zoomLevel controls the scale of the map. See each of these
67 properties for further details about their values.
68
69 When the map is displayed, each possible geographic coordinate that is
70 visible will map to some pixel X and Y coordinate on the screen. To perform
71 conversions between these two, Map provides the \l toCoordinate and
72 \l fromCoordinate functions, which are of general utility.
73
74 \section2 Map Objects
75
76 Map related objects can be declared within the body of a Map object in Qt Quick and will
77 automatically appear on the Map. To add an object programmatically, first be
78 sure it is created with the Map as its parent (for example in an argument to
79 Component::createObject).
80 Then call the \l addMapItem method on the Map, if the type of this object is one of
81 \l MapCircle, \l MapRectangle, \l MapPolyline, \l MapPolygon, \l MapRoute or \l MapQuickItem.
82 A corresponding \l removeMapItem method also exists to do the opposite and
83 remove any of the above types of map objects from the Map.
84
85 Moving Map objects around, resizing them or changing their shape normally
86 does not involve any special interaction with Map itself -- changing these
87 properties in a map object will automatically update the display.
88
89 \section2 Performance
90
91 Maps are rendered using OpenGL (ES) and the Qt Scene Graph stack, and as
92 a result perform quite well where GL accelerated hardware is available.
93
94 For "online" Maps, network bandwidth and latency can be major
95 contributors to the user's perception of performance. Extensive caching is
96 performed to mitigate this, but such mitigation is not always perfect.
97
98 In general, large and complex Map items such as polygons and polylines with
99 large numbers of vertices can have an adverse effect on UI performance.
100
101 \section2 Example Usage
102
103 The following snippet shows a simple Map and the necessary Plugin type
104 to use it. The map is centered over Oslo, Norway, with zoom level 14.
105
106 \quotefromfile minimal_map/main.qml
107 \skipto import
108 \printuntil Window {
109 \dots
110 \skipto Plugin
111 \printuntil
112
113 \image minimal_map.png {Map item centered on Oslo at zoom level 14}
114*/
115
116/*!
117 \qmlsignal QtLocation::Map::copyrightLinkActivated(string link)
118
119 This signal is emitted when the user clicks on a \a link in the copyright notice. The
120 application should open the link in a browser or display its contents to the user.
121*/
122
123QDeclarativeGeoMap::QDeclarativeGeoMap(QQuickItem *parent)
124 : QQuickItem(parent)
125{
126 setFlags(QQuickItem::ItemHasContents | QQuickItem::ItemClipsChildrenToShape);
127
128 m_activeMapType = QGeoMapType(QGeoMapType::NoMap,
129 tr("No Map"),
130 tr("No Map"),
131 false, false,
132 0,
133 QByteArrayLiteral(""),
134 QGeoCameraCapabilities());
135 m_cameraData.setCenter(QGeoCoordinate(51.5073,-0.1277)); //London city center
136 m_cameraData.setZoomLevel(8.0);
137
138 m_cameraCapabilities.setTileSize(256);
139 m_cameraCapabilities.setSupportsBearing(true);
140 m_cameraCapabilities.setSupportsTilting(true);
141 m_cameraCapabilities.setMinimumZoomLevel(0);
142 m_cameraCapabilities.setMaximumZoomLevel(30);
143 m_cameraCapabilities.setMinimumTilt(0);
144 m_cameraCapabilities.setMaximumTilt(89.5);
145 m_cameraCapabilities.setMinimumFieldOfView(1);
146 m_cameraCapabilities.setMaximumFieldOfView(179);
147
148 m_minimumZoomLevel = m_cameraCapabilities.minimumZoomLevel();
149 m_maximumZoomLevel = m_cameraCapabilities.maximumZoomLevel();
150 m_minimumTilt = m_cameraCapabilities.minimumTilt();
151 m_maximumTilt = m_cameraCapabilities.maximumTilt();
152 m_minimumFieldOfView = m_cameraCapabilities.minimumFieldOfView();
153 m_maximumFieldOfView = m_cameraCapabilities.maximumFieldOfView();
154}
155
156QDeclarativeGeoMap::~QDeclarativeGeoMap()
157{
158 // Removing map items from m_map
159 if (m_map) {
160 m_map->clearMapItems();
161 }
162
163 // Remove the items from the map, making them deletable.
164 // Go in the same order as in removeMapChild: views, groups, then items
165 if (!m_mapViews.isEmpty()) {
166 const auto mapViews = m_mapViews;
167 for (QDeclarativeGeoMapItemView *v : mapViews) { // so that removeMapItemView_real can safely modify m_mapViews;
168 if (!v)
169 continue;
170
171 QQuickItem *parent = v->parentItem();
172 QDeclarativeGeoMapItemGroup *group = qobject_cast<QDeclarativeGeoMapItemGroup *>(parent);
173 if (group)
174 continue; // Ignore non-top-level MIVs. They will be recursively processed.
175 // Identify them as being parented by a MapItemGroup.
176
177 removeMapItemView_real(v);
178 }
179 }
180
181 if (!m_mapItemGroups.isEmpty()) {
182 const auto mapGroups = m_mapItemGroups;
183 for (QDeclarativeGeoMapItemGroup *g : mapGroups) {
184 if (!g)
185 continue;
186
187 QQuickItem *parent =g->parentItem();
188 QDeclarativeGeoMapItemGroup *group = qobject_cast<QDeclarativeGeoMapItemGroup *>(parent);
189 if (group)
190 continue; // Ignore non-top-level Groups. They will be recursively processed.
191 // Identify them as being parented by a MapItemGroup.
192
193 removeMapItemGroup_real(g);
194 }
195 }
196
197 // remove any remaining map items associations
198 const auto mapItems = m_mapItems;
199 for (auto mi: mapItems)
200 removeMapItem_real(mi.data());
201
202 if (m_copyrights.data())
203 delete m_copyrights.data();
204 m_copyrights.clear();
205
206 delete m_map; // map objects get reset here
207}
208
209void QDeclarativeGeoMap::onSupportedMapTypesChanged()
210{
211 m_supportedMapTypes = m_mappingManager->supportedMapTypes();
212 if (m_supportedMapTypes.isEmpty()) {
213 m_map->setActiveMapType(QGeoMapType()); // no supported map types: setting an invalid one
214 } else if (!m_supportedMapTypes.contains(m_map->activeMapType())) {
215 QGeoMapType type = m_supportedMapTypes.at(0);
216 m_activeMapType = type;
217 m_map->setActiveMapType(type);
218 }
219
220 emit supportedMapTypesChanged();
221}
222
223void QDeclarativeGeoMap::setError(QGeoServiceProvider::Error error, const QString &errorString)
224{
225 if (m_error == error && m_errorString == errorString)
226 return;
227 m_error = error;
228 m_errorString = errorString;
229 emit errorChanged();
230}
231
232/*!
233 \internal
234 Called when the mapping manager is initialized AND the declarative element has a valid size > 0
235*/
236void QDeclarativeGeoMap::initialize()
237{
238 // try to keep change signals in the end
239 bool visibleAreaHasChanged = false;
240
241 QGeoCoordinate center = m_cameraData.center();
242
243 setMinimumZoomLevel(m_map->minimumZoom(), false);
244
245 double bearing = m_cameraData.bearing();
246 double tilt = m_cameraData.tilt();
247 double fov = m_cameraData.fieldOfView(); // Must be 45.0
248 QGeoCameraData cameraData = m_cameraData;
249
250 if (!m_cameraCapabilities.supportsBearing() && bearing != 0.0)
251 cameraData.setBearing(0);
252
253 if (!m_cameraCapabilities.supportsTilting() && tilt != 0.0)
254 cameraData.setTilt(0);
255
256 m_map->setVisibleArea(m_visibleArea);
257 if (m_map->visibleArea() != m_visibleArea)
258 visibleAreaHasChanged = true;
259
260 cameraData.setFieldOfView(qBound(m_cameraCapabilities.minimumFieldOfView(),
261 fov,
262 m_cameraCapabilities.maximumFieldOfView()));
263
264 // set latitude boundary check
265 m_maximumViewportLatitude = m_map->maximumCenterLatitudeAtZoom(cameraData);
266 m_minimumViewportLatitude = m_map->minimumCenterLatitudeAtZoom(cameraData);
267
268 center.setLatitude(qBound(m_minimumViewportLatitude, center.latitude(), m_maximumViewportLatitude));
269 cameraData.setCenter(center);
270
271 connect(m_map.data(), &QGeoMap::cameraDataChanged,
272 this, &QDeclarativeGeoMap::onCameraDataChanged);
273 m_map->setCameraData(cameraData); // This normally triggers property changed signals.
274 // BUT not in this case, since m_cameraData is already == cameraData.
275 // So, emit visibleRegionChanged() separately, as
276 // the effective visible region becomes available only now.
277
278 m_initialized = true;
279
280 if (visibleAreaHasChanged)
281 emit visibleAreaChanged();
282 connect(m_map.data(), &QGeoMap::visibleAreaChanged, this, &QDeclarativeGeoMap::visibleAreaChanged);
283
284 emit mapReadyChanged(true);
285 emit visibleRegionChanged();
286
287 if (m_copyrights) // To not update during initialize()
288 update();
289}
290
291/*!
292 \internal
293*/
294void QDeclarativeGeoMap::pluginReady()
295{
296 QGeoServiceProvider *provider = m_plugin->sharedGeoServiceProvider();
297 m_mappingManager = provider->mappingManager();
298
299 if (provider->mappingError() != QGeoServiceProvider::NoError) {
300 setError(provider->mappingError(), provider->mappingErrorString());
301 return;
302 }
303
304 if (!m_mappingManager) {
305 //TODO Should really be EngineNotSetError (see QML GeoCodeModel)
306 setError(QGeoServiceProvider::NotSupportedError, tr("Plugin does not support mapping."));
307 return;
308 }
309
310 if (!m_mappingManager->isInitialized()) {
311 connect(m_mappingManager, &QGeoMappingManager::initialized,
312 this, &QDeclarativeGeoMap::mappingManagerInitialized);
313 } else {
314 mappingManagerInitialized();
315 }
316
317 // make sure this is only called once
318 disconnect(m_plugin, &QDeclarativeGeoServiceProvider::attached,
319 this, &QDeclarativeGeoMap::pluginReady);
320}
321
322/*!
323 \internal
324*/
325void QDeclarativeGeoMap::componentComplete()
326{
327 m_componentCompleted = true;
328 populateMap();
329 QQuickItem::componentComplete();
330}
331
332/*!
333 \internal
334
335 This may happen before mappingManagerInitialized()
336*/
337void QDeclarativeGeoMap::populateMap()
338{
339 QSet<QObject *> kids(children().cbegin(), children().cend());
340 const QList<QQuickItem *> quickKids = childItems();
341 for (QQuickItem *ite: quickKids)
342 kids.insert(ite);
343
344 for (QObject *k : std::as_const(kids)) {
345 addMapChild(k);
346 }
347}
348
349/*!
350 \internal
351*/
352void QDeclarativeGeoMap::setupMapView(QDeclarativeGeoMapItemView *view)
353{
354 view->setMap(this);
355}
356
357/*!
358 * \internal
359 */
360QSGNode *QDeclarativeGeoMap::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
361{
362 if (!m_map) {
363 delete oldNode;
364 return nullptr;
365 }
366
367 QSGRectangleNode *root = static_cast<QSGRectangleNode *>(oldNode);
368 if (!root)
369 root = window()->createRectangleNode();
370
371 root->setRect(boundingRect());
372 root->setColor(m_color);
373
374 QSGNode *content = root->childCount() ? root->firstChild() : 0;
375 content = m_map->updateSceneGraph(content, window());
376 if (content && root->childCount() == 0)
377 root->appendChildNode(content);
378
379 return root;
380}
381
382/*!
383 \qmlproperty Plugin QtLocation::Map::plugin
384
385 This property holds the plugin which provides the mapping functionality.
386
387 This is a write-once property. Once the map has a plugin associated with
388 it, any attempted modifications of the plugin will be ignored.
389*/
390
391void QDeclarativeGeoMap::setPlugin(QDeclarativeGeoServiceProvider *plugin)
392{
393 if (m_plugin) {
394 qmlWarning(this) << QStringLiteral("Plugin is a write-once property, and cannot be set again.");
395 return;
396 }
397 m_plugin = plugin;
398 emit pluginChanged(m_plugin);
399
400 if (m_plugin->isAttached()) {
401 pluginReady();
402 } else {
403 connect(m_plugin, &QDeclarativeGeoServiceProvider::attached,
404 this, &QDeclarativeGeoMap::pluginReady);
405 }
406}
407
408/*!
409 \internal
410*/
411void QDeclarativeGeoMap::onCameraCapabilitiesChanged(const QGeoCameraCapabilities &oldCameraCapabilities)
412{
413 if (m_map->cameraCapabilities() == oldCameraCapabilities)
414 return;
415
416 m_cameraCapabilities = m_map->cameraCapabilities();
417
418 setMaximumZoomLevel(m_cameraCapabilities.maximumZoomLevel(), false);
419 setMinimumZoomLevel(m_cameraCapabilities.minimumZoomLevel(), false);
420 setMinimumTilt(m_cameraCapabilities.minimumTilt(), false);
421 setMaximumTilt(m_cameraCapabilities.maximumTilt(), false);
422 setMinimumFieldOfView(m_cameraCapabilities.minimumFieldOfView(), false);
423 setMaximumFieldOfView(m_cameraCapabilities.maximumFieldOfView(), false);
424}
425
426/*!
427 \internal
428 this function will only be ever called once
429*/
430void QDeclarativeGeoMap::mappingManagerInitialized()
431{
432 m_map = m_mappingManager->createMap(this);
433
434 if (!m_map)
435 return;
436
437 // Any map items that were added before the plugin was ready
438 // need to have setMap called again
439 for (const QPointer<QDeclarativeGeoMapItemBase> &item : std::as_const(m_mapItems)) {
440 if (item) {
441 item->setMap(this, m_map);
442 m_map->addMapItem(item.data()); // m_map filters out what is not supported.
443 }
444 }
445
446 /* COPY NOTICE SETUP */
447 m_copyrights = new QDeclarativeGeoMapCopyrightNotice(this);
448 m_copyrights->setCopyrightsZ(m_maxChildZ + 1);
449 m_copyrights->setCopyrightsVisible(m_copyrightsVisible);
450 m_copyrights->setMapSource(this);
451
452 m_supportedMapTypes = m_mappingManager->supportedMapTypes();
453
454 if (m_activeMapType != QGeoMapType() && m_plugin->name().toLatin1() == m_activeMapType.pluginName()) {
455 m_map->setActiveMapType(m_activeMapType);
456 } else {
457 if (!m_supportedMapTypes.isEmpty()) {
458 m_activeMapType = m_supportedMapTypes.at(0);
459 m_map->setActiveMapType(m_activeMapType);
460 } else {
461 m_activeMapType = QGeoMapType(QGeoMapType::NoMap,
462 tr("No Map"),
463 tr("No Map"),
464 false,
465 false,
466 0,
467 QByteArrayLiteral(""),
468 QGeoCameraCapabilities());
469 }
470 }
471
472 // Update camera capabilities
473 onCameraCapabilitiesChanged(m_cameraCapabilities);
474
475 // Map tiles are built in this call. m_map->minimumZoom() becomes operational
476 // after this has been called at least once, after creation.
477 // However, getting into the following block may fire a copyrightsChanged that would get lost,
478 // as the connections are set up after.
479 QString copyrightString;
480 QImage copyrightImage;
481 if (!m_initialized && width() > 0 && height() > 0) {
482 QMetaObject::Connection copyrightStringCatcherConnection =
483 connect(m_map.data(), &QGeoMap::copyrightsChanged, this,
484 [&copyrightString](const QString &copy){ copyrightString = copy; });
485 QMetaObject::Connection copyrightImageCatcherConnection =
486 connect(m_map.data(), &QGeoMap::copyrightsImageChanged, this,
487 [&copyrightImage](const QImage &copy){ copyrightImage = copy; });
488 m_map->setViewportSize(QSize(width(), height()));
489 initialize(); // This emits the caught signals above
490 QObject::disconnect(copyrightStringCatcherConnection);
491 QObject::disconnect(copyrightImageCatcherConnection);
492 }
493
494
495 /* COPYRIGHT SIGNALS REWIRING */
496 connect(m_map.data(), &QGeoMap::copyrightsImageChanged,
497 this, &QDeclarativeGeoMap::copyrightsImageChanged);
498 connect(m_map.data(), &QGeoMap::copyrightsChanged,
499 this, &QDeclarativeGeoMap::copyrightsChanged);
500 if (!copyrightString.isEmpty())
501 emit m_map->copyrightsChanged(copyrightString);
502 else if (!copyrightImage.isNull())
503 emit m_map->copyrightsImageChanged(copyrightImage);
504
505 m_window = window();
506 if (m_window) {
507 connect(m_window, &QQuickWindow::beforeSynchronizing,
508 this, &QDeclarativeGeoMap::updateItemToWindowTransform, Qt::DirectConnection);
509 }
510 connect(m_map.data(), &QGeoMap::sgNodeChanged, this, &QDeclarativeGeoMap::onSGNodeChanged);
511 connect(m_map.data(), &QGeoMap::cameraCapabilitiesChanged,
512 this, &QDeclarativeGeoMap::onCameraCapabilitiesChanged);
513
514 // This prefetches a buffer around the map
515 m_map->prefetchData();
516
517 connect(m_mappingManager, &QGeoMappingManager::supportedMapTypesChanged,
518 this, &QDeclarativeGeoMap::onSupportedMapTypesChanged);
519 emit minimumZoomLevelChanged(minimumZoomLevel());
520 emit maximumZoomLevelChanged(maximumZoomLevel());
521 emit supportedMapTypesChanged();
522 emit activeMapTypeChanged();
523
524 // Any map item groups that were added before the plugin was ready
525 // DO NOT need to have setMap called again on their children map items
526 // because they have been added to m_mapItems, which is processed right above.
527
528 if (m_initialized)
529 update();
530}
531
532/*!
533 \internal
534*/
535QDeclarativeGeoServiceProvider *QDeclarativeGeoMap::plugin() const
536{
537 return m_plugin;
538}
539
540/*!
541 \internal
542 Sets the gesture areas minimum zoom level. If the camera capabilities
543 has been set this method honors the boundaries set by it.
544 The minimum zoom level will also have a lower bound dependent on the size
545 of the canvas, effectively preventing to display out of bounds areas.
546*/
547void QDeclarativeGeoMap::setMinimumZoomLevel(qreal minimumZoomLevel, bool userSet)
548{
549 if (minimumZoomLevel >= 0) {
550 qreal oldMinimumZoomLevel = this->minimumZoomLevel();
551
552 if (userSet)
553 m_userMinimumZoomLevel = minimumZoomLevel;
554 else
555 m_minimumZoomLevel = minimumZoomLevel;
556
557 if (zoomLevel() < minimumZoomLevel)
558 setZoomLevel(minimumZoomLevel);
559
560 if (oldMinimumZoomLevel != this->minimumZoomLevel())
561 emit minimumZoomLevelChanged(this->minimumZoomLevel());
562 }
563}
564
565/*!
566 \qmlproperty real QtLocation::Map::minimumZoomLevel
567
568 This property holds the minimum valid zoom level for the map.
569
570 The minimum zoom level defined by the \l plugin used is a lower bound for
571 this property. However, the returned value is also canvas-size-dependent, and
572 can be higher than the user-specified value, or than the minimum zoom level
573 defined by the plugin used, to prevent the map from being smaller than the
574 viewport in either dimension.
575
576 If the \l plugin property is not set or the plugin does not support mapping, this property is \c 0.
577*/
578
579qreal QDeclarativeGeoMap::minimumZoomLevel() const
580{
581 return qMax(qMin(m_maximumZoomLevel, m_userMinimumZoomLevel), m_minimumZoomLevel);
582}
583
584/*!
585 \internal
586 Sets the gesture areas maximum zoom level. If the camera capabilities
587 has been set this method honors the boundaries set by it.
588*/
589void QDeclarativeGeoMap::setMaximumZoomLevel(qreal maximumZoomLevel, bool userSet)
590{
591 if (maximumZoomLevel >= 0) {
592 qreal oldMaximumZoomLevel = this->maximumZoomLevel();
593
594 if (userSet)
595 m_userMaximumZoomLevel = maximumZoomLevel;
596 else
597 m_maximumZoomLevel = maximumZoomLevel;
598
599 if (zoomLevel() > maximumZoomLevel)
600 setZoomLevel(maximumZoomLevel);
601
602 if (oldMaximumZoomLevel != this->maximumZoomLevel())
603 emit maximumZoomLevelChanged(this->maximumZoomLevel());
604 }
605}
606
607/*!
608 \qmlproperty real QtLocation::Map::maximumZoomLevel
609
610 This property holds the maximum valid zoom level for the map.
611
612 The maximum zoom level is defined by the \l plugin used.
613 If the \l plugin property is not set or the plugin does not support mapping, this property is \c 30.
614*/
615
616qreal QDeclarativeGeoMap::maximumZoomLevel() const
617{
618 return qMin(qMax(m_minimumZoomLevel, m_userMaximumZoomLevel), m_maximumZoomLevel);
619}
620
621/*!
622 \qmlproperty real QtLocation::Map::zoomLevel
623
624 This property holds the zoom level for the map.
625
626 Larger values for the zoom level provide more detail. Zoom levels
627 are always non-negative. The default value is 8.0. Depending on the plugin in use,
628 values outside the [minimumZoomLevel, maximumZoomLevel] range, which represent the range for which
629 tiles are available, may be accepted, or clamped.
630*/
631void QDeclarativeGeoMap::setZoomLevel(qreal zoomLevel)
632{
633 return setZoomLevel(zoomLevel, m_cameraCapabilities.overzoomEnabled());
634}
635
636/*!
637 \internal
638
639 Sets the zoom level.
640 Larger values for the zoom level provide more detail. Zoom levels
641 are always non-negative. The default value is 8.0. Values outside the
642 [minimumZoomLevel, maximumZoomLevel] range, which represent the range for which
643 tiles are available, can be accepted or clamped by setting the overzoom argument
644 to true or false respectively.
645*/
646void QDeclarativeGeoMap::setZoomLevel(qreal zoomLevel, bool overzoom)
647{
648 if (zoomLevel < 0)
649 return;
650
651 if (m_initialized) {
652 QGeoCameraData cameraData = m_map->cameraData();
653 if (cameraData.zoomLevel() == zoomLevel)
654 return;
655
656 cameraData.setZoomLevel(qBound<qreal>(overzoom ? m_map->minimumZoom() : m_cameraCapabilities.minimumZoomLevel(),
657 zoomLevel,
658 overzoom ? 30 : maximumZoomLevel()));
659 m_maximumViewportLatitude = m_map->maximumCenterLatitudeAtZoom(cameraData);
660 m_minimumViewportLatitude = m_map->minimumCenterLatitudeAtZoom(cameraData);
661 QGeoCoordinate coord = cameraData.center();
662 coord.setLatitude(qBound(m_minimumViewportLatitude, coord.latitude(), m_maximumViewportLatitude));
663 cameraData.setCenter(coord);
664 m_map->setCameraData(cameraData);
665 } else {
666 const bool zlHasChanged = zoomLevel != m_cameraData.zoomLevel();
667 m_cameraData.setZoomLevel(zoomLevel);
668 if (zlHasChanged) {
669 emit zoomLevelChanged(zoomLevel);
670 // do not emit visibleRegionChanged() here, because, if the map isn't initialized,
671 // the getter won't return anything updated
672 }
673 }
674}
675
676bool QDeclarativeGeoMap::addMapChild(QObject *child)
677{
678 // dispatch items appropriately
679 QDeclarativeGeoMapItemView *mapView = qobject_cast<QDeclarativeGeoMapItemView *>(child);
680 if (mapView)
681 return addMapItemView_real(mapView);
682
683 QDeclarativeGeoMapItemGroup *itemGroup = qobject_cast<QDeclarativeGeoMapItemGroup *>(child);
684 if (itemGroup) // addMapItemView calls addMapItemGroup
685 return addMapItemGroup_real(itemGroup);
686
687 QDeclarativeGeoMapItemBase *mapItem = qobject_cast<QDeclarativeGeoMapItemBase *>(child);
688 if (mapItem)
689 return addMapItem_real(mapItem);
690
691 return false;
692}
693
694bool QDeclarativeGeoMap::removeMapChild(QObject *child)
695{
696 // dispatch items appropriately
697 QDeclarativeGeoMapItemView *mapView = qobject_cast<QDeclarativeGeoMapItemView *>(child);
698 if (mapView)
699 return removeMapItemView_real(mapView);
700
701 QDeclarativeGeoMapItemGroup *itemGroup = qobject_cast<QDeclarativeGeoMapItemGroup *>(child);
702 if (itemGroup) // removeMapItemView calls removeMapItemGroup for itself.
703 return removeMapItemGroup_real(itemGroup);
704
705 QDeclarativeGeoMapItemBase *mapItem = qobject_cast<QDeclarativeGeoMapItemBase *>(child);
706 if (mapItem)
707 return removeMapItem_real(mapItem);
708
709 return false;
710}
711
712bool QDeclarativeGeoMap::isGroupNested(QDeclarativeGeoMapItemGroup *group) const
713{
714 QObject *parent = group->parent();
715 // Nested groups have parent set in parent's componentComplete()
716 // Those instantiated by MapItemView's delegateModel, however, do not,
717 // but have setParentItem set.
718 return qobject_cast<QDeclarativeGeoMapItemGroup *>(parent)
719 || qobject_cast<QDeclarativeGeoMapItemGroup *>(group->parentItem());
720}
721
722qreal QDeclarativeGeoMap::zoomLevel() const
723{
724 if (m_initialized)
725 return m_map->cameraData().zoomLevel();
726 return m_cameraData.zoomLevel();
727}
728
729/*!
730 \qmlproperty real QtLocation::Map::bearing
731
732 This property holds the bearing for the map.
733 The default value is 0.
734 If the Plugin used for the Map supports bearing, the valid range for this value is between 0 and 360.
735 If the Plugin used for the Map does not support bearing, changing this property will have no effect.
736
737 \since QtLocation 5.9
738*/
739void QDeclarativeGeoMap::setBearing(qreal bearing)
740{
741 bearing = sanitizeBearing(bearing);
742 if (m_initialized) {
743 QGeoCameraData cameraData = m_map->cameraData();
744 cameraData.setBearing(bearing);
745 m_map->setCameraData(cameraData);
746 } else {
747 const bool bearingHasChanged = bearing != m_cameraData.bearing();
748 m_cameraData.setBearing(bearing);
749 if (bearingHasChanged) {
750 emit bearingChanged(bearing);
751 // do not emit visibleRegionChanged() here, because, if the map isn't initialized,
752 // the getter won't return anything updated
753 }
754 }
755}
756
757/*!
758 \qmlmethod void QtLocation::Map::setBearing(real bearing, coordinate coordinate)
759
760 Sets the bearing for the map to \a bearing, rotating it around \a coordinate.
761 If the Plugin used for the Map supports bearing, the valid range for \a bearing is between 0 and 360.
762 If the Plugin used for the Map does not support bearing, or if the map is tilted and \a coordinate happens
763 to be behind the camera, or if the map is not ready (see \l mapReady), calling this method will have no effect.
764
765 The release of this API with Qt 5.10 is a Technology Preview.
766
767 \since 5.10
768*/
769void QDeclarativeGeoMap::setBearing(qreal bearing, const QGeoCoordinate &coordinate)
770{
771 if (!m_initialized)
772 return;
773
774 const QGeoCoordinate currentCenter = center();
775 const qreal currentBearing = QDeclarativeGeoMap::bearing();
776 bearing = sanitizeBearing(bearing);
777
778 if (!coordinate.isValid()
779 || !qIsFinite(bearing)
780 || (coordinate == currentCenter && bearing == currentBearing))
781 return;
782
783 if (m_map->capabilities() & QGeoMap::SupportsSetBearing)
784 m_map->setBearing(bearing, coordinate);
785}
786
787qreal QDeclarativeGeoMap::bearing() const
788{
789 if (m_initialized)
790 return m_map->cameraData().bearing();
791 return m_cameraData.bearing();
792}
793
794/*!
795 \qmlproperty real QtLocation::Map::tilt
796
797 This property holds the tilt for the map, in degrees.
798 The default value is 0.
799 The valid range for this value is [ minimumTilt, maximumTilt ].
800 If the Plugin used for the Map does not support tilting, changing this property will have no effect.
801
802 \sa minimumTilt, maximumTilt
803
804 \since QtLocation 5.9
805*/
806void QDeclarativeGeoMap::setTilt(qreal tilt)
807{
808 tilt = qBound(minimumTilt(), tilt, maximumTilt());
809
810 if (m_initialized) {
811 QGeoCameraData cameraData = m_map->cameraData();
812 cameraData.setTilt(tilt);
813 m_map->setCameraData(cameraData);
814 } else {
815 const bool tiltHasChanged = tilt != m_cameraData.tilt();
816 m_cameraData.setTilt(tilt);
817 if (tiltHasChanged) {
818 emit tiltChanged(tilt);
819 // do not emit visibleRegionChanged() here, because, if the map isn't initialized,
820 // the getter won't return anything updated
821 }
822 }
823}
824
825qreal QDeclarativeGeoMap::tilt() const
826{
827 if (m_initialized)
828 return m_map->cameraData().tilt();
829 return m_cameraData.tilt();
830}
831
832void QDeclarativeGeoMap::setMinimumTilt(qreal minimumTilt, bool userSet)
833{
834 if (minimumTilt >= 0) {
835 qreal oldMinimumTilt = this->minimumTilt();
836
837 if (userSet)
838 m_userMinimumTilt = minimumTilt;
839 else
840 m_minimumTilt = minimumTilt;
841
842 if (tilt() < minimumTilt)
843 setTilt(minimumTilt);
844
845 if (oldMinimumTilt != this->minimumTilt())
846 emit minimumTiltChanged(this->minimumTilt());
847 }
848}
849
850/*!
851 \qmlproperty real QtLocation::Map::fieldOfView
852
853 This property holds the field of view of the camera used to look at the map, in degrees.
854 If the plugin property of the map is not set, or the plugin does not support mapping, the value is 45 degrees.
855
856 Note that changing this value implicitly changes also the distance between the camera and the map,
857 so that, at a tilting angle of 0 degrees, the resulting image is identical for any value used for this property.
858
859 For more information about this parameter, consult the Wikipedia articles about \l {https://en.wikipedia.org/wiki/Field_of_view} {Field of view} and
860 \l {https://en.wikipedia.org/wiki/Angle_of_view} {Angle of view}.
861
862 \sa minimumFieldOfView, maximumFieldOfView
863
864 \since QtLocation 5.9
865*/
866void QDeclarativeGeoMap::setFieldOfView(qreal fieldOfView)
867{
868 fieldOfView = qBound(minimumFieldOfView(), fieldOfView, maximumFieldOfView());
869
870 if (m_initialized) {
871 QGeoCameraData cameraData = m_map->cameraData();
872 cameraData.setFieldOfView(fieldOfView);
873 m_map->setCameraData(cameraData);
874 } else {
875 const bool fovChanged = fieldOfView != m_cameraData.fieldOfView();
876 m_cameraData.setFieldOfView(fieldOfView);
877 if (fovChanged) {
878 emit fieldOfViewChanged(fieldOfView);
879 // do not emit visibleRegionChanged() here, because, if the map isn't initialized,
880 // the getter won't return anything updated
881 }
882 }
883}
884
885qreal QDeclarativeGeoMap::fieldOfView() const
886{
887 if (m_initialized)
888 return m_map->cameraData().fieldOfView();
889 return m_cameraData.fieldOfView();
890}
891
892void QDeclarativeGeoMap::setMinimumFieldOfView(qreal minimumFieldOfView, bool userSet)
893{
894 if (minimumFieldOfView > 0 && minimumFieldOfView < 180.0) {
895 qreal oldMinimumFoV = this->minimumFieldOfView();
896
897 if (userSet)
898 m_userMinimumFieldOfView = minimumFieldOfView;
899 else
900 m_minimumFieldOfView = minimumFieldOfView;
901
902 if (fieldOfView() < minimumFieldOfView)
903 setFieldOfView(minimumFieldOfView);
904
905 if (oldMinimumFoV != this->minimumFieldOfView())
906 emit minimumFieldOfViewChanged(this->minimumFieldOfView());
907 }
908}
909
910/*!
911 \qmlproperty real QtLocation::Map::minimumFieldOfView
912
913 This property holds the minimum valid field of view for the map, in degrees.
914
915 The minimum tilt field of view by the \l plugin used is a lower bound for
916 this property.
917 If the \l plugin property is not set or the plugin does not support mapping, this property is \c 1.
918
919 \sa fieldOfView, maximumFieldOfView
920
921 \since QtLocation 5.9
922*/
923qreal QDeclarativeGeoMap::minimumFieldOfView() const
924{
925 return qMax(qMin(m_maximumFieldOfView, m_userMinimumFieldOfView), m_minimumFieldOfView);
926}
927
928void QDeclarativeGeoMap::setMaximumFieldOfView(qreal maximumFieldOfView, bool userSet)
929{
930 if (maximumFieldOfView > 0 && maximumFieldOfView < 180.0) {
931 qreal oldMaximumFoV = this->maximumFieldOfView();
932 if (userSet)
933 m_userMaximumFieldOfView = maximumFieldOfView;
934 else
935 m_maximumFieldOfView = maximumFieldOfView;
936
937 if (fieldOfView() > maximumFieldOfView)
938 setFieldOfView(maximumFieldOfView);
939
940 if (oldMaximumFoV != this->maximumFieldOfView())
941 emit maximumFieldOfViewChanged(this->maximumFieldOfView());
942 }
943}
944
945/*!
946 \qmlproperty real QtLocation::Map::maximumFieldOfView
947
948 This property holds the maximum valid field of view for the map, in degrees.
949
950 The minimum tilt field of view by the \l plugin used is an upper bound for
951 this property.
952 If the \l plugin property is not set or the plugin does not support mapping, this property is \c 179.
953
954 \sa fieldOfView, minimumFieldOfView
955
956 \since QtLocation 5.9
957*/
958qreal QDeclarativeGeoMap::maximumFieldOfView() const
959{
960 return qMin(qMax(m_minimumFieldOfView, m_userMaximumFieldOfView), m_maximumFieldOfView);
961}
962
963/*!
964 \qmlproperty real QtLocation::Map::minimumTilt
965
966 This property holds the minimum valid tilt for the map, in degrees.
967
968 The minimum tilt defined by the \l plugin used is a lower bound for
969 this property.
970 If the \l plugin property is not set or the plugin does not support mapping, this property is \c 0.
971
972 Since QtLocation 5.12, plugins can additionally restrict this value depending on the current zoom level.
973
974 \sa tilt, maximumTilt
975
976 \since QtLocation 5.9
977*/
978qreal QDeclarativeGeoMap::minimumTilt() const
979{
980 return qMax(qMin(m_maximumTilt, m_userMinimumTilt), m_minimumTilt);
981}
982
983void QDeclarativeGeoMap::setMaximumTilt(qreal maximumTilt, bool userSet)
984{
985 if (maximumTilt >= 0) {
986 qreal oldMaximumTilt = this->maximumTilt();
987
988 if (userSet)
989 m_userMaximumTilt = maximumTilt;
990 else
991 m_maximumTilt = maximumTilt;
992
993 if (tilt() > maximumTilt)
994 setTilt(maximumTilt);
995
996 if (oldMaximumTilt != this->maximumTilt())
997 emit maximumTiltChanged(this->maximumTilt());
998 }
999}
1000
1001/*!
1002 \qmlproperty real QtLocation::Map::maximumTilt
1003
1004 This property holds the maximum valid tilt for the map, in degrees.
1005
1006 The maximum tilt defined by the \l plugin used is an upper bound for
1007 this property.
1008 If the \l plugin property is not set or the plugin does not support mapping, this property is \c 89.5.
1009
1010 Since QtLocation 5.12, plugins can additionally restrict this value depending on the current zoom level.
1011
1012 \sa tilt, minimumTilt
1013
1014 \since QtLocation 5.9
1015*/
1016qreal QDeclarativeGeoMap::maximumTilt() const
1017{
1018 return qMin(qMax(m_minimumTilt, m_userMaximumTilt), m_maximumTilt);
1019}
1020
1021/*!
1022 \qmlproperty coordinate QtLocation::Map::center
1023
1024 This property holds the coordinate which occupies the center of the
1025 mapping viewport. Invalid center coordinates are ignored.
1026
1027 The default value is an arbitrary valid coordinate.
1028*/
1029void QDeclarativeGeoMap::setCenter(const QGeoCoordinate &center)
1030{
1031 if (!center.isValid())
1032 return;
1033
1034 if (m_initialized) {
1035 QGeoCoordinate coord(center);
1036 coord.setLatitude(qBound(m_minimumViewportLatitude, center.latitude(), m_maximumViewportLatitude));
1037 QGeoCameraData cameraData = m_map->cameraData();
1038 cameraData.setCenter(coord);
1039 m_map->setCameraData(cameraData);
1040 } else {
1041 const bool centerHasChanged = center != m_cameraData.center();
1042 m_cameraData.setCenter(center);
1043 if (centerHasChanged) {
1044 emit centerChanged(center);
1045 // do not emit visibleRegionChanged() here, because, if the map isn't initialized,
1046 // the getter won't return anything updated
1047 }
1048 }
1049}
1050
1051QGeoCoordinate QDeclarativeGeoMap::center() const
1052{
1053 if (m_initialized)
1054 return m_map->cameraData().center();
1055 return m_cameraData.center();
1056}
1057
1058
1059/*!
1060 \qmlproperty geoShape QtLocation::Map::visibleRegion
1061
1062 This property holds the region which occupies the viewport of
1063 the map. The camera is positioned in the center of the shape, and
1064 at the largest integral zoom level possible which allows the
1065 whole shape to be visible on the screen. This implies that
1066 reading this property back shortly after having been set the
1067 returned area is equal or larger than the set area.
1068
1069 Setting this property implicitly changes the \l center and
1070 \l zoomLevel of the map. Any previously set value to those
1071 properties will be overridden.
1072
1073 \note Since Qt 5.14 This property provides change notifications.
1074
1075 \since 5.6
1076*/
1077void QDeclarativeGeoMap::setVisibleRegion(const QGeoShape &shape)
1078{
1079 if (shape.boundingGeoRectangle() == visibleRegion())
1080 return;
1081
1082 m_visibleRegion = shape.boundingGeoRectangle();
1083 if (!m_visibleRegion.isValid()
1084 || (m_visibleRegion.bottomRight().latitude() >= 85.0) // rect entirely outside web mercator
1085 || (m_visibleRegion.topLeft().latitude() <= -85.0)) {
1086 // shape invalidated -> nothing to fit anymore
1087 m_visibleRegion = QGeoRectangle();
1088 m_pendingFitViewport = false;
1089 emit visibleRegionChanged();
1090 return;
1091 }
1092
1093 if (!m_map || !width() || !height()) {
1094 m_pendingFitViewport = true;
1095 emit visibleRegionChanged();
1096 return;
1097 }
1098
1099 fitViewportToGeoShape(m_visibleRegion);
1100 emit visibleRegionChanged();
1101}
1102
1103QGeoShape QDeclarativeGeoMap::visibleRegion() const
1104{
1105 if (!m_map || !width() || !height())
1106 return m_visibleRegion;
1107
1108 if (m_map->capabilities() & QGeoMap::SupportsVisibleRegion) {
1109 return m_map->visibleRegion();
1110 } else {
1111 // ToDo: handle projections not supporting visible region in a better way.
1112 // This approach will fail when horizon is in the view or the map is greatly zoomed out.
1113 QList<QGeoCoordinate> visiblePoly;
1114 visiblePoly << m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(0,0), false);
1115 visiblePoly << m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(m_map->viewportWidth() - 1,
1116 0), false);
1117 visiblePoly << m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(m_map->viewportWidth() - 1,
1118 m_map->viewportHeight() - 1), false);
1119 visiblePoly << m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(0,
1120 m_map->viewportHeight() - 1), false);
1121 QGeoPath path;
1122 path.setPath(visiblePoly);
1123 return path.boundingGeoRectangle();
1124 }
1125}
1126
1127/*!
1128 \qmlproperty bool QtLocation::Map::copyrightsVisible
1129
1130 This property holds the visibility of the copyrights notice. The notice is usually
1131 displayed in the bottom left corner. By default, this property is set to \c true.
1132
1133 \note Many map providers require the notice to be visible as part of the terms and conditions.
1134 Please consult the relevant provider documentation before turning this notice off.
1135
1136 \since 5.7
1137*/
1138void QDeclarativeGeoMap::setCopyrightsVisible(bool visible)
1139{
1140 if (m_copyrightsVisible == visible)
1141 return;
1142
1143 if (!m_copyrights.isNull())
1144 m_copyrights->setCopyrightsVisible(visible);
1145
1146 m_copyrightsVisible = visible;
1147 emit copyrightsVisibleChanged(visible);
1148}
1149
1150bool QDeclarativeGeoMap::copyrightsVisible() const
1151{
1152 return m_copyrightsVisible;
1153}
1154
1155
1156
1157/*!
1158 \qmlproperty color QtLocation::Map::color
1159
1160 This property holds the background color of the map element.
1161
1162 \since 5.6
1163*/
1164void QDeclarativeGeoMap::setColor(const QColor &color)
1165{
1166 if (color != m_color) {
1167 m_color = color;
1168 update();
1169 emit colorChanged(m_color);
1170 }
1171}
1172
1173QColor QDeclarativeGeoMap::color() const
1174{
1175 return m_color;
1176}
1177
1178/*!
1179 \qmlproperty rect QtLocation::Map::visibleArea
1180
1181 This property holds the visible area inside the Map QML element.
1182 It is a rect whose coordinates are relative to the Map element.
1183 Its size will be clamped to the size of the Map element.
1184 A null visibleArea means that the whole Map is visible.
1185
1186 \since 5.12
1187*/
1188QRectF QDeclarativeGeoMap::visibleArea() const
1189{
1190 if (m_initialized)
1191 return m_map->visibleArea();
1192 return m_visibleArea;
1193}
1194
1195void QDeclarativeGeoMap::setVisibleArea(const QRectF &visibleArea)
1196{
1197 const QRectF oldVisibleArea = QDeclarativeGeoMap::visibleArea();
1198 if (visibleArea == oldVisibleArea)
1199 return;
1200
1201 if (!visibleArea.isValid() && !visibleArea.isEmpty()) // values < 0
1202 return;
1203
1204 if (m_initialized) {
1205 m_map->setVisibleArea(visibleArea);
1206 const QRectF newVisibleArea = QDeclarativeGeoMap::visibleArea();
1207 if (newVisibleArea != oldVisibleArea) {
1208 // polish map items
1209 for (const QPointer<QDeclarativeGeoMapItemBase> &i: std::as_const(m_mapItems)) {
1210 if (i)
1211 i->visibleAreaChanged();
1212 }
1213 }
1214 } else {
1215 m_visibleArea = visibleArea;
1216 const QRectF newVisibleArea = QDeclarativeGeoMap::visibleArea();
1217 if (newVisibleArea != oldVisibleArea)
1218 emit visibleAreaChanged();
1219 }
1220}
1221
1222/*!
1223 \qmlproperty bool QtLocation::Map::mapReady
1224
1225 This property holds whether the map has been successfully initialized and is ready to be used.
1226 Some methods, such as \l fromCoordinate and \l toCoordinate, will not work before the map is ready.
1227 Due to the architecture of the \l Map, it's advised to use the signal emitted for this property
1228 in place of \l {QtQml::Component::completed()}{Component.onCompleted}, to make sure that everything behaves as expected.
1229
1230 \since 5.9
1231*/
1232bool QDeclarativeGeoMap::mapReady() const
1233{
1234 return m_initialized;
1235}
1236
1237QMargins QDeclarativeGeoMap::mapMargins() const
1238{
1239 const QRectF va = m_map->visibleArea();
1240 if (va.isEmpty())
1241 return QMargins();
1242 return QMargins( va.x()
1243 , va.y()
1244 , width() - va.width() - va.x()
1245 , height() - va.height() - va.y());
1246}
1247
1248/*!
1249 \qmlproperty list<mapType> QtLocation::Map::supportedMapTypes
1250
1251 This read-only property holds the set of \l{mapType}{map types} supported by this map.
1252
1253 \sa activeMapType
1254*/
1255QList<QGeoMapType> QDeclarativeGeoMap::supportedMapTypes()
1256{
1257 return m_supportedMapTypes;
1258}
1259
1260/*!
1261 \qmlmethod void QtLocation::Map::alignCoordinateToPoint(coordinate coordinate, QPointF point)
1262
1263 Aligns \a coordinate to \a point.
1264 This method effectively extends the functionality offered by the \l center qml property, allowing
1265 to align a coordinate to point of the Map element other than its center.
1266 This is useful in those applications where the center of the scene (e.g., a cursor) is not to be
1267 placed exactly in the center of the map.
1268
1269 If the map is tilted, and \a coordinate happens to be behind the camera, or if the map is not ready
1270 (see \l mapReady), calling this method will have no effect.
1271
1272 The release of this API with Qt 5.10 is a Technology Preview.
1273
1274 \sa center
1275
1276 \since 5.10
1277*/
1278void QDeclarativeGeoMap::alignCoordinateToPoint(const QGeoCoordinate &coordinate, const QPointF &point)
1279{
1280 if (!m_map || !(m_map->capabilities() & QGeoMap::SupportsAnchoringCoordinate))
1281 return;
1282
1283 if (!coordinate.isValid()
1284 || !qIsFinite(point.x())
1285 || !qIsFinite(point.y()))
1286 return;
1287
1288 m_map->anchorCoordinateToPoint(coordinate, point);
1289}
1290
1291/*!
1292 \qmlmethod coordinate QtLocation::Map::toCoordinate(QPointF position, bool clipToViewPort)
1293
1294 Returns the coordinate which corresponds to the \a position relative to the map item.
1295
1296 If \a clipToViewPort is \c true, or not supplied then returns an invalid coordinate if
1297 \a position is not within the current viewport.
1298*/
1299QGeoCoordinate QDeclarativeGeoMap::toCoordinate(const QPointF &position, bool clipToViewPort) const
1300{
1301 if (m_map)
1302 return m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(position), clipToViewPort);
1303 else
1304 return QGeoCoordinate();
1305}
1306
1307/*!
1308 \qmlmethod point QtLocation::Map::fromCoordinate(coordinate coordinate, bool clipToViewPort)
1309
1310 Returns the position relative to the map item which corresponds to the \a coordinate.
1311
1312 If \a clipToViewPort is \c true, or not supplied then returns an invalid QPointF if
1313 \a coordinate is not within the current viewport.
1314*/
1315QPointF QDeclarativeGeoMap::fromCoordinate(const QGeoCoordinate &coordinate, bool clipToViewPort) const
1316{
1317 if (m_map)
1318 return m_map->geoProjection().coordinateToItemPosition(coordinate, clipToViewPort).toPointF();
1319 else
1320 return QPointF(qQNaN(), qQNaN());
1321}
1322
1323/*!
1324 \qmlmethod void QtLocation::Map::pan(int dx, int dy)
1325
1326 Starts panning the map by \a dx pixels along the x-axis and
1327 by \a dy pixels along the y-axis.
1328
1329 Positive values for \a dx move the map right, negative values left.
1330 Positive values for \a dy move the map down, negative values up.
1331
1332 During panning the \l center, and \l zoomLevel may change.
1333*/
1334void QDeclarativeGeoMap::pan(int dx, int dy)
1335{
1336 if (!m_map)
1337 return;
1338 if (dx == 0 && dy == 0)
1339 return;
1340
1341 QGeoCoordinate coord = m_map->geoProjection().itemPositionToCoordinate(
1342 QDoubleVector2D(m_map->viewportWidth() / 2 + dx,
1343 m_map->viewportHeight() / 2 + dy));
1344 setCenter(coord);
1345}
1346
1347
1348/*!
1349 \qmlmethod void QtLocation::Map::prefetchData()
1350
1351 Optional hint that allows the map to prefetch during this idle period
1352*/
1353void QDeclarativeGeoMap::prefetchData()
1354{
1355 if (!m_map)
1356 return;
1357 m_map->prefetchData();
1358}
1359
1360/*!
1361 \qmlmethod void QtLocation::Map::clearData()
1362
1363 Clears map data collected by the currently selected plugin.
1364 \note This method will delete cached files.
1365 \sa plugin
1366*/
1367void QDeclarativeGeoMap::clearData()
1368{
1369 if (m_map)
1370 m_map->clearData();
1371}
1372
1373/*!
1374 \qmlmethod void QtLocation::Map::fitViewportToGeoShape(geoShape, margins)
1375
1376 Fits the viewport to a specific geo shape \a geoShape.
1377 The \a margins are in screen pixels.
1378
1379 \note If the projection used by the plugin is not WebMercator, and the plugin does not have fitting to
1380 shape capability, this method will do nothing.
1381
1382 \sa visibleRegion
1383 \since 5.13
1384*/
1385void QDeclarativeGeoMap::fitViewportToGeoShape(const QGeoShape &shape, QVariant margins)
1386{
1387 QMargins m(10, 10, 10, 10); // lets defaults to 10 if margins is invalid
1388 switch (margins.typeId()) {
1389 case QMetaType::Int:
1390 case QMetaType::Double: {
1391 const int value = int(margins.toDouble());
1392 m = QMargins(value, value, value, value);
1393 }
1394 break;
1395 // ToDo: Support distinct margins in some QML form. Perhaps QRect?
1396 default:
1397 break;
1398 }
1399 fitViewportToGeoShape(shape, m);
1400}
1401
1402void QDeclarativeGeoMap::fitViewportToGeoShape(const QGeoShape &shape, const QMargins &borders)
1403{
1404 if (!m_map || !shape.isValid())
1405 return;
1406
1407 if (m_map->geoProjection().projectionType() == QGeoProjection::ProjectionWebMercator) {
1408 // This case remains handled here, and not inside QGeoMap*::fitViewportToGeoRectangle,
1409 // in order to honor animations on center and zoomLevel
1410 const QMargins margins = borders + mapMargins();
1411 const QGeoProjectionWebMercator &p = static_cast<const QGeoProjectionWebMercator&>(m_map->geoProjection());
1412 const QPair<QGeoCoordinate, qreal> fitData = p.fitViewportToGeoRectangle(shape.boundingGeoRectangle(),
1413 margins);
1414 if (!fitData.first.isValid())
1415 return;
1416
1417 // position camera to the center of bounding box
1418 setProperty("center", QVariant::fromValue(fitData.first)); // not using setCenter(centerCoordinate) to honor a possible animation set on the center property
1419
1420 if (!qIsFinite(fitData.second))
1421 return;
1422 double newZoom = qMax<double>(minimumZoomLevel(), fitData.second);
1423 setProperty("zoomLevel", QVariant::fromValue(newZoom)); // not using setZoomLevel(newZoom) to honor a possible animation set on the zoomLevel property
1424 } else if (m_map->capabilities() & QGeoMap::SupportsFittingViewportToGeoRectangle) {
1425 // Animations cannot be honored in this case, as m_map acts as a black box
1426 m_map->fitViewportToGeoRectangle(m_visibleRegion, borders);
1427 }
1428 // else out of luck
1429}
1430
1431/*!
1432 \qmlproperty string QtLocation::Map::errorString
1433
1434 This read-only property holds the textual presentation of the latest mapping provider error.
1435 If no error has occurred, an empty string is returned.
1436
1437 An empty string may also be returned if an error occurred which has no associated
1438 textual representation.
1439
1440 \sa QGeoServiceProvider::errorString()
1441*/
1442
1443QString QDeclarativeGeoMap::errorString() const
1444{
1445 return m_errorString;
1446}
1447
1448/*!
1449 \qmlproperty enumeration QtLocation::Map::error
1450
1451 This read-only property holds the last occurred mapping service provider error.
1452
1453 \list
1454 \li Map.NoError - No error has occurred.
1455 \li Map.NotSupportedError -The maps plugin property was not set or there is no mapping manager associated with the plugin.
1456 \li Map.UnknownParameterError -The plugin did not recognize one of the parameters it was given.
1457 \li Map.MissingRequiredParameterError - The plugin did not find one of the parameters it was expecting.
1458 \li Map.ConnectionError - The plugin could not connect to its backend service or database.
1459 \endlist
1460
1461 \sa QGeoServiceProvider::Error
1462*/
1463
1464QGeoServiceProvider::Error QDeclarativeGeoMap::error() const
1465{
1466 return m_error;
1467}
1468
1469QGeoMap *QDeclarativeGeoMap::map() const
1470{
1471 return m_map;
1472}
1473
1474void QDeclarativeGeoMap::itemChange(ItemChange change, const ItemChangeData &value)
1475{
1476 if (change == ItemChildAddedChange) {
1477 QQuickItem *child = value.item;
1478 QQuickItem *mapItem = qobject_cast<QDeclarativeGeoMapItemBase *>(child);
1479 if (!mapItem)
1480 mapItem = qobject_cast<QDeclarativeGeoMapItemGroup *>(child);
1481
1482 if (mapItem) {
1483 qreal z = mapItem->z();
1484 if (z > m_maxChildZ) { // Ignore children removal
1485 m_maxChildZ = z;
1486 // put the copyrights notice object at the highest z order
1487 if (m_copyrights)
1488 m_copyrights->setCopyrightsZ(m_maxChildZ + 1);
1489 }
1490 }
1491 } else if (change == ItemSceneChange) {
1492 if (m_window) {
1493 disconnect(m_window, &QQuickWindow::beforeSynchronizing,
1494 this, &QDeclarativeGeoMap::updateItemToWindowTransform);
1495 }
1496 m_window = value.window;
1497 if (m_window) {
1498 connect(m_window, &QQuickWindow::beforeSynchronizing,
1499 this, &QDeclarativeGeoMap::updateItemToWindowTransform, Qt::DirectConnection);
1500 }
1501 }
1502 QQuickItem::itemChange(change, value);
1503}
1504
1505void QDeclarativeGeoMap::attachCopyrightNotice(bool initialVisibility)
1506{
1507 if (initialVisibility) {
1508 ++m_copyNoticesVisible;
1509 if (m_map)
1510 m_map->setCopyrightVisible(m_copyNoticesVisible > 0);
1511 }
1512}
1513
1514void QDeclarativeGeoMap::detachCopyrightNotice(bool currentVisibility)
1515{
1516 if (currentVisibility) {
1517 --m_copyNoticesVisible;
1518 if (m_map)
1519 m_map->setCopyrightVisible(m_copyNoticesVisible > 0);
1520 }
1521}
1522
1523void QDeclarativeGeoMap::onAttachedCopyrightNoticeVisibilityChanged()
1524{
1525 QDeclarativeGeoMapCopyrightNotice *copy = static_cast<QDeclarativeGeoMapCopyrightNotice *>(sender());
1526 m_copyNoticesVisible += ( int(copy->copyrightsVisible()) * 2 - 1);
1527 if (m_map)
1528 m_map->setCopyrightVisible(m_copyNoticesVisible > 0);
1529}
1530
1531void QDeclarativeGeoMap::onCameraDataChanged(const QGeoCameraData &cameraData)
1532{
1533 bool centerHasChanged = cameraData.center() != m_cameraData.center();
1534 bool bearingHasChanged = cameraData.bearing() != m_cameraData.bearing();
1535 bool tiltHasChanged = cameraData.tilt() != m_cameraData.tilt();
1536 bool fovHasChanged = cameraData.fieldOfView() != m_cameraData.fieldOfView();
1537 bool zoomHasChanged = cameraData.zoomLevel() != m_cameraData.zoomLevel();
1538
1539 m_cameraData = cameraData;
1540 // polish map items
1541 for (const QPointer<QDeclarativeGeoMapItemBase> &i: std::as_const(m_mapItems)) {
1542 if (i)
1543 i->baseCameraDataChanged(m_cameraData); // Consider optimizing this further, removing the contained duplicate if conditions.
1544 }
1545
1546 if (centerHasChanged)
1547 emit centerChanged(m_cameraData.center());
1548 if (zoomHasChanged)
1549 emit zoomLevelChanged(m_cameraData.zoomLevel());
1550 if (bearingHasChanged)
1551 emit bearingChanged(m_cameraData.bearing());
1552 if (tiltHasChanged)
1553 emit tiltChanged(m_cameraData.tilt());
1554 if (fovHasChanged)
1555 emit fieldOfViewChanged(m_cameraData.fieldOfView());
1556 if (centerHasChanged || zoomHasChanged || bearingHasChanged
1557 || tiltHasChanged || fovHasChanged)
1558 emit visibleRegionChanged();
1559}
1560
1561/*!
1562 \qmlproperty list<MapItem> QtLocation::Map::mapItems
1563
1564 Returns the list of all map items in no particular order.
1565 These items include items that were declared statically as part of
1566 the type declaration, as well as dynamical items (\l addMapItem,
1567 \l MapItemView).
1568
1569 \sa addMapItem, removeMapItem, clearMapItems
1570*/
1571
1572QList<QObject *> QDeclarativeGeoMap::mapItems()
1573{
1574 QList<QObject *> ret;
1575 for (const auto &ptr : m_mapItems) {
1576 if (ptr)
1577 ret << ptr.data();
1578 }
1579 return ret;
1580}
1581
1582/*!
1583 \qmlmethod void QtLocation::Map::addMapItem(MapItem item)
1584
1585 Adds the given \a item to the Map (for example MapQuickItem, MapCircle). If the object
1586 already is on the Map, it will not be added again.
1587
1588 As an example, consider the case where you have a MapCircle representing your current position:
1589
1590 \snippet declarative/maps.qml QtQuick import
1591 \snippet declarative/maps.qml QtLocation import
1592 \codeline
1593 \snippet declarative/maps.qml Map addMapItem MapCircle at current position
1594
1595 \note MapItemViews cannot be added with this method.
1596
1597 \sa mapItems, removeMapItem, clearMapItems
1598*/
1599
1600void QDeclarativeGeoMap::addMapItem(QDeclarativeGeoMapItemBase *item)
1601{
1602 if (addMapItem_real(item))
1603 emit mapItemsChanged();
1604}
1605
1606bool QDeclarativeGeoMap::addMapItem_real(QDeclarativeGeoMapItemBase *item)
1607{
1608 if (!item || item->quickMap())
1609 return false;
1610 // If the item comes from a MapItemGroup, do not reparent it.
1611 if (!qobject_cast<QDeclarativeGeoMapItemGroup *>(item->parentItem()))
1612 item->setParentItem(this);
1613 m_mapItems.append(item);
1614 if (m_map) {
1615 item->setMap(this, m_map);
1616 m_map->addMapItem(item);
1617 }
1618 return true;
1619}
1620
1621/*!
1622 \qmlmethod void QtLocation::Map::removeMapItem(MapItem item)
1623
1624 Removes the given \a item from the Map (for example MapQuickItem, MapCircle). If
1625 the MapItem does not exist or was not previously added to the map, the
1626 method does nothing.
1627
1628 \sa mapItems, addMapItem, clearMapItems
1629*/
1630void QDeclarativeGeoMap::removeMapItem(QDeclarativeGeoMapItemBase *ptr)
1631{
1632 if (removeMapItem_real(ptr))
1633 emit mapItemsChanged();
1634}
1635
1636bool QDeclarativeGeoMap::removeMapItem_real(QDeclarativeGeoMapItemBase *ptr)
1637{
1638 if (!ptr)
1639 return false;
1640 QPointer<QDeclarativeGeoMapItemBase> item(ptr);
1641 if (!m_mapItems.contains(item))
1642 return false;
1643 if (m_map)
1644 m_map->removeMapItem(ptr);
1645 if (item->parentItem() == this)
1646 item->setParentItem(0);
1647 item->setMap(0, 0);
1648 // these can be optimized for perf, as we already check the 'contains' above
1649 m_mapItems.removeOne(item);
1650 return true;
1651}
1652
1653/*!
1654 \qmlmethod void QtLocation::Map::clearMapItems()
1655
1656 Removes all items and item groups from the map.
1657
1658 \sa mapItems, addMapItem, removeMapItem, addMapItemGroup, removeMapItemGroup
1659*/
1660void QDeclarativeGeoMap::clearMapItems()
1661{
1662 if (m_mapItems.isEmpty())
1663 return;
1664
1665 qsizetype removed = 0;
1666 for (qsizetype i = 0; i < m_mapItemGroups.count(); ++i) {
1667 auto item = m_mapItemGroups.at(i);
1668 // Processing only top-level groups (!views)
1669 if (qobject_cast<QDeclarativeGeoMapItemView *>(item))
1670 continue;
1671
1672
1673 if (item->parentItem() != this)
1674 continue;
1675
1676 if (removeMapItemGroup_real(item)) {
1677 removed++;
1678 --i;
1679 }
1680 }
1681
1682 while (!m_mapItems.isEmpty())
1683 removed += removeMapItem_real(m_mapItems.first());
1684
1685 if (removed)
1686 emit mapItemsChanged();
1687}
1688
1689/*!
1690 \qmlmethod void QtLocation::Map::addMapItemGroup(MapItemGroup itemGroup)
1691
1692 Adds the map items contained in the given \a itemGroup to the Map
1693 (for example MapQuickItem, MapCircle).
1694
1695 \sa MapItemGroup, removeMapItemGroup
1696
1697 \since 5.9
1698*/
1699void QDeclarativeGeoMap::addMapItemGroup(QDeclarativeGeoMapItemGroup *itemGroup)
1700{
1701 if (addMapItemGroup_real(itemGroup))
1702 emit mapItemsChanged();
1703}
1704
1705bool QDeclarativeGeoMap::addMapItemGroup_real(QDeclarativeGeoMapItemGroup *itemGroup)
1706{
1707 if (!itemGroup || itemGroup->quickMap()) // Already added to some map
1708 return false;
1709
1710 itemGroup->setQuickMap(this);
1711
1712 if (!isGroupNested(itemGroup))
1713 itemGroup->setParentItem(this);
1714
1715 QPointer<QDeclarativeGeoMapItemGroup> g(itemGroup);
1716 m_mapItemGroups.append(g);
1717
1718 const QList<QQuickItem *> quickKids = itemGroup->childItems();
1719 int count = 0;
1720 for (auto c: quickKids) {
1721 count += addMapChild(c); // this calls addMapItemGroup recursively, if needed
1722 }
1723 return count;
1724}
1725
1726/*!
1727 \qmlmethod void QtLocation::Map::removeMapItemGroup(MapItemGroup itemGroup)
1728
1729 Removes \a itemGroup and the items contained therein from the Map.
1730
1731 \sa MapItemGroup, addMapItemGroup
1732
1733 \since 5.9
1734*/
1735void QDeclarativeGeoMap::removeMapItemGroup(QDeclarativeGeoMapItemGroup *itemGroup)
1736{
1737 if (removeMapItemGroup_real(itemGroup))
1738 emit mapItemsChanged();
1739}
1740
1741bool QDeclarativeGeoMap::removeMapItemGroup_real(QDeclarativeGeoMapItemGroup *itemGroup)
1742{
1743 if (!itemGroup || itemGroup->quickMap() != this) // cant remove an itemGroup added to another map
1744 return false;
1745
1746 QPointer<QDeclarativeGeoMapItemGroup> g(itemGroup);
1747 if (!m_mapItemGroups.removeOne(g))
1748 return false;
1749
1750 const QList<QQuickItem *> quickKids = itemGroup->childItems();
1751 int count = 0;
1752 for (auto c: quickKids) {
1753 count += removeMapChild(c);
1754 }
1755 itemGroup->setQuickMap(nullptr);
1756 if (itemGroup->parentItem() == this)
1757 itemGroup->setParentItem(0);
1758 return count;
1759}
1760
1761/*!
1762 \qmlmethod void QtLocation::Map::removeMapItemView(MapItemView itemView)
1763
1764 Removes \a itemView and the items instantiated by it from the Map.
1765
1766 \sa MapItemView, addMapItemView
1767
1768 \since 5.10
1769*/
1770void QDeclarativeGeoMap::removeMapItemView(QDeclarativeGeoMapItemView *itemView)
1771{
1772 if (removeMapItemView_real(itemView))
1773 emit mapItemsChanged();
1774}
1775
1776bool QDeclarativeGeoMap::removeMapItemView_real(QDeclarativeGeoMapItemView *itemView)
1777{
1778 if (!itemView || itemView->m_map != this) // can't remove a view that is already added to another map
1779 return false;
1780
1781 itemView->removeInstantiatedItems(false); // remove the items without using transitions AND abort ongoing ones
1782 itemView->m_map = 0;
1783 m_mapViews.removeOne(itemView);
1784 return removeMapItemGroup_real(itemView); // at this point, all delegate instances have been removed.
1785}
1786
1787void QDeclarativeGeoMap::updateItemToWindowTransform()
1788{
1789 if (!m_initialized)
1790 return;
1791
1792 // Update itemToWindowTransform into QGeoProjection
1793 QTransform item2Window = QQuickItemPrivate::get(this)->itemToWindowTransform();
1794 if (!property("layer").isNull() && property("layer").value<QObject *>()->property("enabled").toBool())
1795 item2Window.reset(); // When layer is enabled, the item is rendered offscreen with no transformation, then the layer is applied
1796
1797 m_map->setItemToWindowTransform(item2Window);
1798
1799 m_sgNodeHasChanged = false;
1800}
1801
1802void QDeclarativeGeoMap::onSGNodeChanged()
1803{
1804 m_sgNodeHasChanged = true;
1805 update();
1806}
1807
1808/*!
1809 \qmlmethod void QtLocation::Map::addMapItemView(MapItemView itemView)
1810
1811 Adds \a itemView to the Map.
1812
1813 \sa MapItemView, removeMapItemView
1814
1815 \since 5.10
1816*/
1817void QDeclarativeGeoMap::addMapItemView(QDeclarativeGeoMapItemView *itemView)
1818{
1819 if (addMapItemView_real(itemView))
1820 emit mapItemsChanged();
1821}
1822
1823bool QDeclarativeGeoMap::addMapItemView_real(QDeclarativeGeoMapItemView *itemView)
1824{
1825 if (!itemView || itemView->m_map) // can't add a view twice
1826 return false;
1827
1828 int count = addMapItemGroup_real(itemView); // at this point, delegates aren't yet incubated.
1829 // Not appending it to m_mapViews because it seems unnecessary even if the
1830 // itemView is a child of this (in which case it would be destroyed
1831 m_mapViews.append(itemView);
1832 setupMapView(itemView);
1833 return count;
1834}
1835
1836/*!
1837 \qmlproperty mapType QtLocation::Map::activeMapType
1838
1839 \brief Access to the currently active \l{mapType}{map type}.
1840
1841 This property can be set to change the active \l{mapType}{map type}.
1842 See the \l{Map::supportedMapTypes}{supportedMapTypes} property for possible values.
1843
1844 \sa mapType
1845*/
1846void QDeclarativeGeoMap::setActiveMapType(const QGeoMapType &mapType)
1847{
1848 if (m_activeMapType != mapType) {
1849 if (m_map) {
1850 if (mapType.pluginName() == m_plugin->name().toLatin1()) {
1851 m_map->setActiveMapType(mapType);
1852 m_activeMapType = mapType;
1853 emit activeMapTypeChanged();
1854 }
1855 } else {
1856 m_activeMapType = mapType;
1857 emit activeMapTypeChanged();
1858 }
1859 }
1860}
1861
1862QGeoMapType QDeclarativeGeoMap::activeMapType() const
1863{
1864 return m_activeMapType;
1865}
1866
1867/*!
1868 \internal
1869*/
1870void QDeclarativeGeoMap::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
1871{
1872 QQuickItem::geometryChange(newGeometry, oldGeometry);
1873
1874 if (!m_map || newGeometry.size().isEmpty())
1875 return;
1876
1877 m_map->setViewportSize(newGeometry.size().toSize());
1878
1879 if (!m_initialized) {
1880 initialize();
1881 } else {
1882 setMinimumZoomLevel(m_map->minimumZoom(), false);
1883
1884 // Update the center latitudinal threshold
1885 QGeoCameraData cameraData = m_map->cameraData();
1886 const double maximumCenterLatitudeAtZoom = m_map->maximumCenterLatitudeAtZoom(cameraData);
1887 const double minimumCenterLatitudeAtZoom = m_map->minimumCenterLatitudeAtZoom(cameraData);
1888 if (maximumCenterLatitudeAtZoom != m_maximumViewportLatitude
1889 || minimumCenterLatitudeAtZoom != m_minimumViewportLatitude) {
1890 m_maximumViewportLatitude = maximumCenterLatitudeAtZoom;
1891 m_minimumViewportLatitude = minimumCenterLatitudeAtZoom;
1892 QGeoCoordinate coord = cameraData.center();
1893 coord.setLatitude(qBound(m_minimumViewportLatitude, coord.latitude(), m_maximumViewportLatitude));
1894 cameraData.setCenter(coord);
1895 m_map->setCameraData(cameraData);
1896 }
1897 if (oldGeometry.size() != newGeometry.size()) {
1898 // polish map items
1899 for (const QPointer<QDeclarativeGeoMapItemBase> &i: std::as_const(m_mapItems)) {
1900 if (i)
1901 i->polishAndUpdate();
1902 }
1903 }
1904 }
1905
1906 /*
1907 The fitViewportTo*() functions depend on a valid map geometry.
1908 If they were called prior to the first resize they cause
1909 the zoomlevel to jump to 0 (showing the world). Therefore the
1910 calls were queued up until now.
1911
1912 Multiple fitViewportTo*() calls replace each other.
1913 */
1914 if (m_pendingFitViewport && width() && height()) {
1915 fitViewportToGeoShape(m_visibleRegion);
1916 m_pendingFitViewport = false;
1917 }
1918
1919}
1920
1921/*!
1922 \qmlmethod void QtLocation::Map::fitViewportToMapItems(list<MapItems> items = {})
1923
1924 If no argument is provided, fits the current viewport to the boundary of all map items.
1925 The camera is positioned in the center of the map items, and at the largest integral zoom level
1926 possible which allows all map items to be visible on screen.
1927 If \a items is provided, fits the current viewport to the boundary of the specified map items only.
1928
1929 \note This method gained the optional \a items argument since Qt 5.15.
1930 In previous releases, this method fitted the map to all map items.
1931
1932 \sa fitViewportToVisibleMapItems
1933*/
1934void QDeclarativeGeoMap::fitViewportToMapItems(const QVariantList &items)
1935{
1936 if (items.size()) {
1937 QList<QPointer<QDeclarativeGeoMapItemBase> > itms;
1938 for (const QVariant &i: items) {
1939 QDeclarativeGeoMapItemBase *itm = qobject_cast<QDeclarativeGeoMapItemBase *>(i.value<QObject *>());
1940 if (itm)
1941 itms.append(itm);
1942 }
1943 fitViewportToMapItemsRefine(itms, true, false);
1944 } else {
1945 fitViewportToMapItemsRefine(m_mapItems, true, false);
1946 }
1947}
1948
1949/*!
1950 \qmlmethod void QtLocation::Map::fitViewportToVisibleMapItems()
1951
1952 Fits the current viewport to the boundary of all \b visible map items.
1953 The camera is positioned in the center of the map items, and at the largest integral
1954 zoom level possible which allows all map items to be visible on screen.
1955
1956 \sa fitViewportToMapItems
1957*/
1958void QDeclarativeGeoMap::fitViewportToVisibleMapItems()
1959{
1960 fitViewportToMapItemsRefine(m_mapItems, true, true);
1961}
1962
1963/*!
1964 \internal
1965*/
1966void QDeclarativeGeoMap::fitViewportToMapItemsRefine(const QList<QPointer<QDeclarativeGeoMapItemBase> > &mapItems,
1967 bool refine,
1968 bool onlyVisible)
1969{
1970 if (!m_map)
1971 return;
1972
1973 if (mapItems.size() == 0)
1974 return;
1975
1976 double minX = qInf();
1977 double maxX = -qInf();
1978 double minY = qInf();
1979 double maxY = -qInf();
1980 double topLeftX = 0;
1981 double topLeftY = 0;
1982 double bottomRightX = 0;
1983 double bottomRightY = 0;
1984 bool haveQuickItem = false;
1985
1986 // find bounds of all map items
1987 qsizetype itemCount = 0;
1988 for (qsizetype i = 0; i < mapItems.count(); ++i) {
1989 if (!mapItems.at(i))
1990 continue;
1991 QDeclarativeGeoMapItemBase *item = mapItems.at(i).data();
1992 if (!item || (onlyVisible && (!item->isVisible() || item->mapItemOpacity() <= 0.0)))
1993 continue;
1994
1995 // skip quick items in the first pass and refine the fit later
1996 QDeclarativeGeoMapQuickItem *quickItem =
1997 qobject_cast<QDeclarativeGeoMapQuickItem*>(item);
1998 if (refine && quickItem) {
1999 haveQuickItem = true;
2000 continue;
2001 }
2002 // Force map items to update immediately. Needed to ensure correct item size and positions
2003 // when recursively calling this function.
2004 // TODO: See if we really need updatePolish on delegated items, in particular
2005 // in relation to
2006 // a) fitViewportToMapItems
2007 // b) presence of MouseArea
2008 //
2009 // This is also legacy code. It must be updated to not operate on screen sizes.
2010 if (item->isPolishScheduled())
2011 item->updatePolish();
2012
2013 if (quickItem && quickItem->matrix_ && !quickItem->matrix_->m_matrix.isIdentity()) {
2014 // TODO: recalculate the center/zoom level so that the item becomes projectable again
2015 if (quickItem->zoomLevel() == 0.0) // the item is unprojectable, should be skipped.
2016 continue;
2017
2018 QRectF brect = item->boundingRect();
2019 brect = quickItem->matrix_->m_matrix.mapRect(brect);
2020 QPointF transformedPosition = quickItem->matrix_->m_matrix.map(item->position());
2021 topLeftX = transformedPosition.x();
2022 topLeftY = transformedPosition.y();
2023 bottomRightX = topLeftX + brect.width();
2024 bottomRightY = topLeftY + brect.height();
2025 } else {
2026 QGeoRectangle brect = item->geoShape().boundingGeoRectangle();
2027 topLeftX = fromCoordinate(brect.topLeft(), false).x();
2028 topLeftY = fromCoordinate(brect.topLeft(), false).y();
2029 bottomRightX = fromCoordinate(brect.bottomRight(), false).x();
2030 bottomRightY = fromCoordinate(brect.bottomRight(), false).y();
2031 }
2032
2033 minX = qMin(minX, topLeftX);
2034 maxX = qMax(maxX, bottomRightX);
2035 minY = qMin(minY, topLeftY);
2036 maxY = qMax(maxY, bottomRightY);
2037
2038 ++itemCount;
2039 }
2040
2041 if (itemCount == 0) {
2042 if (haveQuickItem)
2043 fitViewportToMapItemsRefine(mapItems, false, onlyVisible);
2044 return;
2045 }
2046 double bboxWidth = maxX - minX;
2047 double bboxHeight = maxY - minY;
2048 double bboxCenterX = minX + (bboxWidth / 2.0);
2049 double bboxCenterY = minY + (bboxHeight / 2.0);
2050
2051 // position camera to the center of bounding box
2052 QGeoCoordinate coordinate;
2053 coordinate = m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(bboxCenterX, bboxCenterY), false);
2054 setProperty("center", QVariant::fromValue(coordinate));
2055
2056 // adjust zoom
2057 double bboxWidthRatio = bboxWidth / (bboxWidth + bboxHeight);
2058 double mapWidthRatio = width() / (width() + height());
2059 double zoomRatio;
2060
2061 if (bboxWidthRatio > mapWidthRatio)
2062 zoomRatio = bboxWidth / width();
2063 else
2064 zoomRatio = bboxHeight / height();
2065
2066 qreal newZoom = std::log10(zoomRatio) / std::log10(0.5);
2067 newZoom = std::floor(qMax(minimumZoomLevel(), (zoomLevel() + newZoom)));
2068 setProperty("zoomLevel", QVariant::fromValue(newZoom));
2069
2070 // as map quick items retain the same screen size after the camera zooms in/out
2071 // we refine the viewport again to achieve better results
2072 if (refine)
2073 fitViewportToMapItemsRefine(mapItems, false, onlyVisible);
2074}
2075
2076QT_END_NAMESPACE