aboutsummaryrefslogtreecommitdiffstats
path: root/apps/com.pelagicore.qtlocation/Maps.qml
blob: 84cc3d8d966d5f0a724619135ff5fa4c6a28878d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/****************************************************************************
**
** Copyright (C) 2017-2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Neptune 3 IVI UI.
**
** $QT_BEGIN_LICENSE:GPL-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
** SPDX-License-Identifier: GPL-3.0
**
****************************************************************************/

import QtQuick 2.8
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import QtPositioning 5.9
import QtLocation 5.9
import QtGraphicalEffects 1.0

import Qt.labs.platform 1.0

import utils 1.0
import controls 1.0 as NeptuneControls
import animations 1.0

import com.pelagicore.styles.neptune 3.0

Item {
    id: root

    property bool offlineMapsEnabled
    onOfflineMapsEnabledChanged: getAvailableMapsAndLocation()

    // props for secondary window
    property alias mapInteractive: mainMap.mapInteractive
    property alias mapCenter: mainMap.center
    property alias mapZoomLevel: mainMap.zoomLevel
    property alias mapTilt: mainMap.tilt
    property alias mapBearing: mainMap.bearing
    readonly property alias mapReady: mainMap.mapReady

    property bool searchViewEnabled: false

    signal maximizeMap()

    function fetchCurrentLocation() { // PositionSource doesn't work on Linux
        var req = new XMLHttpRequest;
        req.onreadystatechange = function() {
            if (req.readyState === XMLHttpRequest.DONE) {
                var objectArray = JSON.parse(req.responseText);
                if (objectArray.errors !== undefined) {
                    console.warn("Error fetching location:", objectArray.errors[0].message);
                } else {
                    priv.positionCoordinate = QtPositioning.coordinate(objectArray.location.lat, objectArray.location.lng);
                    console.info("Current location:", priv.positionCoordinate);
                }
            }
        }
        req.open("GET", "https://location.services.mozilla.com/v1/geolocate?key=geoclue");
        req.send();
    }

    function getAvailableMapsAndLocation() {
        if (mainMap.mapReady) {
            mapTypeModel.clear();
            console.info("Supported map types:");
            for (var i = 0; i < mainMap.supportedMapTypes.length; i++) {
                var map = mainMap.supportedMapTypes[i];
                mapTypeModel.append({"name": map.name, "data": map}) // fill the map type model
                console.info("\t", map.name, ", description:", map.description, ", style:", map.style, ", night mode:", map.night);
            }
            if (!root.offlineMapsEnabled) {
                fetchCurrentLocation();
            }
        }
    }

    function getMapType(name) {
        if (!mainMap.mapReady || !mapTypeModel.count) {
            return
        }
        for (var i = 0; i < mapTypeModel.count; i++) {
            var map = mapTypeModel.get(i);
            if (map && map.name === name) {
                return map.data;
            }
        }
    }

    QtObject {
        id: priv
        readonly property var plugins: ["mapboxgl", "osm"]
        property var positionCoordinate: offlineMapsEnabled ? QtPositioning.coordinate(57.709912, 11.966632) // Gothenburg
                                                            : QtPositioning.coordinate(49.5938686, 17.2508706) // Olomouc
        property var originalPosition: positionCoordinate
        readonly property string defaultLightThemeId: "mapbox://styles/qtauto/cjcm1by3q12dk2sqnquu0gju9"
        readonly property string defaultDarkThemeId: "mapbox://styles/qtauto/cjcm1czb812co2sno1ypmp1r8"
    }

    ListModel {
        // lists the various map styles (including the custom ones); filled in Map.onMapReadyChanged
        id: mapTypeModel
    }

    Plugin {
        id: mapPlugin
        locales: Style.languageLocale
        preferred: priv.plugins

        readonly property string cacheDirUrl: StandardPaths.writableLocation(StandardPaths.CacheLocation);

        // Mapbox Plugin Parameters
        PluginParameter {
            name: "mapboxgl.access_token"
            value: "pk.eyJ1IjoicXRhdXRvIiwiYSI6ImNqY20wbDZidzBvcTQyd3J3NDlkZ21jdjUifQ.4KYDlP7UmQEVPYffr6VuVQ"
        }
        PluginParameter {
            name: "mapboxgl.mapping.additional_style_urls"
            value: [priv.defaultLightThemeId, priv.defaultDarkThemeId].join(",")
        }

        // OSM Plugin Parameters
        PluginParameter { name: "osm.useragent"; value: "Neptune UI" }

        // Offline maps support
        PluginParameter { name: "mapboxgl.mapping.cache.directory";
            // needs to be an absolute filepath so strip the file:/// protocol; several leading slashes don't matter
            value: mapPlugin.cacheDirUrl.toString().substring(mapPlugin.cacheDirUrl.indexOf(':')+1) }
    }

    // This is needed since MapBox plugin does not support geocoding yet. TODO: find a better way to support geocoding.
    Plugin {
        id: geocodePlugin
        name: "osm"
        locales: Style.languageLocale

        // OSM Plugin Parameters
        PluginParameter { name: "osm.useragent"; value: "Neptune UI" }
    }

    GeocodeModel {
        id: geocodeModel
        plugin: geocodePlugin
        limit: 20
    }

    MapView {
        id: mainMap
        anchors.fill: parent
        plugin: mapPlugin
        routingPlugin: geocodePlugin
        center: priv.positionCoordinate
        state: root.state
        currentLocation: priv.positionCoordinate
        offlineMapsEnabled: root.offlineMapsEnabled
        activeMapType: {
            if (!mapReady || plugin.name !== "mapboxgl") {
                return supportedMapTypes[0];
            }
            return NeptuneStyle.theme === NeptuneStyle.Light ? getMapType(priv.defaultLightThemeId) : getMapType(priv.defaultDarkThemeId);
        }
        onOpenSearchTextInput: {
            root.maximizeMap();
            searchViewEnabled = true;
        }
        onStartNavigationRequested: {
            priv.originalPosition = priv.positionCoordinate;
        }
        onShowRouteRequested: {
            priv.originalPosition = priv.positionCoordinate;
        }
        onStopNavigationRequested: {
            priv.positionCoordinate = priv.originalPosition;
            mainMap.center = priv.positionCoordinate;
        }

        onMapReadyChanged: getAvailableMapsAndLocation();
        onMaximizeMap: root.maximizeMap()
    }

    NeptuneControls.Tool {
        anchors.left: parent.left
        anchors.leftMargin: Style.hspan(0.6)
        anchors.top: parent.top
        anchors.topMargin: Style.vspan(0.6)
        opacity: root.state === "Widget1Row" ? 1 : 0
        Behavior on opacity { DefaultNumberAnimation {} }
        visible: opacity > 0
        symbol: Qt.resolvedUrl("assets/ic-search.png")
        background: Image {
            fillMode: Image.Pad
            source: Style.localAsset("floating-button-bg", NeptuneStyle.theme)
        }
        onClicked: root.maximizeMap()
    }

    FastBlur {
        anchors.fill: mainMap
        source: mainMap
        radius: 64
        visible: searchViewEnabled
    }

    BorderImage {
        id: overlay
        anchors.fill: root
        border.top: 322
        border.bottom: 323
        border.left: 0
        border.right: 0
        source: Style.gfx2("input-overlay")
        visible: searchViewEnabled
    }

    ColumnLayout {
        id: searchOverlay
        anchors.fill: root
        anchors.topMargin: Style.vspan(1)
        visible: searchViewEnabled
        spacing: Style.vspan(1)

        NeptuneControls.Tool {
            anchors.left: parent.left
            anchors.leftMargin: Style.hspan(1)
            symbol: Style.symbol("ic_back")
            onClicked: searchViewEnabled = false
            text: qsTr("Back")
        }

        MapSearchTextField {
            id: searchField
            anchors.left: parent.left
            anchors.leftMargin: Style.hspan(2)
            anchors.right: parent.right
            anchors.rightMargin: Style.hspan(2)
            selectByMouse: true
            focus: searchViewEnabled
            busy: geocodeModel.status == GeocodeModel.Loading
            onAccepted: {
                geocodeModel.query = searchField.text;
                geocodeModel.update();
                searchViewEnabled = false;
            }
            onTextChanged: {
                if (text.length > 1) {
                    searchTimer.restart();
                } else {
                    searchTimer.stop();
                    geocodeModel.reset();
                }
            }
            Keys.onEscapePressed: searchViewEnabled = false
        }

        ListView {
            id: searchResultsList
            Layout.fillHeight: true
            anchors.left: parent.left
            anchors.leftMargin: Style.hspan(2)
            anchors.right: parent.right
            anchors.rightMargin: Style.hspan(2)
            clip: true
            model: geocodeModel
            visible: searchViewEnabled
            state: root.state
            delegate: NeptuneControls.ListItem {
                id: itemDelegate
                width: parent.width
                height: Style.vspan(1.5)
                readonly property string addressText: locationData.address.text
                readonly property string city: locationData.address.city
                readonly property string country: locationData.address.country
                text: addressText
                subText: itemDelegate.city !== "" ? itemDelegate.city + ", " + itemDelegate.country : itemDelegate.country;
                onClicked: {
                    searchViewEnabled = false;
                    mainMap.center = locationData.coordinate;
                    mainMap.startCoord = priv.positionCoordinate;
                    mainMap.destCoord = locationData.coordinate;
                    mainMap.destination = itemDelegate.addressText;
                    if (locationData.boundingBox.isValid) {
                        mainMap.visibleRegion = locationData.boundingBox;
                    }
                    mainMap.navigationMode = true;
                }
            }
            onStateChanged: {
                if (state !== "Maximized") {
                    searchViewEnabled = false;
                }
            }
            ScrollIndicator.vertical: ScrollIndicator {}
        }
    }

    Timer {
        id: searchTimer
        interval: 500
        onTriggered: {
            geocodeModel.query = searchField.text;
            geocodeModel.update();
        }
    }
}