QGeoCodeReplyQGC.cpp 12.7 KB
Newer Older
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
/****************************************************************************
**
** Copyright (C) 2013 Aaron McCarthy <mccarthy.aaron@gmail.com>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
** 2015.4.4
41
** Adapted for use with QGroundControl
42 43 44 45 46
**
** Gus Grubba <mavlink@grubba.com>
**
****************************************************************************/

dogmaphobic's avatar
dogmaphobic committed
47 48
#include "QGeoCodeReplyQGC.h"

49 50 51 52 53 54 55
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
#include <QtPositioning/QGeoCoordinate>
#include <QtPositioning/QGeoAddress>
#include <QtPositioning/QGeoLocation>
#include <QtPositioning/QGeoRectangle>
Don Gagne's avatar
Don Gagne committed
56 57
#include <QSet>
#include <QDebug>
58

59
enum QGCGeoCodeType {
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
    GeoCodeTypeUnknown,
    StreetAddress, // indicates a precise street address.
    Route, // indicates a named route (such as "US 101").
    Intersection, // indicates a major intersection, usually of two major roads.
    Political, // indicates a political entity. Usually, this type indicates a polygon of some civil administration.
    Country, // indicates the national political entity, and is typically the highest order type returned by the Geocoder.
    AdministrativeAreaLevel1, // indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states.
    AdministrativeAreaLevel2, // indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties.
    AdministrativeAreaLevel3, // indicates a third-order civil entity below the country level. This type indicates a minor civil division.
    ColloquialArea, // indicates a commonly-used alternative name for the entity.
    Locality, // indicates an incorporated city or town political entity.
    Sublocality, // indicates a first-order civil entity below a locality. For some locations may receive one of the additional types: sublocality_level_1 through to sublocality_level_5. Each sublocality level is a civil entity. Larger numbers indicate a smaller geographic area.
    SublocalityLevel1,
    SublocalityLevel2,
    SublocalityLevel3,
    SublocalityLevel4,
    SublocalityLevel5,
    Neighborhood, // indicates a named neighborhood
    Premise, // indicates a named location, usually a building or collection of buildings with a common name
    Subpremise, // indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common name
    PostalCode, // indicates a postal code as used to address postal mail within the country.
    NaturalFeature, // indicates a prominent natural feature.
    Airport, // indicates an airport.
    Park, // indicates a named park.
    PointOfInterest, // indicates a named point of interest. Typically, these "POI"s are prominent local entities that don't easily fit in another category such as "Empire State Building" or "Statue of Liberty."
    Floor, // indicates the floor of a building address.
    Establishment, // typically indicates a place that has not yet been categorized.
    Parking, // indicates a parking lot or parking structure.
    PostBox, // indicates a specific postal box.
    PostalTown, // indicates a grouping of geographic areas, such as locality and sublocality, used for mailing addresses in some countries.
    RoomIndicates, // the room of a building address.
    StreetNumber, // indicates the precise street number.
    BusStation, //  indicate the location of a bus stop.
    TrainStation, //  indicate the location of a train stop.
    TransitStation, // indicate the location of a public transit stop.
};

class JasonMonger {
public:
    JasonMonger();
100
    QSet<int> json2QGCGeoCodeType(const QJsonArray &types);
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
private:
    int _getCode(const QString &key);
    QMap<QString, int> _m;
};

