Amine Jery
Amine Jery

Reputation: 1

Qml: ReferenceError: mainWindow is not defined

I'am trying to display markers in the openstreetmap dynamically but I am getting this error
<qrc:/QmlMap.qml:34>: ReferenceError: mainWindow is not defined
i am getting the coordinates by the geocoding fonction
here is the code I used to understand better

QML file:

import QtQuick 2.0
import QtLocation 5.9
import QtPositioning 5.9

Rectangle {
    id: window

    property Component markerComponent
    property var markers: []

    Plugin {
        id: mapPlugin
        name: "osm"
        PluginParameter {
            name: "osm.mapping.custom.host";
            value: "https://tile.openstreetmap.org/"
        }
    }

    Map {
        id: mapView
        anchors.fill: parent
        plugin: mapPlugin
        center: QtPositioning.coordinate(36.897633, 10.189658) // Default center
        zoomLevel: 10

        Component.onCompleted: {
            markerComponent = mapMarker
            addFournisseurMarkers(); // Call the function to add fournisseur markers
        }

        // Function to add markers for fournisseurs
        function addFournisseurMarkers() {
            var coordinatesList = mainWindow.getFournisseurCoordinatesList(); // Call C++ function to get coordinates
            for (var i = 0; i < coordinatesList.length; ++i) {
                var coord = coordinatesList[i];
                addMarker(coord[0], coord[1]); // Call addMarker function with latitude and longitude
            }
        }

        // Function to add a marker dynamically
        function addMarker(lat, lng) {
            console.log("Adding marker at latitude:", lat, "and longitude:", lng);
            var marker = markerComponent.createObject(mapView, { coordinate: QtPositioning.coordinate(lat, lng) });
            if (marker !== null) {
                console.log("Marker created successfully.");
                markers.push(marker);
            } else {
                console.error("Failed to create marker.");
            }
        }

        // Function to clear all markers
        function clearMarkers() {
            for (var i = 0; i < markers.length; ++i) {
                markers[i].destroy();
            }
            markers = [];
        }
    }

    Component {
        id: mapMarker
        MapQuickItem {
            anchorPoint.x: image.width / 4
            anchorPoint.y: image.height
            sourceItem: Image {
                source: "http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_red.png"
            }
        }
    }
}  

and here is my main.cpp

#include "mainwindow.h"
#include "connection.h"
#include <QMessageBox>
#include <QApplication>
#include <QFile>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Load stylesheet
    QFile styleFile("C:/Users/Wizin/Desktop/myprojet/rstudio-gnome-dark.qss");
    if (!styleFile.open(QFile::ReadOnly))
    {
        QMessageBox::critical(nullptr, QObject::tr("Stylesheet Error"),
                              QObject::tr("Failed to open stylesheet file."));
        return 1; // Exit with error
    }
    QString style = QLatin1String(styleFile.readAll());
    a.setStyleSheet(style);

    // Create database connection
    Connection c;
    bool test = c.createconnect();

    // Create main window
    MainWindow w;

    // Test database connection and display result
    if (test)
    {
        w.show();
        QMessageBox::information(nullptr, QObject::tr("Database Open"),
                                 QObject::tr("Connection successful.\nClick Cancel to exit."),
                                 QMessageBox::Cancel);
    }
    else
    {
        QMessageBox::critical(nullptr, QObject::tr("Database Error"),
                              QObject::tr("Failed to connect to database.\nClick Cancel to exit."),
                              QMessageBox::Cancel);
    }

    // Expose mainWindow to QML
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("mainWindow", &w);
    engine.load(QUrl(QStringLiteral("qrc:/QmlMap.qml")));

    return a.exec();
}

and here is the geocoding fonction it works properly

QPair<double, double> MainWindow::geocodeAddress(const QString& address)
{
    qDebug() << "Geocoding address:" << address;

    QString urlString = "https://nominatim.openstreetmap.org/search?format=json&q=" + address;
    QUrl url(urlString);

    qDebug() << "Request URL:" << url;

    QNetworkAccessManager manager;
    QEventLoop eventLoop;
    connect(&manager, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);

    QNetworkReply *reply = manager.get(QNetworkRequest(url));
    eventLoop.exec();

    double latitude = 0.0;
    double longitude = 0.0;

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray responseData = reply->readAll();
        qDebug() << "Response Data:" << responseData;

        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        if (jsonDoc.isArray() && !jsonDoc.isEmpty()) {
            QJsonObject firstResult = jsonDoc.array().first().toObject();
            latitude = firstResult["lat"].toString().toDouble();
            longitude = firstResult["lon"].toString().toDouble();
            qDebug() << "Latitude:" << latitude << ", Longitude:" << longitude;

        } else {
            qDebug() << "No coordinates found for the given address.";
        }
    } else {
        qDebug() << "Error:" << reply->errorString();
    }
    reply->deleteLater();

    return qMakePair(latitude, longitude);
}

and here is

QList<QPair<double, double>> MainWindow::getFournisseurCoordinatesList() {
    QList<QString> fournisseurAddresses = fournisseur.retrieveAddressesFromDatabase();
    QList<QPair<double, double>> coordinatesList;

    for (const QString& address : fournisseurAddresses) {
        QPair<double, double> coordinates = geocodeAddress(address);
        if (coordinates.first != 0.0 || coordinates.second != 0.0) {
            coordinatesList.append(coordinates);
        } else {
            qDebug() << "Failed to get coordinates for address:" << address;
        }
    }

    return coordinatesList;
}

these are the used fonctions

I al willing to find solution for this problem

Upvotes: 0

Views: 51

Answers (0)

Related Questions