Пример #1
0
void GeolocationClientQt::positionUpdated(const QGeoPositionInfo &geoPosition)
{
    if (!geoPosition.isValid())
        return;

    QGeoCoordinate coord = geoPosition.coordinate();
    double latitude = coord.latitude();
    double longitude = coord.longitude();
    bool providesAltitude = (geoPosition.coordinate().type() == QGeoCoordinate::Coordinate3D);
    double altitude = coord.altitude();

    double accuracy = geoPosition.attribute(QGeoPositionInfo::HorizontalAccuracy);

    bool providesAltitudeAccuracy = geoPosition.hasAttribute(QGeoPositionInfo::VerticalAccuracy);
    double altitudeAccuracy = geoPosition.attribute(QGeoPositionInfo::VerticalAccuracy);

    bool providesHeading =  geoPosition.hasAttribute(QGeoPositionInfo::Direction);
    double heading = geoPosition.attribute(QGeoPositionInfo::Direction);

    bool providesSpeed = geoPosition.hasAttribute(QGeoPositionInfo::GroundSpeed);
    double speed = geoPosition.attribute(QGeoPositionInfo::GroundSpeed);

    double timeStampInSeconds = geoPosition.timestamp().toMSecsSinceEpoch() / 1000;

    m_lastPosition = GeolocationPosition::create(timeStampInSeconds, latitude, longitude,
                                                 accuracy, providesAltitude, altitude,
                                                 providesAltitudeAccuracy, altitudeAccuracy,
                                                 providesHeading, heading, providesSpeed, speed);

    WebCore::Page* page = QWebPagePrivate::core(m_page);
    page->geolocationController()->positionChanged(m_lastPosition.get());
}
Пример #2
0
void GpsLocation::newPosition(QGeoPositionInfo pos)
{
	int64_t lastTime = 0;
	QGeoCoordinate lastCoord;
	int nr = m_trackers.count();
	if (nr) {
		gpsTracker gt = m_trackers.last();
		lastCoord.setLatitude(gt.latitude.udeg / 1000000.0);
		lastCoord.setLongitude(gt.longitude.udeg / 1000000.0);
		lastTime = gt.when;
	}
	// if we are waiting for a position update or
	// if we have no record stored or if at least the configured minimum
	// time has passed or we moved at least the configured minimum distance
	int64_t delta = (int64_t)pos.timestamp().toTime_t() + gettimezoneoffset() - lastTime;
	if (!nr || waitingForPosition || delta > prefs.time_threshold ||
	    lastCoord.distanceTo(pos.coordinate()) > prefs.distance_threshold) {
		QString msg("received new position %1 after delta %2 threshold %3 (now %4 last %5)");
		status(qPrintable(msg.arg(pos.coordinate().toString()).arg(delta).arg(prefs.time_threshold).arg(pos.timestamp().toString()).arg(QDateTime().fromMSecsSinceEpoch(lastTime * 1000).toString())));
		waitingForPosition = false;
		acquiredPosition();
		gpsTracker gt;
		gt.when = pos.timestamp().toTime_t();
		gt.when += gettimezoneoffset(gt.when);
		gt.latitude.udeg = lrint(pos.coordinate().latitude() * 1000000);
		gt.longitude.udeg = lrint(pos.coordinate().longitude() * 1000000);
		addFixToStorage(gt);
		gpsTracker gtNew = m_trackers.last();
		qDebug() << "newest fix is now at" << QDateTime().fromMSecsSinceEpoch(gtNew.when - gettimezoneoffset(gtNew.when) * 1000).toString();
	}
}
Пример #3
0
void KTracks::on_acSelect_triggered()
{
   QModelIndexList selection = ui->tvTracks->selectionModel()->selectedRows();
   QAbstractItemModel *model = ui->tvTracks->model();

   if (!selection.isEmpty()) {
       QList<QGeoPositionInfo> trackList;
       trackList.clear();
       trackList = sql.selTrack(model->data(model->index(selection.at(0).row(),0)).toInt());

       ui->cpPlot->clearGraphs();
       ui->cpPlot->addGraph();

       QGeoPositionInfo tp;
       QVector<double> x;
       QVector<double> y;
       int cnt = trackList.count();
       x.resize(cnt);
       y.resize(cnt);

       //options
       int pType;
       if (ui->miAltitude->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Altitude [m]");
           pType = 1; }
       if (ui->miDistance->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Distance [m]");
           pType = 2; }
       if (ui->miSpeed->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Speed [m/s]");
           pType = 3; }
       ui->cpPlot->xAxis->setLabel("time [hh:mm:ss]");

       for (int i=0; i<cnt; i++) {
           tp = trackList.value(i);
           x[i] = tp.timestamp().toTime_t();
           switch (pType) {
             case 1: {
               y[i] = tp.coordinate().altitude();
               break; }
             case 2: {
               y[i] = tp.coordinate().distanceTo(trackList.value(0).coordinate());
               break; }
             case 3: {
               y[i] = tp.attribute(QGeoPositionInfo::GroundSpeed);
               break; }
           } //switch
       } //for to

       ui->cpPlot->graph(0)->setData(x,y);
       // set axes ranges, so we see all data:
       ui->cpPlot->xAxis->setRange(x[0],x[cnt-1]);
       qSort(y.begin(), y.end());
       ui->cpPlot->yAxis->setRange(y.first(),y.last());
       //repaint
       ui->cpPlot->replot();

   } //selection.isempty
}
Пример #4
0
void LocationTracker::positionUpdated(const QGeoPositionInfo& pos)
{

	m_latitude = pos.coordinate().latitude();
	m_longitude = pos.coordinate().longitude();

	emit dataChanged(pos);
}
void FoursquareVenueSelectionPage::positionUpdated(const QGeoPositionInfo &update)
{
	mDebug(__func__) 
		<< "Position lookup done, we're at "
		<< update.coordinate().latitude() << "," 
		<< update.coordinate().longitude() << ". ";
	m_geoinfo = update;
	m_here->setEnabled(true);
}
Пример #6
0
void GpsLocation::updateLocation(QGeoPositionInfo positionInfo)
{
    this->latitude = positionInfo.coordinate().latitude();
    this->longitude = positionInfo.coordinate().longitude();

    this->calculateXY();

    this->m_valid = true;

    emit(this->gpsLocationChanged(this));
}
Пример #7
0
void RouteMePositionInfo::onPositionUpdated(const QGeoPositionInfo &info)
{
    if (!info.isValid() || !info.coordinate().isValid())
        return;

    QGeoCoordinate coordinate = info.coordinate();
    m_currentCoordinate.setGeoCoordinate(coordinate);

    emit currentCoordinateAvailable();

    stopUpdates();
}
Пример #8
0
void LocationWatcher::positionUpdated(const QGeoPositionInfo &info)
{
    if (info.isValid()) {

        double latitude=info.coordinate().latitude();
        double longitude=info.coordinate().longitude();

        //QSqlDatabase db = openDB();
        profilemanager pm;
        // QSqlDatabase db = QSqlDatabase::database("/home/user/.local/share/data/QML/OfflineStorage/Databases/3e6ed8d4e46837c47b903b1e4ae85712.sqlite");

      if( !db.open() )
      {
        qFatal( "Failed to connect." );
      }
      if( db.open() )
      {      
          QSqlQuery query(db);
          double radius = getSetting("radius").toDouble();

          QString HereProfile="";
          //start looping through all areas
          query.exec("SELECT * FROM records");
          while(query.next()) {
              QString lat = query.value(0).toString();
              QString lon = query.value(1).toString();
              QString profile = query.value(2).toString();
              double lat1 = lat.toDouble();
              double lon1 = lon.toDouble();
              double distance=cut(lat1,lon1,latitude,longitude);
              if(distance<radius){
                    qDebug() << "to vrikame: " << lat<<lon<<profile<<distance<<radius;
                    HereProfile=profile;
                    break;
              }else{
                  HereProfile="";
              }
          }//telos loop perioxes
          if(HereProfile!="")
              pm.setProfile(HereProfile);
          else {
              query.exec("SELECT value FROM settings WHERE key='previousProfile'");
              query.first();
              QString previous=query.value(0).toString();
              qDebug()<<previous;
              pm.setProfile(previous);
          }
      }
    }//telos isvalid

}
Пример #9
0
void
MapWidget::positionUpdated(const QGeoPositionInfo & info)
{
    follow->show();
    coord = QPointF(info.coordinate().latitude(), info.coordinate().longitude());
    positionMarker->setVisible(true);
    positionMarker->setCoordinate(QPointF(coord.y(), coord.x()));

    if (!follow->isChecked())
        return ;

    if (plugin && plugin->rect().contains(coord))
        centerView(coord, 17);
}
Пример #10
0
void tst_PositionPlugin::getUpdates()
{
    QGeoPositionInfoSource *src = QGeoPositionInfoSource::createSource("test.source", 0);
    src->setUpdateInterval(1000);

    QSignalSpy spy(src, SIGNAL(positionUpdated(QGeoPositionInfo)));
    src->startUpdates();
    QTest::qWait(1500);
    QCOMPARE(spy.count(), 1);
    QCOMPARE(spy[0].size(), 1);

    QGeoPositionInfo info = qvariant_cast<QGeoPositionInfo>(spy[0][0]);
    QCOMPARE(info.coordinate().latitude(), 0.1);
    QCOMPARE(info.coordinate().longitude(), 0.1);
}
Пример #11
0
//! [3]
void AppModel::positionUpdated(QGeoPositionInfo gpsPos)
{
    d->coord = gpsPos.coordinate();

    if (!(d->useGps))
        return;

    QString latitude, longitude;
    longitude.setNum(d->coord.longitude());
    latitude.setNum(d->coord.latitude());
//! [3]
    QUrl url("http://maps.google.com/maps/geo");
    QUrlQuery query;
    query.addQueryItem("q", latitude + "," + longitude);
    query.addQueryItem("output", "xml");
    url.setQuery(query);

    QNetworkReply *rep = d->nam->get(QNetworkRequest(url));
    // connect up the signal right away
    d->geoReplyMapper->setMapping(rep, rep);
    connect(rep, SIGNAL(finished()),
            d->geoReplyMapper, SLOT(map()));
    // it might have finished though while we were connecting it
    // if so, pass it straight on
    if (rep->isFinished())
        this->handleGeoNetworkData(rep);
}
Пример #12
0
//! [3]
void AppModel::positionUpdated(QGeoPositionInfo gpsPos)
{
    d->coord = gpsPos.coordinate();

    if (!(d->useGps))
        return;

    QString latitude, longitude;
    longitude.setNum(d->coord.longitude());
    latitude.setNum(d->coord.latitude());
//! [3]

    //don't update more often then once a minute
    //to keep load on server low
    if (d->throttle.isValid() && d->throttle.elapsed() < 1000*10 ) {
        return;
    }
    d->throttle.restart();

    QUrl url("http://api.openweathermap.org/data/2.5/weather");
    QUrlQuery query;
    query.addQueryItem("lat", latitude);
    query.addQueryItem("lon", longitude);
    query.addQueryItem("mode", "json");
    url.setQuery(query);

    QNetworkReply *rep = d->nam->get(QNetworkRequest(url));
    // connect up the signal right away
    d->geoReplyMapper->setMapping(rep, rep);
    connect(rep, SIGNAL(finished()),
            d->geoReplyMapper, SLOT(map()));
}
Пример #13
0
void MainWindow::positionUpdated(QGeoPositionInfo geoPositionInfo)
{
    if (geoPositionInfo.isValid())
    {
        // Stop regular position updates, because a valid position has been
        // obtained
        locationDataSource->stopUpdates();

        // Get the current location as latitude and longitude
        QGeoCoordinate geoCoordinate = geoPositionInfo.coordinate();
        qreal latitude = geoCoordinate.latitude();
        qreal longitude = geoCoordinate.longitude();



        QString string1;
        QString string2;
     //   QChar c = 'g';

        //build the string for latitude-longitude
        string1.setNum(latitude);
        this->latlng.append(string1);
        string2.setNum(longitude);
        this->latlng.append(",");
        this->latlng.append(string2);


        //send the location request
        sendRequest();
    }
}
void
QTMLocationProvider::positionUpdated(const QGeoPositionInfo &geoPosition)
{
    if (!geoPosition.isValid()) {
        NS_WARNING("Invalida geoposition received");
        return;
    }

    QGeoCoordinate coord = geoPosition.coordinate();
    double latitude = coord.latitude();
    double longitude = coord.longitude();
    double altitude = coord.altitude();
    double accuracy = geoPosition.attribute(QGeoPositionInfo::HorizontalAccuracy);
    double altitudeAccuracy = geoPosition.attribute(QGeoPositionInfo::VerticalAccuracy);
    double heading = geoPosition.attribute(QGeoPositionInfo::Direction);

    bool providesSpeed = geoPosition.hasAttribute(QGeoPositionInfo::GroundSpeed);
    double speed = geoPosition.attribute(QGeoPositionInfo::GroundSpeed);

    nsRefPtr<nsGeoPosition> p =
        new nsGeoPosition(latitude, longitude,
                          altitude, accuracy,
                          altitudeAccuracy, heading,
                          speed, geoPosition.timestamp().toTime_t());
    if (mCallback) {
        mCallback->Update(p);
    }
}
Пример #15
0
void QgsQuickPositionKit::onPositionUpdated( const QGeoPositionInfo &info )
{
  bool hasPosition = info.coordinate().isValid();
  if ( hasPosition != mHasPosition )
  {
    mHasPosition = hasPosition;
    emit hasPositionChanged();
  }

  // Calculate position
  QgsPoint position = QgsPoint(
                        info.coordinate().longitude(),
                        info.coordinate().latitude(),
                        info.coordinate().altitude() ); // can be NaN

  if ( position != mPosition )
  {
    mPosition = position;
    emit positionChanged();
  }
  // calculate accuracy
  double accuracy;
  if ( info.hasAttribute( QGeoPositionInfo::HorizontalAccuracy ) )
    accuracy = info.attribute( QGeoPositionInfo::HorizontalAccuracy );
  else
    accuracy = -1;
  if ( !qgsDoubleNear( accuracy, mAccuracy ) )
  {
    mAccuracy = accuracy;
    emit accuracyChanged();
  }

  // calculate direction
  double direction;
  if ( info.hasAttribute( QGeoPositionInfo::Direction ) )
    direction = info.attribute( QGeoPositionInfo::Direction );
  else
    direction = -1;
  if ( !qgsDoubleNear( direction, mDirection ) )
  {
    mDirection = direction;
    emit directionChanged();
  }

  // recalculate projected/screen variables
  onMapSettingsUpdated();
}
Пример #16
0
void TrackingService::sendMark()
{
    qDebug() << "sendMark";
    QGeoPositionInfo info = m_locationManager->getInfo();
    if (info.isValid())
    {
        m_dataMark->setLatitude(info.coordinate().latitude());
        m_dataMark->setLongitude(info.coordinate().longitude());
        m_dataMark->setTime();
        m_writeTagQuery->doRequest();
    }
    else
    {
        qDebug() << "invalid geo info, waitin and trying again";
        QTimer::singleShot(m_period * 1000, this, SLOT(sendMark()));
    }
}
Пример #17
0
//! [3]
void AppModel::positionUpdated(QGeoPositionInfo gpsPos)
{
    d->coord = gpsPos.coordinate();

    if (!(d->useGps))
        return;

    queryCity();
}
void QGeoAreaMonitorSimulator::positionUpdated(const QGeoPositionInfo &info)
{
    qreal distance = info.coordinate().distanceTo(center());

    if (distance <= QGeoAreaMonitor::radius()) {
        if(!insideArea)
            emit areaEntered(info);
        insideArea = true;
    } else if (insideArea) {
        emit areaExited(info);
        insideArea = false;
    }
}
Пример #19
0
// Testcase to check that values are passed correctly
void TestQGeoPositionInfoSource::updateValues()
{
    CHECK_SOURCE_VALID;

    QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)));
    m_source->startUpdates();
    QTRY_VERIFY_WITH_TIMEOUT(!spy.isEmpty(), 2000);
    QList<QVariant> list = spy.takeFirst();
    QGeoPositionInfo info;
    info = list.at(0).value<QGeoPositionInfo>();
    QCOMPARE(qFuzzyCompare(info.coordinate().latitude(), 21), TRUE );
    QCOMPARE(qFuzzyCompare(info.coordinate().longitude(), 31), TRUE );
    QCOMPARE(qFuzzyCompare(info.coordinate().altitude(), 5.1), TRUE );
    QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::HorizontalAccuracy), 8), TRUE );
    QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::VerticalAccuracy), 9), TRUE );
    QDateTime dateTime;
    dateTime.setTime_t(99998);
    // there is some rounding difference impacting at sec level
    // hence don't compare directly
    QCOMPARE(info.timestamp().date(),dateTime.date());
    QCOMPARE(info.timestamp().time().hour(),dateTime.time().hour());
}
Пример #20
0
void GPSDisplay::positionUpdated(const QGeoPositionInfo& info)
{
    Q_UNUSED(info);

    gps_updated = true;
    tracking_lost = false;
    has_valid_position = true;

    bool ok = false;
    calcLatestGPSCoord(ok);
    if (ok)
    {
        emit mapPositionUpdated(latest_gps_coord, latest_gps_coord_accuracy);
        emit latLonUpdated(
            info.coordinate().latitude(),
            info.coordinate().longitude(),
            (info.coordinate().type() == QGeoCoordinate::Coordinate3D) ? info.coordinate().altitude() : -9999,
            latest_gps_coord_accuracy
        );
    }

    updateMapWidget();
}
Пример #21
0
int CLbsPositionLogger::Write(const QGeoPositionInfo &info)
{
    int nRet = 0;

    QString szContext;
    szContext = QString::number(info.timestamp().toUTC().toTime_t()) + ","
            + QString::number(info.coordinate().latitude()) + ","
            + QString::number(info.coordinate().longitude()) + ",";
    if(!qIsNaN(info.coordinate().altitude()))
        szContext += QString::number(info.coordinate().altitude());
    szContext += ",";
    if(info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy))
        szContext += QString::number(info.attribute(QGeoPositionInfo::HorizontalAccuracy));
    szContext += ",";
    if(info.hasAttribute(QGeoPositionInfo::Direction))
        szContext += QString::number(info.attribute(QGeoPositionInfo::Direction));
    szContext += ",";
    if(info.hasAttribute(QGeoPositionInfo::GroundSpeed))
        szContext += QString::number(info.attribute(QGeoPositionInfo::GroundSpeed));
    szContext += "\n";
    m_logFile.write(szContext.toStdString().c_str(), szContext.length());
    return nRet;
}
Пример #22
0
void GpsPosition::positionUpdated(QGeoPositionInfo info)
{
    double latitude, longitude;
    //qDebug() << "gps info " << info;
    QGeoCoordinate coord = info.coordinate();
    if (coord.isValid()){
        longitude = coord.longitude();
        latitude = coord.latitude();
        qDebug() << "lon = " << longitude << ", lat = " << latitude;
        if (_isUpdated){
            _location->stopUpdates();
            _isUpdated = false;
        }
        emit findCoord(latitude, longitude);

        /* set timer */
        startTimer();
    }
}
Пример #23
0
void GPSWidget::positionUpdated(QGeoPositionInfo geoPositionInfo)
{
    //qWarning("positionUpdated");
    if (geoPositionInfo.isValid())
    {
        // Stop regular position updates, because a valid position has been
        // obtained
        locationDataSource->stopUpdates();

        // Get the current location as latitude and longitude
        geoCoordinate_ = geoPositionInfo.coordinate();


        emit gpsData(geoCoordinate_);

        locationDataSource->startUpdates();// chamówa

    }
}
Пример #24
0
void
Loco::NewPosition (const QGeoPositionInfo & here)
{
  static QGeoCoordinate old;
  QGeoCoordinate coord = here.coordinate();
  QString newPlace = coord.toString();
  qreal dist = old.distanceTo (coord);
  qreal azi = old.azimuthTo (coord);
  mainUi.displayMap->SetCourseAngle (azi);
  QString directions = QString (" %1 km head %2 (%3)")
                       .arg (dist/1000.0)
                       .arg (CompassDir(azi))
                       .arg (azi);
  old = coord;
  lastLocation = coord;
  QDateTime now = QDateTime::currentDateTime();
  dist = coord.distanceTo (destination);
  qreal destDist = coord.distanceTo (destination);
  qreal etaSecs = (destDist / locator->MoveStep()) * (locator->Interval()/1000.0);
  mainUi.destination->setText (tr("going %6 m %4 (%5) to %1 \n"
                        "at %2 \n"
                        "with %3 km left ETA %7 secs")
                               .arg (destName)
                               .arg (destination.toString())
                               .arg (qRound(dist/1000.0))
                               .arg (CompassDir (azi))
                               .arg (azi)
                               .arg (locator->MoveStep())
                               .arg (etaSecs, 10, 'g',4));
  QString stats ("Cache: Hits %1 Misses %2");
  mainUi.statLabel->setText (stats
                     .arg (mainUi.displayMap->CacheHits())
                     .arg (mainUi.displayMap->CacheMisses()));

  if (destDist < qreal (normalStep * 5)) {
    steppingNormal = false;
    locator->SetMoveStep (shortStep);
  } else {
    steppingNormal = true;
    locator->SetMoveStep (normalStep);
  }
}
Пример #25
0
void LocationData::onPositionChanged(const QGeoPositionInfo& info)
{
    emit positionChanged(info);
    if (info.isValid())
    {
        const QGeoCoordinate& c = info.coordinate();
        if (c.isValid())
        {
            double lat = c.latitude();
            double lon = c.longitude();
            double alt = c.altitude();
            //qDebug() << "LocationData::onPositionChanged()" << lat << lon << alt;
            if ((latitude != lat) || (longitude != lon))
            {
                latitude  = lat;
                mask |= LATMASK;
                longitude = lon;
                mask |= LONMASK;
            }
            if (altitude != alt)
            {
                altitude = alt;
                mask |= ALTMASK;
            }
            emit positionChanged(lat,lon,alt);
        }
        if (info.hasAttribute(QGeoPositionInfo::GroundSpeed))
        {
            double s = info.attribute(QGeoPositionInfo::GroundSpeed);
            emit speedChanged(s);
        }
        if (info.hasAttribute(QGeoPositionInfo::Direction))
        {
            double c = info.attribute(QGeoPositionInfo::Direction);
            emit courseChanged(c);
        }
    }
}
Пример #26
0
void JSKitGeolocation::handlePosition(const QGeoPositionInfo &pos)
{
    qCDebug(l) << "got position at" << pos.timestamp() << "type" << pos.coordinate().type();

    if (_watches.empty()) {
        qCWarning(l) << "got position update but no one is watching";
        _source->stopUpdates(); // Just in case.
        return;
    }

    QJSValue obj = buildPositionObject(pos);

    for (auto it = _watches.begin(); it != _watches.end(); /*no adv*/) {
        invokeCallback(it->successCallback, obj);

        if (it->once) {
            it = _watches.erase(it);
        } else {
            it->timer.restart();
            ++it;
        }
    }
}
Пример #27
0
void ClientApplication::positionUpdated(const QGeoPositionInfo &info)
{
    textEdit->append(QString("Position updated: Date/time = %1, Coordinate = %2").arg(info.timestamp().toString()).arg(info.coordinate().toString()));
}
Пример #28
0
void QDeclarativePosition::setPosition(const QGeoPositionInfo &info)
{
    // timestamp
    const QDateTime pTimestamp = m_info.timestamp();
    const QDateTime timestamp = info.timestamp();
    bool emitTimestampChanged = pTimestamp != timestamp;

    // coordinate
    const QGeoCoordinate pCoordinate = m_info.coordinate();
    const QGeoCoordinate coordinate = info.coordinate();
    bool emitCoordinateChanged = pCoordinate != coordinate;
    bool emitLatitudeValidChanged = exclusiveNaN(pCoordinate.latitude(), coordinate.latitude());
    bool emitLongitudeValidChanged = exclusiveNaN(pCoordinate.longitude(), coordinate.longitude());
    bool emitAltitudeValidChanged = exclusiveNaN(pCoordinate.altitude(), coordinate.altitude());

    // direction
    const qreal pDirection = m_info.attribute(QGeoPositionInfo::Direction);
    const qreal direction = info.attribute(QGeoPositionInfo::Direction);
    bool emitDirectionChanged = !equalOrNaN(pDirection, direction);
    bool emitDirectionValidChanged = exclusiveNaN(pDirection, direction);

    // ground speed
    const qreal pSpeed = m_info.attribute(QGeoPositionInfo::GroundSpeed);
    const qreal speed = info.attribute(QGeoPositionInfo::GroundSpeed);
    bool emitSpeedChanged = !equalOrNaN(pSpeed, speed);
    bool emitSpeedValidChanged = exclusiveNaN(pSpeed, speed);

    // vertical speed
    const qreal pVerticalSpeed = m_info.attribute(QGeoPositionInfo::VerticalSpeed);
    const qreal verticalSpeed = info.attribute(QGeoPositionInfo::VerticalSpeed);
    bool emitVerticalSpeedChanged = !equalOrNaN(pVerticalSpeed, verticalSpeed);
    bool emitVerticalSpeedValidChanged = exclusiveNaN(pVerticalSpeed, verticalSpeed);

    // magnetic variation
    const qreal pMagneticVariation = m_info.attribute(QGeoPositionInfo::MagneticVariation);
    const qreal magneticVariation = info.attribute(QGeoPositionInfo::MagneticVariation);
    bool emitMagneticVariationChanged = !equalOrNaN(pMagneticVariation, magneticVariation);
    bool emitMagneticVariationValidChanged = exclusiveNaN(pMagneticVariation, magneticVariation);

    // horizontal accuracy
    const qreal pHorizontalAccuracy = m_info.attribute(QGeoPositionInfo::HorizontalAccuracy);
    const qreal horizontalAccuracy = info.attribute(QGeoPositionInfo::HorizontalAccuracy);
    bool emitHorizontalAccuracyChanged = !equalOrNaN(pHorizontalAccuracy, horizontalAccuracy);
    bool emitHorizontalAccuracyValidChanged = exclusiveNaN(pHorizontalAccuracy, horizontalAccuracy);

    // vertical accuracy
    const qreal pVerticalAccuracy = m_info.attribute(QGeoPositionInfo::VerticalAccuracy);
    const qreal verticalAccuracy = info.attribute(QGeoPositionInfo::VerticalAccuracy);
    bool emitVerticalAccuracyChanged = !equalOrNaN(pVerticalAccuracy, verticalAccuracy);
    bool emitVerticalAccuracyValidChanged = exclusiveNaN(pVerticalAccuracy, verticalAccuracy);

    m_info = info;

    if (emitTimestampChanged)
        emit timestampChanged();
    if (emitCoordinateChanged)
        emit coordinateChanged();
    if (emitLatitudeValidChanged)
        emit latitudeValidChanged();
    if (emitLongitudeValidChanged)
        emit longitudeValidChanged();
    if (emitAltitudeValidChanged)
        emit altitudeValidChanged();
    if (emitDirectionChanged)
        emit directionChanged();
    if (emitDirectionValidChanged)
        emit directionValidChanged();
    if (emitSpeedChanged)
        emit speedChanged();
    if (emitSpeedValidChanged)
        emit speedValidChanged();
    if (emitVerticalSpeedChanged)
        emit verticalSpeedChanged();
    if (emitVerticalSpeedValidChanged)
        emit verticalSpeedValidChanged();
    if (emitHorizontalAccuracyChanged)
        emit horizontalAccuracyChanged();
    if (emitHorizontalAccuracyValidChanged)
        emit horizontalAccuracyValidChanged();
    if (emitVerticalAccuracyChanged)
        emit verticalAccuracyChanged();
    if (emitVerticalAccuracyValidChanged)
        emit verticalAccuracyValidChanged();
    if (emitMagneticVariationChanged)
        emit magneticVariationChanged();
    if (emitMagneticVariationValidChanged)
        emit magneticVariationValidChanged();
}
Пример #29
0
void TestQGeoPositionInfoSource::lastKnownPosition()
{
    CHECK_SOURCE_VALID;
    QFETCH(int, positioningMethod);
    QFETCH(bool, lastKnownPositionArgument);
    QFETCH(bool, positionValid);

#if defined(Q_OS_SYMBIAN)
    QSKIP("Real GPS not suitable for autotesting, skipping the test.", SkipAll);
#endif
    QGeoPositionInfoSource::PositioningMethods method
            = static_cast<QGeoPositionInfoSource::PositioningMethods>(positioningMethod);

    if ((m_source->supportedPositioningMethods() & method) == 0)
        QSKIP("Not a supported positioning method for this position source", SkipSingle);

    m_source->setPreferredPositioningMethods(method);

    QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)));
    QSignalSpy timeout(m_source, SIGNAL(updateTimeout()));
    int time_out = 7000;
    m_source->setUpdateInterval(time_out);
    m_source->startUpdates();

    // Use QEventLoop instead of qWait() to ensure we stop as soon as a
    // position is emitted (otherwise the lastKnownPosition() may have
    // changed by the time it is checked)
    QEventLoop loop;
    QTimer timer;
    timer.setInterval(9500);
    connect(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)),
            &loop, SLOT(quit()));
    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    timer.start();
    loop.exec();

    EXPECT_FAIL_WINCE_SEE_MOBILITY_337_ABORT;

    QVERIFY((spy.count() > 0) && (timeout.count() == 0));

    QList<QVariant> list = spy.takeFirst();
    QGeoPositionInfo info;
    info = list.at(0).value<QGeoPositionInfo>();
    QGeoPositionInfo lastPositioninfo;
    lastPositioninfo = m_source->lastKnownPosition(lastKnownPositionArgument);
 
    QCOMPARE(lastPositioninfo.isValid(), positionValid);

    if (positionValid) {
        QCOMPARE(info.coordinate(), lastPositioninfo.coordinate());
        QCOMPARE(info.timestamp(), lastPositioninfo.timestamp());

        QCOMPARE(info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy),
                 lastPositioninfo.hasAttribute(QGeoPositionInfo::HorizontalAccuracy));

        if (info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy)) {
            bool isNaN1 =  qIsNaN(info.attribute(QGeoPositionInfo::HorizontalAccuracy));
            bool isNaN2 =  qIsNaN(lastPositioninfo.attribute(QGeoPositionInfo::HorizontalAccuracy));
            QCOMPARE(isNaN1, isNaN2);
            if (!isNaN1) {
                QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::HorizontalAccuracy),
                                       lastPositioninfo.attribute(QGeoPositionInfo::HorizontalAccuracy)), TRUE);
            }
        }

        QCOMPARE(info.hasAttribute(QGeoPositionInfo::VerticalAccuracy),
                 lastPositioninfo.hasAttribute(QGeoPositionInfo::VerticalAccuracy));

        if (info.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) {
            bool isNaN1 =  qIsNaN(info.attribute(QGeoPositionInfo::VerticalAccuracy));
            bool isNaN2 =  qIsNaN(lastPositioninfo.attribute(QGeoPositionInfo::VerticalAccuracy));
            QCOMPARE(isNaN1, isNaN2);
            if (!isNaN1) {
                QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::VerticalAccuracy),
                                       lastPositioninfo.attribute(QGeoPositionInfo::VerticalAccuracy)), TRUE);
            }
        }
    }

    m_source->stopUpdates();
}
Пример #30
0
void TRMainWindow::newLocationInfoReceived(const QGeoPositionInfo positionInfo)
{
    QGeoCoordinate currentCoords = positionInfo.coordinate();
    if(m_lastKnownPosition || !(currentCoords == *m_lastKnownPosition))
    {
        // We need to write to the file, let's initialize it
        if(m_outputKMLFile == NULL)
        {
            // File initialization
            QString timeStamp = positionInfo.timestamp().toString(Qt::ISODate);
            QString fileTimeStamp = positionInfo.timestamp().toString("hhmmssddMMyy");
            m_outputKMLFile = new QFile("c://Data//trackroute_"+fileTimeStamp+".kml");
            m_outputKMLFile->open(QIODevice::WriteOnly | QIODevice::Text);
            // File writer initialization
            if(m_kmlFileWriter == NULL)
            {
                // Header
                m_kmlFileWriter = new QXmlStreamWriter(m_outputKMLFile);
                m_kmlFileWriter->writeStartDocument();
                m_kmlFileWriter->writeNamespace("http://www.opengis.net/kml/2.2","kml");
                // Document
                m_kmlFileWriter->writeStartElement("Document");
                m_kmlFileWriter->writeTextElement("name","TrackRoute Path File");
                m_kmlFileWriter->writeTextElement("description","Pathfile generated by Trackroute on: "+timeStamp);
                // Style
                m_kmlFileWriter->writeStartElement("Style");
                m_kmlFileWriter->writeAttribute("id","yellowLineGreenPoly");
                // LineStyle
                m_kmlFileWriter->writeStartElement("LineStyle");
                m_kmlFileWriter->writeTextElement("color","7f00ffff");
                m_kmlFileWriter->writeTextElement("width","4");
                m_kmlFileWriter->writeEndElement();
                // PolyStyle
                m_kmlFileWriter->writeStartElement("PolyStyle");
                m_kmlFileWriter->writeTextElement("color","7f00ff00");
                m_kmlFileWriter->writeEndElement();
                // End Style
                m_kmlFileWriter->writeEndElement();
                // Placemark
                m_kmlFileWriter->writeStartElement("Placemark");
                m_kmlFileWriter->writeTextElement("name","TrackRoute Path "+timeStamp);
                m_kmlFileWriter->writeTextElement("description","Path generated by Trackroute on: "+timeStamp);
                m_kmlFileWriter->writeTextElement("styleUrl","#yellowLineGreenPoly");
                // LineString
                m_kmlFileWriter->writeStartElement("LineString");
                m_kmlFileWriter->writeTextElement("extrude","1");
                m_kmlFileWriter->writeTextElement("tessellate","1");
                m_kmlFileWriter->writeTextElement("altitudeMode","absolute");
                // Coordinates
                m_kmlFileWriter->writeStartElement("coordinates");
            }
        }

        // Update data
        m_numberOfUpdatesReceived++;
        m_currentSpeed = positionInfo.attribute(QGeoPositionInfo::GroundSpeed);
        m_currentSpeed = m_currentSpeed > 0 ? m_currentSpeed:0;
        m_totalSpeed += m_currentSpeed;
        m_averageSpeed = m_totalSpeed / m_numberOfUpdatesReceived;
        QString coordString = currentCoords.toString();

        // Update UI
        ui->latLonDataLabel->setText(coordString.left(coordString.lastIndexOf(",")));
        ui->altitudeDataLabel->setText(QString::number(currentCoords.altitude())+" m");
        ui->wptNumberDataLabel->setText(QString::number(m_numberOfUpdatesReceived));
        ui->currentSpdDataLabel->setText(QString::number(m_currentSpeed)+" km/h");
        ui->averageSpdDataLabel->setText(QString::number(m_averageSpeed)+" km/h");

        // Write to the KML file
        QString locationData = QString::number(currentCoords.latitude()).append(",").append(QString::number(currentCoords.longitude()))
                               .append(",").append(QString::number(currentCoords.altitude())).append(" ");
        m_kmlFileWriter->writeCharacters(locationData);
        m_outputKMLFile->flush();
    }
    m_lastKnownPosition = &currentCoords;
}