JasonMonger::JasonMonger()
{
    _m[QStringLiteral("street_address")] = StreetAddress;
    _m[QStringLiteral("route")] = Route;
    _m[QStringLiteral("intersection")] = Intersection;
    _m[QStringLiteral("political")] = Political;
    _m[QStringLiteral("country")] = Country;
    _m[QStringLiteral("administrative_area_level_1")] = AdministrativeAreaLevel1;
    _m[QStringLiteral("administrative_area_level_2")] = AdministrativeAreaLevel2;
    _m[QStringLiteral("administrative_area_level_3")] = AdministrativeAreaLevel3;
    _m[QStringLiteral("colloquial_area")] = ColloquialArea;
    _m[QStringLiteral("locality")] = Locality;
    _m[QStringLiteral("sublocality")] = Sublocality;
    _m[QStringLiteral("sublocality_level_1")] = SublocalityLevel1;
    _m[QStringLiteral("sublocality_level_2")] = SublocalityLevel2;
    _m[QStringLiteral("sublocality_level_3")] = SublocalityLevel3;
    _m[QStringLiteral("sublocality_level_4")] = SublocalityLevel4;
    _m[QStringLiteral("sublocality_level_5")] = SublocalityLevel5;
    _m[QStringLiteral("neighborhood")] = Neighborhood;
    _m[QStringLiteral("premise")] = Premise;
    _m[QStringLiteral("subpremise")] = Subpremise;
    _m[QStringLiteral("postal_code")] = PostalCode;
    _m[QStringLiteral("natural_feature")] = NaturalFeature;
    _m[QStringLiteral("airport")] = Airport;
    _m[QStringLiteral("park")] = Park;
    _m[QStringLiteral("point_of_interest")] = PointOfInterest;
    _m[QStringLiteral("floor")] = Floor;
    _m[QStringLiteral("establishment")] = Establishment;
    _m[QStringLiteral("parking")] = Parking;
    _m[QStringLiteral("post_box")] = PostBox;
    _m[QStringLiteral("postal_town")] = PostalTown;
    _m[QStringLiteral("room indicates")] = RoomIndicates;
    _m[QStringLiteral("street_number")] = StreetNumber;
    _m[QStringLiteral("bus_station")] = BusStation;
    _m[QStringLiteral("train_station")] = TrainStation;
    _m[QStringLiteral("transit_station")] = TransitStation;
}

int JasonMonger::_getCode(const QString &key) {
    return _m.value(key, GeoCodeTypeUnknown);
}

148
QSet<int> JasonMonger::json2QGCGeoCodeType(const QJsonArray &types) {
149 150 151 152 153 154 155 156 157
    QSet<int> result;
    for (int i=0; i<types.size(); ++i) {
        result |= _getCode(types[i].toString());
    }
    return result;
}

JasonMonger kMonger;

158
QGeoCodeReplyQGC::QGeoCodeReplyQGC(QNetworkReply *reply, QObject *parent)
159 160 161 162 163 164 165 166 167 168
:   QGeoCodeReply(parent), m_reply(reply)
{
    connect(m_reply, SIGNAL(finished()), this, SLOT(networkReplyFinished()));
    connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(networkReplyError(QNetworkReply::NetworkError)));

    setLimit(1);
    setOffset(0);
}

169
QGeoCodeReplyQGC::~QGeoCodeReplyQGC()
170 171 172 173 174
{
    if (m_reply)
        m_reply->deleteLater();
}

175
void QGeoCodeReplyQGC::abort()
176 177 178 179 180 181 182 183 184 185
{
    if (!m_reply)
        return;

    m_reply->abort();

    m_reply->deleteLater();
    m_reply = 0;
}

