~guilhem-bonnefille/unav/doc-add-hacking

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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
/*
 * uNav http://launchpad.net/unav
 * Copyright (C) 2015-2016 Marcos Alvarez Costales https://launchpad.net/~costales
 * Copyright (C) 2015-2016 JkB https://launchpad.net/~joergberroth
 * Copyright (C) 2016 Nekhelesh Ramananthan https://launchpad.net/~nik90
 *
 * uNav is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * uNav is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

import QtQuick 2.4
import Ubuntu.Web 0.2
import Ubuntu.Components 1.3
import QtQuick.Layouts 1.1
import Ubuntu.Components.Popups 1.3
import Qt.labs.settings 1.0
import com.canonical.Oxide 1.9 as Oxide
import Ubuntu.Content 1.1
import QtMultimedia 5.0
import QtFeedback 5.0
import QtSystemInfo 5.0
import QtQuick.XmlListModel 2.0
import "components"
import "js/utils.js" as QmlJs
import "js/db.js" as UnavDB
import QtQuick.LocalStorage 2.0
import QtQuick.Window 2.2

Window {
    id: unavWindow

    title: "uNav"
    width: units.gu(150)
    height: units.gu(100)
    minimumWidth: units.gu(60)
    minimumHeight: units.gu(80)

    MainView {
        id: navApp

        objectName: "navApp"
        applicationName: "navigator.costales"

        Component.onCompleted: {
            // Translations
            i18n.domain = "unav";
            i18n.bindtextdomain("unav", "nav/locales/mo");
        }

        anchorToKeyboard: true

        width: unavWindow.width + units.gu(0.1) //TODO: Investigate why this is needed
        height: unavWindow.height + units.gu(0.1) //TODO: Investigate why this is needed

        property string applicationVersion: "0.62"
        property string mapUrl: "../nav/index.html"
        property string appUA: "Mozilla/5.0 (Linux; Android 5.0; Nexus 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.102 Mobile Safari/537.36"

        // persistent app settings:
        property var settings: Settings {
            property int soundIndications: 0 // 0 voice 1 notification 2 none
            property int layer: 0
            property int onlineLayer: 0
            property int unit: 0
            property int routingMode: 0 // 0 car, 1 walk, 2 bicycle
            property bool avoidTolls: false
            property bool alertRadars: false
            property bool legalRadarShow: true
            property string prevLat: ''
            property string prevLng: ''
            property int prevZoom: 9999
            property bool uiShowSpeed: false
            property bool saveHistory: true
            property bool headerVisible: true
            property bool showTuto: true
            property int defaultDistancePOI: 1
            
            property string default_coord_0a: '51.506177'
            property string default_coord_1a: '-0.100236'
            property string default_coord_2a: '51'
            property string default_coord_2b: '30'
            property string default_coord_2c: '22.23'
            property string default_coord_2d: 'N'
            property string default_coord_3a: '0'
            property string default_coord_3b: '6'
            property string default_coord_3c: '0.84'
            property string default_coord_3d: 'W'
        }

        ScreenSaver {
            id: screenSaver
            screenSaverEnabled: !Qt.application.active
        }

        AdaptivePageLayout {
            id: mainPageStack

            property int maxWidth: units.gu(125)
            property bool childPageOpened: false

            function showSideBar() {
                childPageOpened = true
            }

            function hideSideBar() {
                childPageOpened = false
            }

            anchors.fill: parent
            primaryPage: navigationPage

            layouts:[
                PageColumnsLayout {
                    id: standardlayout

                    when: navApp.settings.showTuto

                    PageColumn {
                        fillWidth: true
                    }
                },

                PageColumnsLayout {
                    id: nonstandardlayout
                    when: !navApp.settings.showTuto && width >= mainPageStack.maxWidth && mainPageStack.childPageOpened

                    // column #0
                    PageColumn {
                        fillWidth: true
                    }

                    // column #1
                    PageColumn {
                        minimumWidth: units.gu(30)
                        maximumWidth: mainPageStack.maxWidth
                        preferredWidth: units.gu(50)
                    }
                }
            ]

            Component.onCompleted: {
                // If uNav is being opened for the first time, show the welcome tutorial in just one column
                if (navApp.settings.showTuto) {
                    mainPageStack.addPageToCurrentColumn(mainPageStack.primaryPage, Qt.resolvedUrl("tuto/WelcomeWizard.qml"))
                }
            }

            property string currentLat: "null"
            property string currentLng: "null"
            property string endLat: "null"
            property string endLng: "null"
            property string clickedLat: "null"
            property string clickedLng: "null"
            property string ptFromLat: "null"
            property string ptFromLng: "null"
            property string routeState: "no"
            property int center_onpos: 0 // 0 GPS off, 1 GPS on + not center, 2 GPS on + center
            property bool favPopup: false
            property bool onLoadingExecuted: false

            property string usContext: "messaging://"
            // Workaround: as long as map keeps a webcontainer this function handles js events to the webview.
            function executeJavaScript(code) {
                var req = webview.rootFrame.sendMessage(mainPageStack.usContext, "EXECUTE", {code: code});
                //req.onreply = function (msg) {
                //console.log(msg.str);
                //}
                req.onerror = function (code, explanation) {
                    console.log("Error " + code + ": " + explanation)
                }
            }

            Page {
                id: navigationPage

                property bool buttonsEnabled: false

                anchors.fill: parent

                header: UNavHeader {
                    id: header

                    title: "uNav"
                    visible: navApp.settings.headerVisible

                    leadingActionBar {
                        width: 0
                        visible: false
                    }

                    trailingActionBar {
                        numberOfSlots: 4
                        actions: [
                            Action {
                                id: actionSettings
                                iconName: "settings"
                                text: i18n.tr("Settings")
                                enabled: navigationPage.buttonsEnabled
                                onTriggered: {
                                    mainPageStack.showSideBar()
                                    mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("SettingsPage.qml"))
                                }
                            },

                            Action {
                                id: centerPosAction
                                iconName: mainPageStack.center_onpos ? "media-optical-symbolic" : "gps"
                                text: i18n.tr("Center on Position")
                                enabled: navigationPage.buttonsEnabled && mainPageStack.center_onpos !== 2
                                onTriggered: {
                                    if (mainPageStack.center_onpos === 0) {
                                        notificationBar.text =  i18n.tr("Searching your position… This could take a while");
                                        notificationBar.info();
                                        notificationBarTimer.start();
                                    }
                                    mainPageStack.center_onpos = 2;
                                    goThereActionPopover.hide();
                                    mainPageStack.executeJavaScript("center_pos()");
                                }
                            },

                            Action {
                                id: searchAction
                                iconName: "find"
                                shortcut: "Ctrl+F"
                                text: i18n.tr("Search")
                                enabled: navigationPage.buttonsEnabled
                                onTriggered: {
                                    mainPageStack.showSideBar()
                                    mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("SearchPage.qml"))
                                }
                            },

                            Action {
                                id: cancelAction
                                iconSource: Qt.resolvedUrl("../nav/img/header/nav-actions.svg")
                                text: i18n.tr("Destination")
                                visible: mainPageStack.routeState !== 'no'
                                enabled: navigationPage.buttonsEnabled
                                onTriggered: {
                                    goThereActionPopover.hide();
                                    goThereActionPopover.showMenu = true;
                                    goThereActionPopover.show();
                                }
                            }
                        ]
                    }
                }

                /**
            Workaround:
            QML Map Element currently does not support flicking. This makes it unusable to this app so far.
            As long as this is to supported, the map view falls back to a html5 container that renders the navigation.
            Signals from qml are sent via eventhandlers in oxide via userScript.
            The panel stays in html5, too, for ease of integration.
            **/

                WebContext {
                    id: webcontext
                    userAgent: navApp.appUA
                    userScripts: [
                        Oxide.UserScript {
                            context: mainPageStack.usContext
                            url: Qt.resolvedUrl("js/oxide.js")
                        }
                    ]
                }

                WebView {
                    id: webview
                    anchors.fill: parent
                    z: -6
                    context: webcontext
                    url: navApp.mapUrl
                    preferences.allowFileAccessFromFileUrls: true
                    preferences.allowUniversalAccessFromFileUrls: true
                    preferences.appCacheEnabled: true
                    preferences.javascriptCanAccessClipboard: true
                    preferences.javascriptEnabled: true
                    //not used right now:
                    //filePicker: filePickerLoader.item

                    // get in-webcontainer click events (e.g. click on map)
                    // and coordinates to handle them in qml ui:
                    onNavigationRequested:{
                        // We could start to clean this up a bit by writing functions on that...
                        var url = request.url.toString().split("?");
                        var params = url[1].split("/");
                        switch (url[0]) {
                        case "http://go/":
                            Qt.openUrlExternally(url[1]);
                            break;

                        case "http://get_routeinfo_list/":
                            var dec_routeList = decodeURIComponent(url[1]);
                            mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("RouteInfoListPage.qml"), { routeList: JSON.parse(dec_routeList) });
                            break;

                        case "http://route_status/":
                            mainPageStack.currentLat = params[0];
                            mainPageStack.currentLng = params[1];
                            mainPageStack.endLat = params[2];
                            mainPageStack.endLng = params[3];
                            mainPageStack.routeState = params[4];
                            break;

                        case "http://clicked_on_map/":
                            goThereActionPopover.hide();
                            goThereActionPopover.osm_type = 'none';
                            goThereActionPopover.osm_id = 'none';
                            goThereActionPopover.phone = '';
                            goThereActionPopover.poiName = "";
                            notificationBar.visible = false;
                            
                            if (params[0] === 'nofollow' && mainPageStack.center_onpos === 2)
                                mainPageStack.center_onpos = 1;
                            
                            mainPageStack.clickedLat = params[1];
                            mainPageStack.clickedLng = params[2];
                            
                            if (params[3] !== 'none')
                                goThereActionPopover.osm_type = params[3];
                            
                            if (params[4] !== 'none')
                                goThereActionPopover.osm_id = params[4];
                            
                            if (params[5] !== 'none')
                                goThereActionPopover.phone = params[5];
                            
                            if (params[6] !== "none")
                                goThereActionPopover.poiName = decodeURIComponent(params[6]);

                            mainPageStack.favPopup = false;
                            goThereActionPopover.show();

                            // Perform reverse geocoding only when it is a generic marker that the user clicked on the map
                            if (goThereActionPopover.poiName === "" && goThereActionPopover.osm_id === 'none') {
                                reverseXmlModel.reverseSearch(mainPageStack.clickedLat, mainPageStack.clickedLng);
                            }
                            break;

                        case "http://hide_popup/":
                            goThereActionPopover.hide();
                            break;
                            
                        case "http://set_center_onpos/":
                            switch (params[0]) {
                            case '0': // GPS Denied (special)
                                mainPageStack.routeState = 'no';
                                mainPageStack.center_onpos = 0;
                                break;
                            case '1':
                                mainPageStack.center_onpos = 1;
                                break;
                            case '2':
                                mainPageStack.center_onpos = 2;
                                break;
                            }
                            break;
                            
                        case "http://set_ui_speed/":
                            if (params[0] === 'true')
                                navApp.settings.uiShowSpeed = true;
                            else
                                navApp.settings.uiShowSpeed = false;
                            break;
                            
                        case "http://cancel_route/":
                            mainPageStack.routeState = 'no';
                            break;

                        case "http://save_pos/":
                            navApp.settings.prevLat = params[0];
                            navApp.settings.prevLng = params[1];
                            navApp.settings.prevZoom = params[2];
                            break;
                        
                        case "http://show_notification/":
                            switch (params[0]) {
                                case "info":
                                    notificationBar.info();
                                    break;
                                case "warning":
                                    notificationBar.warning();
                                    break;
                                case "critical":
                                    notificationBar.critical();
                                    break;
                            }
                            switch (params[1]) {
                                case "speed_camera_error":
                                    notificationBar.text =  i18n.tr("Error getting speed cameras!");
                                    break;
                                case "webapi_error":
                                    notificationBar.text =  i18n.tr("Error finding route! Retrying again in 30 seconds…");
                                    break;
                                case "calcfromout_error":
                                    notificationBar.text =  i18n.tr("Error finding route! Trying again…");
                                    break;
                            }
                            notificationBarTimer.start();
                        }
                        
                        request.action = Oxide.NavigationRequest.ActionReject;
                    }

                    Component.onCompleted: {
                        preferences.localStorageEnabled = true
                    }

                    onLoadingStateChanged: {
                        if (!loading && !mainPageStack.onLoadingExecuted) {
                            mainPageStack.onLoadingExecuted = true;
                            //send saved Setting states:
                            mainPageStack.executeJavaScript("settings.set_sound(" + navApp.settings.soundIndications + ");");
                            if (!navApp.settings.layer) {
                                if (!navApp.settings.onlineLayer) // Terrain
                                    mainPageStack.executeJavaScript("ui.set_map_layer('terrain');");
                                else // OSM
                                    mainPageStack.executeJavaScript("ui.set_map_layer('OSM');");
                            }
                            else {
                                mainPageStack.executeJavaScript("ui.set_map_layer('offline');");
                            }
                            mainPageStack.executeJavaScript("settings.set_unit(\'" + ( navApp.settings.unit === 0 ? "km" : "mi" ) +"\');");
                            mainPageStack.executeJavaScript("ui.set_scale_unit(\'" + ( navApp.settings.unit === 0 ? "km" : "mi" ) +"\');");
                            mainPageStack.executeJavaScript("settings.set_routing_mode(" + navApp.settings.routingMode + ");");
                            mainPageStack.executeJavaScript("settings.set_avoid_tolls(" + navApp.settings.avoidTolls + ");");
                            mainPageStack.executeJavaScript("settings.set_alert_radars(" + navApp.settings.alertRadars + ");");
                            mainPageStack.executeJavaScript("settings.set_ui_speed(" + navApp.settings.uiShowSpeed + ");");

                            // Center map in last position
                            if (navApp.settings.prevLat !== '' && navApp.settings.prevLng !== '' && navApp.settings.prevLat !== null && navApp.settings.prevLng !== null && navApp.settings.prevZoom !== 9999) {
                                mainPageStack.executeJavaScript("map.getView().setCenter(ol.proj.transform([" + navApp.settings.prevLng + "," + navApp.settings.prevLat + "], 'EPSG:4326', 'EPSG:3857')); map.getView().setZoom(" + navApp.settings.prevZoom + ");");
                            }

                            // Hack: If user click so fast in buttons, app breaks sometimes
                            navigationPage.buttonsEnabled = true;

                            // Catching urls
                            var url_dispatcher = Qt.application.arguments[1];
                            if (QmlJs.is_url_dispatcher(url_dispatcher)['is_dispatcher']) {
                                var coord = QmlJs.get_url_coord(url_dispatcher);
                                if (coord['lat'] !== null && coord['lng'] !== null) {
                                    mainPageStack.clickedLat = coord['lat'];
                                    mainPageStack.clickedLng = coord['lng'];
                                    if (mainPageStack.center_onpos === 2)
                                        mainPageStack.center_onpos = 1;
                                    mainPageStack.executeJavaScript("ui.markers_POI_set([{title: \"" + i18n.tr("Shared Position") + "\", lat: " + mainPageStack.clickedLat + ", lng: " + mainPageStack.clickedLng + "}])");
                                    mainPageStack.favPopup = false;
                                    goThereActionPopover.show();
                                }
                            }
                        }
                    }

                    onGeolocationPermissionRequested: { request.allow() }
                }

                Connections {
                    target: UriHandler
                    onOpened: {
                        if (uris.length === 0 ) {
                            return;
                        }
                        // Catching urls
                        var url_dispatcher = uris[0];
                        if (QmlJs.is_url_dispatcher(url_dispatcher)['is_dispatcher']) {
                            var coord = QmlJs.get_url_coord(url_dispatcher);
                            if (coord['lat'] !== null && coord['lng'] !== null) {
                                mainPageStack.clickedLat = coord['lat'];
                                mainPageStack.clickedLng = coord['lng'];
                                if (mainPageStack.center_onpos === 2)
                                    mainPageStack.center_onpos = 1;
                                mainPageStack.executeJavaScript("ui.markers_POI_set([{title: \"" + i18n.tr("Shared Position") + "\", lat: " + mainPageStack.clickedLat + ", lng: " + mainPageStack.clickedLng + "}])");
                                mainPageStack.favPopup = false;
                                goThereActionPopover.show();
                            }
                        }
                    }
                }

                Loader {
                    id: actionButtonRowLoader
                    sourceComponent: !header.visible ? actionButtonRowComponent : undefined
                    anchors { right: parent.right; top: parent.top; margins: units.gu(1) }
                }

                Component {
                    id: actionButtonRowComponent
                    Row {
                        id: actionButtonRow

                        opacity: navigationPage.buttonsEnabled ? 1.0 : 0.2

                        ActionIcon {
                            icon.source: Qt.resolvedUrl("../nav/img/header/nav-actions-transparent.svg")
                            enabled: navigationPage.buttonsEnabled
                            visible: mainPageStack.routeState !== 'no'
                            onClicked: {
                                goThereActionPopover.hide();
                                goThereActionPopover.showMenu = true;
                                goThereActionPopover.show();
                            }
                        }

                        ActionIcon {
                            icon.name: "find"
                            enabled: navigationPage.buttonsEnabled
                            onClicked: {
                                mainPageStack.showSideBar()
                                mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("SearchPage.qml"))
                            }
                        }

                        ActionIcon {
                            icon.name: mainPageStack.center_onpos ? "media-optical-symbolic" : "gps"
                            enabled: navigationPage.buttonsEnabled && mainPageStack.center_onpos !== 2
                            onClicked: {
                                if (mainPageStack.center_onpos === 0) {
                                    notificationBar.text =  i18n.tr("Searching your position… This could take a while");
                                    notificationBar.info();
                                    notificationBarTimer.start();
                                }
                                mainPageStack.center_onpos = 2;
                                goThereActionPopover.hide();
                                mainPageStack.executeJavaScript("center_pos()");
                            }
                        }

                        ActionIcon {
                            icon.name: "settings"
                            enabled: navigationPage.buttonsEnabled
                            onClicked: {
                                mainPageStack.showSideBar()
                                mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("SettingsPage.qml"))
                            }
                        }
                    }
                }

                Item {
                    clip: true
                    width: zoomButtons.width + units.gu(2)
                    height: zoomButtons.height + units.gu(6)
                    anchors { right: parent.right; verticalCenter: parent.verticalCenter; verticalCenterOffset: units.gu(-3) }
                    ZoomButtons {
                        id: zoomButtons
                        visible: navigationPage.buttonsEnabled
                        onZoomedIn: mainPageStack.executeJavaScript("custom_zoom(1)")
                        onZoomedOut: mainPageStack.executeJavaScript("custom_zoom(-1)")
                    }
                }

                Timer {
                    id: notificationBarTimer
                    interval: 4000
                    repeat: false
                    onTriggered: {
                        notificationBar.visible = false
                    }
                }

                NotificationBar {
                    id: notificationBar
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            notificationBarTimer.stop()
                            notificationBar.visible = false
                        }
                    }
                }

                XmlListModel {
                    id: reverseXmlModel

                    readonly property string baseUrl: "https://nominatim.openstreetmap.org/reverse?format=xml&email=costales.marcos@gmail.com&addressdetails=0&extratags=1&zoom=18&namedetails=1&"

                    function reverseSearch(lat, lon) {
                        source = (baseUrl + "lat=" + lat + "&lon=" + lon) ;
                    }

                    function clear() {
                        goThereActionPopover.reverseGeoString = "";
                        source = "";
                    }

                    onStatusChanged: {
                        if (status === XmlListModel.Error || (status === XmlListModel.Ready && count === 0)) {
                            goThereActionPopover.reverseGeoString = ""
                            console.log("Error reverse geocoding the location!")
                        }

                        else if (status === XmlListModel.Ready && count > 0) {
                            // Check if the location returned by reverse geocoding is a POI by looking for the existence of certain parameters
                            // like cuisine, phone, opening_hours, internet_access, wheelchair etc that do not apply to a generic address.
                            if (reverseXmlModel.get(0).description || reverseXmlModel.get(0).cuisine || reverseXmlModel.get(0).phone || reverseXmlModel.get(0).opening_hours
                                    || reverseXmlModel.get(0).website && reverseXmlModel.get(0).wheelchair || reverseXmlModel.get(0).internet_access) {

                                // Check if the name, osm_id and osm_type are valid, otherwise the POI popup will break.
                                if (reverseXmlModel.get(0).name && reverseXmlModel.get(0).osm_id && reverseXmlModel.get(0).osm_type) {
                                    goThereActionPopover.poiName = reverseXmlModel.get(0).name
                                    goThereActionPopover.osm_id = reverseXmlModel.get(0).osm_id
                                    goThereActionPopover.osm_type = reverseXmlModel.get(0).osm_type.charAt(0).toUpperCase()
                                    goThereActionPopover.phone = reverseXmlModel.get(0).phone
                                } else {
                                    goThereActionPopover.reverseGeoString = reverseXmlModel.get(0).result
                                }
                            }

                            // If nothing works, fall back to just showing the address in a generic popup
                            else {
                                goThereActionPopover.reverseGeoString = reverseXmlModel.get(0).result
                            }
                        }
                    }

                    source: ""
                    query: "/reversegeocode"

                    XmlRole { name: "osm_type"; query: "result/@osm_type/string()" }
                    XmlRole { name: "osm_id"; query: "result/@osm_id/string()" }
                    XmlRole { name: "result"; query: "result/string()" }
                    XmlRole { name: "name"; query: "namedetails/name/string()" }
                    XmlRole { name: "description"; query: "extratags/tag[@key='description']/@value/string()" }
                    XmlRole { name: "cuisine"; query: "extratags/tag[@key='cuisine']/@value/string()" }
                    XmlRole { name: "phone"; query: "extratags/tag[@key='phone']/@value/string()" }
                    XmlRole { name: "opening_hours"; query: "extratags/tag[@key='opening_hours']/@value/string()" }
                    XmlRole { name: "website"; query: "extratags/tag[@key='website']/@value/string()" }
                    XmlRole { name: "internet_access"; query: "extratags/tag[@key='internet_access']/@value/string()" }
                    XmlRole { name: "wheelchair"; query: "extratags/tag[@key='wheelchair']/@value/string()" }
                }

                PoiPopup {
                    id: goThereActionPopover

                    // Dragons be here! Don't change these values
                    hidePosition: -3*height
                    showPosition: navApp.settings.headerVisible ? 0 : -navigationPage.header.height
                    anchors { top: navigationPage.header.bottom }

                    height: mainContentLoader.height + 2*mainContentLoader.anchors.margins

                    property string reverseGeoString: ""
                    property string poiName
                    property string osm_type
                    property string osm_id
                    property string phone
                    property bool showMenu: false

                    onIsShownChanged: {
                        if (!goThereActionPopover.isShown) {
                            reverseXmlModel.clear()
                            goThereActionPopover.showMenu = false
                        }
                    }

                    Loader {
                        id: mainContentLoader

                        sourceComponent: {
                            if (goThereActionPopover.isShown) {
                                if (goThereActionPopover.showMenu) {
                                    return routeMenu
                                }

                                if (goThereActionPopover.osm_id === 'none') {
                                    return genericPopupComponent
                                }
                                return poiPopupComponent
                            }
                            return undefined
                        }

                        anchors { top: parent.top; left: parent.left; right: parent.right; margins: units.gu(2) }
                    }

                    Component {
                        id: routeMenu
                        Column {
                            height: routePageGrid.height
                            spacing: 0
                            Component.onCompleted: {
                                mainPageStack.executeJavaScript("qml_set_route_status();")
                            }

                            Row {
                                id: gridRow
                                spacing: units.gu(2)
                                anchors.horizontalCenter: parent.horizontalCenter

                                Loader {
                                    id: poiQuickAccessLoader
                                    sourceComponent: POIQuickAccessGridView {}
                                }

                                CustomGridView {
                                    id: routePageGrid

                                    ListModel {
                                        id: routePageModel
                                        Component.onCompleted: initialize()

                                        function initialize() {
                                            routePageModel.append({mode: "DESTINATION", text: i18n.tr("NearBy Destination"), iconName: "location"})
                                            routePageModel.append({mode: "CANCEL", text: i18n.tr("Cancel Route"), iconName: "dialog-error-symbolic"})
                                        }
                                    }

                                    itemWidth: units.gu(8)
                                    model: routePageModel

                                    delegate: GridDelegate {
                                        id: delegate

                                        width: units.gu(8)
                                        title: model.text
                                        icon.name: model.iconName

                                        onClicked: {
                                            if (model.mode === "DESTINATION") {
                                                mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("PoiPage.qml"), {"lat": mainPageStack.endLat, "lng": mainPageStack.endLng})
                                            } else if (model.mode === "CANCEL") {
                                                mainPageStack.routeState = 'no';
                                                mainPageStack.executeJavaScript("click_cancel_route();");
                                            }
                                            goThereActionPopover.showMenu = false
                                            goThereActionPopover.hide()
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Component {
                        id: genericPopupComponent
                        Column {
                            spacing: units.gu(2)

                            Label {
                                id: geoCodeLabel
                                maximumLineCount: 3
                                width: parent.width
                                wrapMode: Text.WordWrap
                                color: UbuntuColors.slate
                                horizontalAlignment: Text.AlignHCenter
                                textSize: !truncated ? Label.Large : Label.Medium
                                text: goThereActionPopover.poiName ? goThereActionPopover.poiName :
                                            goThereActionPopover.reverseGeoString ? goThereActionPopover.reverseGeoString :
                                                                                    i18n.tr("Coord: %1, %2").arg(parseFloat(mainPageStack.clickedLat).toFixed(5)).arg(parseFloat(mainPageStack.clickedLng).toFixed(5));
                            }

                            Row {
                                spacing: units.gu(0.5)
                                anchors.horizontalCenter: parent.horizontalCenter

                                GridIconDelegate {
                                    icon.name: "send"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    visible: goThereActionPopover.poiName !== i18n.tr("Current Position") ? true : false
                                    onClicked: {
                                        if (navApp.settings.saveHistory && goThereActionPopover.reverseGeoString) {
                                            UnavDB.saveToSearchHistory(geoCodeLabel.text, mainPageStack.clickedLat, mainPageStack.clickedLng);
                                        }
                                        goThereActionPopover.hide();
                                        mainPageStack.center_onpos = 2;
                                        mainPageStack.routeState = 'yes';
                                        mainPageStack.executeJavaScript("calc2coord(" + mainPageStack.clickedLat + ", " + mainPageStack.clickedLng + ");");
                                    }
                                }

                                GridIconDelegate {
                                    icon.name: mainPageStack.favPopup ? "starred" : "non-starred"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    onClicked: {
                                        mainPageStack.favPopup = !mainPageStack.favPopup;
                                        mainPageStack.showSideBar();
                                        var incubator = mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("SearchPage.qml"), {favLat: mainPageStack.clickedLat, favLng: mainPageStack.clickedLng, favName: ""});
                                        incubator.onStatusChanged = function(status) {
                                            if (status === Component.Ready) {
                                                incubator.object.addFavorite();
                                            }
                                        }
                                    }
                                }

                                GridIconDelegate {
                                    icon.name: "location"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    onClicked: {
                                        mainPageStack.showSideBar()
                                        mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("PoiPage.qml"), {"lat": mainPageStack.clickedLat, "lng": mainPageStack.clickedLng})
                                    }
                                }

                                GridIconDelegate {
                                    icon.name: "share"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    onClicked: {
                                        mainPageStack.showSideBar()
                                        mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("Share.qml"), {"lat": mainPageStack.clickedLat, "lon": mainPageStack.clickedLng, "isParentPage": true})
                                    }
                                }

                                GridIconDelegate {
                                    icon.name: "transfer-progress-upload"
                                    visible: mainPageStack.ptFromLat === "null"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    onClicked: {
                                        goThereActionPopover.hide();
                                        mainPageStack.ptFromLat = mainPageStack.clickedLat;
                                        mainPageStack.ptFromLng = mainPageStack.clickedLng;
                                        notificationBar.text =  i18n.tr("Simulate from here! Now click on destination");
                                        notificationBar.info();
                                        notificationBarTimer.start();

                                    }
                                }

                                GridIconDelegate {
                                    icon.name: "transfer-progress-download"
                                    visible: mainPageStack.ptFromLat !== "null"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    onClicked: {
                                        // Validate coordinates are different points
                                        if (mainPageStack.ptFromLat === mainPageStack.clickedLat && mainPageStack.ptFromLng === mainPageStack.clickedLng) {
                                            goThereActionPopover.hide();
                                            mainPageStack.ptFromLat = "null";
                                            notificationBar.text = i18n.tr("Set a different coordinates for simulating");
                                            notificationBar.warning();
                                            notificationBarTimer.start();
                                        }
                                        else {
                                            goThereActionPopover.hide();
                                            mainPageStack.routeState = 'simulate_calculating';
                                            mainPageStack.executeJavaScript("simulate2coord(" + mainPageStack.ptFromLat + ", " + mainPageStack.ptFromLng + ", " + mainPageStack.clickedLat + ", " + mainPageStack.clickedLng + ");");
                                            mainPageStack.ptFromLat = "null";
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Component {
                        id: poiPopupComponent
                        Column {
                            spacing: units.gu(2)

                            Label {
                                id: poiPopupComponentLabel
                                text: goThereActionPopover.poiName
                                visible: goThereActionPopover.poiName !== ""
                                maximumLineCount: 2
                                width: parent.width
                                horizontalAlignment: Text.AlignHCenter
                                textSize: Label.Large
                                elide: Text.ElideRight
                                wrapMode: Text.WordWrap
                                color: UbuntuColors.slate
                            }

                            Row {
                                spacing: units.gu(2)
                                anchors.horizontalCenter: parent.horizontalCenter

                                GridIconDelegate {
                                    icon.name: "send"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    onClicked: {
                                        if (navApp.settings.saveHistory) {
                                            UnavDB.saveToSearchHistory(poiPopupComponentLabel.text, mainPageStack.clickedLat, mainPageStack.clickedLng);
                                        }
                                        goThereActionPopover.hide();
                                        mainPageStack.center_onpos = 2;
                                        mainPageStack.routeState = 'yes';
                                        mainPageStack.executeJavaScript("calc2coord(" + mainPageStack.clickedLat + ", " + mainPageStack.clickedLng + ");");
                                    }
                                }

                                GridIconDelegate {
                                    icon.name: "call-start"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    visible: goThereActionPopover.phone !== ""
                                    onClicked: {
                                        Qt.openUrlExternally("tel:///" + goThereActionPopover.phone)
                                    }
                                }

                                GridIconDelegate {
                                    icon.name: "info"
                                    icon.height: units.gu(3)
                                    highlightSize: units.gu(-1)
                                    onClicked: {
                                        goThereActionPopover.hide();
                                        mainPageStack.showSideBar()
                                        mainPageStack.addPageToNextColumn(mainPageStack.primaryPage, Qt.resolvedUrl("PoiDetailsPage.qml"), {osm_id: goThereActionPopover.osm_id, osm_type: goThereActionPopover.osm_type, poiName: goThereActionPopover.poiName, isParentPage: true})
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        Connections {
            target: Qt.application
            onStateChanged:
                if(Qt.application.state !== Qt.ApplicationActive) {
                    mainPageStack.executeJavaScript("qml_save_pos();");
                }
        }
    }
}