186
void QGeoCodeReplyQGC::networkReplyFinished()
187 188 189 190 191 192 193 194 195
{
    if (!m_reply)
        return;

    if (m_reply->error() != QNetworkReply::NoError)
        return;

    QJsonDocument document = QJsonDocument::fromJson(m_reply->readAll());
    QJsonObject object = document.object();
dogmaphobic's avatar
dogmaphobic committed
196

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    if (object.value(QStringLiteral("status")) != QStringLiteral("OK")) {
        QString error = object.value(QStringLiteral("status")).toString();
        qWarning() << m_reply->url() << "returned" << error;
        setError(QGeoCodeReply::CommunicationError, error);
        m_reply->deleteLater();
        m_reply = 0;
        return;
    }

    QList<QGeoLocation> locations;
    QJsonArray results = object.value(QStringLiteral("results")).toArray();
    for (int i=0; i<results.size(); ++i) {
        if (!results[i].isObject())
            continue;

        QJsonObject geocode = results[i].toObject();
dogmaphobic's avatar
dogmaphobic committed
213

214 215 216 217
        QGeoAddress address;
        if (geocode.contains(QStringLiteral("formatted_address"))) {
            address.setText(geocode.value(QStringLiteral("formatted_address")).toString());
        }
dogmaphobic's avatar
dogmaphobic committed
218 219


220 221 222 223 224 225 226 227 228 229 230
        if (geocode.contains(QStringLiteral("address_components"))) {
            QJsonArray ac = geocode.value(QStringLiteral("address_components")).toArray();

            for (int j=0; j<ac.size(); ++j) {
                if (!ac[j].isObject())
                    continue;

                QJsonObject c = ac[j].toObject();
                if (!c.contains(QStringLiteral("types")))
                    continue;

231
                QSet<int> types = kMonger.json2QGCGeoCodeType(c[QStringLiteral("types")].toArray());
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
                QString long_name = c[QStringLiteral("long_name")].toString();
                QString short_name = c[QStringLiteral("short_name")].toString();
                if (types.contains(Country)) {
                    address.setCountry(long_name);
                    address.setCountryCode(short_name);
                } else if (types.contains(AdministrativeAreaLevel1)) {
                    address.setState(long_name);
                } else if (types.contains(AdministrativeAreaLevel2)) {
                    address.setCounty(long_name);
                } else if (types.contains(Locality)) {
                    address.setCity(long_name);
                } else if (types.contains(Sublocality)) {
                    address.setDistrict(long_name);
                } else if (types.contains(PostalCode)) {
                    address.setPostalCode(long_name);
                } else if (types.contains(StreetAddress) || types.contains(Route) || types.contains(Intersection)) {
                    address.setStreet(long_name);
                }
            }
        }

        QGeoCoordinate coordinate;
        QGeoRectangle boundingBox;
        if (geocode.contains(QStringLiteral("geometry"))) {
            QJsonObject geom = geocode.value(QStringLiteral("geometry")).toObject();
            if (geom.contains(QStringLiteral("location"))) {
                QJsonObject location = geom.value(QStringLiteral("location")).toObject();
                coordinate.setLatitude(location.value(QStringLiteral("lat")).toDouble());
                coordinate.setLongitude(location.value(QStringLiteral("lng")).toDouble());
            }
            if (geom.contains(QStringLiteral("bounds"))) {
                QJsonObject bounds = geom.value(QStringLiteral("bounds")).toObject();
                QJsonObject northeast = bounds.value(QStringLiteral("northeast")).toObject();
                QJsonObject southwest = bounds.value(QStringLiteral("southwest")).toObject();
                QGeoCoordinate topRight(northeast.value(QStringLiteral("lat")).toDouble(),
                                        northeast.value(QStringLiteral("lng")).toDouble());
                QGeoCoordinate bottomLeft(southwest.value(QStringLiteral("lat")).toDouble(),
                                          southwest.value(QStringLiteral("lng")).toDouble());
                boundingBox.setTopRight(topRight);
                boundingBox.setBottomLeft(bottomLeft);
            }
        }

        QGeoLocation location;
        location.setAddress(address);
        location.setCoordinate(coordinate);
        location.setBoundingBox(boundingBox);

        locations << location;
    }

    setLocations(locations);
    setFinished(true);

    m_reply->deleteLater();
    m_reply = 0;
}

290
void QGeoCodeReplyQGC::networkReplyError(QNetworkReply::NetworkError error)
291 292 293 294 295 296 297 298
{
    Q_UNUSED(error)
    if (!m_reply)
        return;
    setError(QGeoCodeReply::CommunicationError, m_reply->errorString());
    m_reply->deleteLater();
    m_reply = 0;
}