void QgsPointSample::addSamplePoints( QgsFeature& inputFeature, QgsVectorFileWriter& writer, int nPoints, double minDistance )
{
  if ( !inputFeature.constGeometry() )
    return;

  const QgsGeometry* geom = inputFeature.constGeometry();
  QgsRectangle geomRect = geom->boundingBox();
  if ( geomRect.isEmpty() )
  {
    return;
  }

  QgsSpatialIndex sIndex; //to check minimum distance
  QMap< QgsFeatureId, QgsPoint > pointMapForFeature;

  int nIterations = 0;
  int maxIterations = nPoints * 200;
  int points = 0;

  double randX = 0;
  double randY = 0;

  while ( nIterations < maxIterations && points < nPoints )
  {
    randX = (( double )mt_rand() / MD_RAND_MAX ) * geomRect.width() + geomRect.xMinimum();
    randY = (( double )mt_rand() / MD_RAND_MAX ) * geomRect.height() + geomRect.yMinimum();
    QgsPoint randPoint( randX, randY );
    QgsGeometry* ptGeom = QgsGeometry::fromPoint( randPoint );
    if ( ptGeom->within( geom ) && checkMinDistance( randPoint, sIndex, minDistance, pointMapForFeature ) )
    {
      //add feature to writer
      QgsFeature f( mNCreatedPoints );
      f.setAttribute( "id", mNCreatedPoints + 1 );
      f.setAttribute( "station_id", points + 1 );
      f.setAttribute( "stratum_id", inputFeature.id() );
      f.setGeometry( ptGeom );
      writer.addFeature( f );
      sIndex.insertFeature( f );
      pointMapForFeature.insert( mNCreatedPoints, randPoint );
      ++points;
      ++mNCreatedPoints;
    }
    else
    {
      delete ptGeom;
    }
    ++nIterations;
  }
}
Example #2
0
void QgsGeometryAnalyzer::convexFeature( QgsFeature& f, int nProcessedFeatures, QgsGeometry** dissolveGeometry )
{
  if ( !f.constGeometry() )
  {
    return;
  }

  const QgsGeometry* featureGeometry = f.constGeometry();
  QgsGeometry* tmpGeometry = 0;
  QgsGeometry* convexGeometry = 0;

  convexGeometry = featureGeometry->convexHull();

  if ( nProcessedFeatures == 0 )
  {
    *dissolveGeometry = convexGeometry;
  }
  else
  {
    tmpGeometry = *dissolveGeometry;
    *dissolveGeometry = ( *dissolveGeometry )->combine( convexGeometry );
    delete tmpGeometry;
    delete convexGeometry;
  }
}
Example #3
0
bool QgsVectorLayerImport::addFeature( QgsFeature& feat )
{
  QgsAttributes attrs = feat.attributes();

  QgsFeature newFeat;
  if ( feat.constGeometry() )
    newFeat.setGeometry( *feat.constGeometry() );

  newFeat.initAttributes( mAttributeCount );

  for ( int i = 0; i < attrs.count(); ++i )
  {
    // add only mapped attributes (un-mapped ones will not be present in the
    // destination layer)
    int dstIdx = mOldToNewAttrIdx.value( i, -1 );
    if ( dstIdx < 0 )
      continue;

    QgsDebugMsgLevel( QString( "moving field from pos %1 to %2" ).arg( i ).arg( dstIdx ), 3 );
    newFeat.setAttribute( dstIdx, attrs.at( i ) );
  }

  mFeatureBuffer.append( newFeat );

  if ( mFeatureBuffer.count() >= FEATURE_BUFFER_SIZE )
  {
    return flushBuffer();
  }

  return true;
}
Example #4
0
bool QgsSpatialIndex::featureInfo( const QgsFeature& f, SpatialIndex::Region& r, QgsFeatureId &id )
{
  if ( !f.constGeometry() )
    return false;

  QgsGeometry g( *f.constGeometry() );

  id = f.id();
  r = rectToRegion( g.boundingBox() );
  return true;
}
bool QgsPointDisplacementRenderer::renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer, bool selected, bool drawVertexMarker )
{
  Q_UNUSED( drawVertexMarker );
  Q_UNUSED( context );
  Q_UNUSED( layer );

  //check, if there is already a point at that position
  if ( !feature.constGeometry() )
    return false;

  QgsSymbolV2* symbol = firstSymbolForFeature( mRenderer, feature, context );

  //if the feature has no symbol (eg, no matching rule in a rule-based renderer), skip it
  if ( !symbol )
    return false;

  //point position in screen coords
  const QgsGeometry* geom = feature.constGeometry();
  QGis::WkbType geomType = geom->wkbType();
  if ( geomType != QGis::WKBPoint && geomType != QGis::WKBPoint25D )
  {
    //can only render point type
    return false;
  }

  if ( selected )
    mSelectedFeatures.insert( feature.id() );

  double searchDistance = mTolerance * QgsSymbolLayerV2Utils::mapUnitScaleFactor( context, mToleranceUnit, mToleranceMapUnitScale );
  QList<QgsFeatureId> intersectList = mSpatialIndex->intersects( searchRect( feature.constGeometry()->asPoint(), searchDistance ) );
  if ( intersectList.empty() )
  {
    mSpatialIndex->insertFeature( feature );
    // create new group
    DisplacementGroup newGroup;
    newGroup.insert( feature.id(), qMakePair( feature, symbol ) );
    mDisplacementGroups.push_back( newGroup );
    // add to group index
    mGroupIndex.insert( feature.id(), mDisplacementGroups.count() - 1 );
    return true;
  }

  //go through all the displacement group maps and search an entry where the id equals the result of the spatial search
  QgsFeatureId existingEntry = intersectList.at( 0 );

  int groupIdx = mGroupIndex[ existingEntry ];
  DisplacementGroup& group = mDisplacementGroups[groupIdx];

  // add to a group
  group.insert( feature.id(), qMakePair( feature, symbol ) );
  // add to group index
  mGroupIndex.insert( feature.id(), groupIdx );
  return true;
}
Example #6
0
void QgsMapToolNodeTool::createTopologyRubberBands()
{
  QgsVectorLayer* vlayer = mSelectedFeature->vlayer();

  Q_FOREACH ( const QgsVertexEntry* vertexEntry, mSelectedFeature->vertexMap() )
  {
    if ( !vertexEntry->isSelected() )
    {
      continue;
    }

    // Snap vertex
    QMultiMap<double, QgsSnappingResult> snapResults;
    vlayer->snapWithContext( vertexEntry->pointV1(), ZERO_TOLERANCE, snapResults, QgsSnapper::SnapToVertex );
    Q_FOREACH ( const QgsSnappingResult& snapResult, snapResults )
    {
      // Get geometry of snapped feature
      QgsFeatureId snapFeatureId = snapResult.snappedAtGeometry;
      QgsFeature feature;
      if ( !vlayer->getFeatures( QgsFeatureRequest( snapFeatureId ).setSubsetOfAttributes( QgsAttributeList() ) ).nextFeature( feature ) )
      {
        continue;
      }
      // Get VertexId of snapped vertex
      QgsVertexId vid;
      if ( !feature.constGeometry()->vertexIdFromVertexNr( snapResult.snappedVertexNr, vid ) )
      {
        continue;
      }
      // Add rubberband if not already added
      if ( !mMoveRubberBands.contains( snapFeatureId ) )
      {
        QgsGeometryRubberBand* rb = new QgsGeometryRubberBand( mCanvas, feature.constGeometry()->type() );
        QSettings settings;
        QColor color(
          settings.value( "/qgis/digitizing/line_color_red", 255 ).toInt(),
          settings.value( "/qgis/digitizing/line_color_green", 0 ).toInt(),
          settings.value( "/qgis/digitizing/line_color_blue", 0 ).toInt() );
        double myAlpha = settings.value( "/qgis/digitizing/line_color_alpha", 30 ).toInt() / 255.0 ;
        color.setAlphaF( myAlpha );
        rb->setOutlineColor( color );
        rb->setBrushStyle( Qt::NoBrush );
        rb->setOutlineWidth( settings.value( "/qgis/digitizing/line_width", 1 ).toInt() );
        QgsAbstractGeometryV2* rbGeom = feature.constGeometry()->geometry()->clone();
        if ( mCanvas->mapSettings().layerTransform( vlayer ) )
          rbGeom->transform( *mCanvas->mapSettings().layerTransform( vlayer ) );
        rb->setGeometry( rbGeom );
        mMoveRubberBands.insert( snapFeatureId, rb );
      }
      // Add to list of vertices to be moved
      mMoveVertices[snapFeatureId].append( qMakePair( vid, toMapCoordinates( vlayer, feature.constGeometry()->geometry()->vertexAt( vid ) ) ) );
    }
  }
Example #7
0
void QgsVectorLayerRenderer::drawRendererV2( QgsFeatureIterator& fit )
{
  QgsFeature fet;
  while ( fit.nextFeature( fet ) )
  {
    try
    {
      if ( !fet.constGeometry() )
        continue; // skip features without geometry

      if ( mContext.renderingStopped() )
      {
        QgsDebugMsg( QString( "Drawing of vector layer %1 cancelled." ).arg( layerID() ) );
        break;
      }

      bool sel = mContext.showSelection() && mSelectedFeatureIds.contains( fet.id() );
      bool drawMarker = ( mDrawVertexMarkers && mContext.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || sel ) );

      if ( mCache )
      {
        // Cache this for the use of (e.g.) modifying the feature's uncommitted geometry.
        mCache->cacheGeometry( fet.id(), *fet.constGeometry() );
      }

      // render feature
      bool rendered = mRendererV2->renderFeature( fet, mContext, -1, sel, drawMarker );

      // labeling - register feature
      Q_UNUSED( rendered );
      if ( rendered && mContext.labelingEngine() )
      {
        if ( mLabeling )
        {
          mContext.labelingEngine()->registerFeature( mLayerID, fet, mContext );
        }
        if ( mDiagrams )
        {
          mContext.labelingEngine()->registerDiagramFeature( mLayerID, fet, mContext );
        }
      }
    }
    catch ( const QgsCsException &cse )
    {
      Q_UNUSED( cse );
      QgsDebugMsg( QString( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
                   .arg( fet.id() ).arg( cse.what() ) );
    }
  }

  stopRendererV2( NULL );
}
Example #8
0
void QgsGeometryAnalyzer::bufferFeature( QgsFeature& f, int nProcessedFeatures, QgsVectorFileWriter* vfw, bool dissolve,
    QgsGeometry** dissolveGeometry, double bufferDistance, int bufferDistanceField )
{
  if ( !f.constGeometry() )
  {
    return;
  }

  double currentBufferDistance;
  const QgsGeometry* featureGeometry = f.constGeometry();
  QgsGeometry* tmpGeometry = 0;
  QgsGeometry* bufferGeometry = 0;

  //create buffer
  if ( bufferDistanceField == -1 )
  {
    currentBufferDistance = bufferDistance;
  }
  else
  {
    currentBufferDistance = f.attribute( bufferDistanceField ).toDouble();
  }
  bufferGeometry = featureGeometry->buffer( currentBufferDistance, 5 );

  if ( dissolve )
  {
    if ( nProcessedFeatures == 0 )
    {
      *dissolveGeometry = bufferGeometry;
    }
    else
    {
      tmpGeometry = *dissolveGeometry;
      *dissolveGeometry = ( *dissolveGeometry )->combine( bufferGeometry );
      delete tmpGeometry;
      delete bufferGeometry;
    }
  }
  else //dissolve
  {
    QgsFeature newFeature;
    newFeature.setGeometry( bufferGeometry );
    newFeature.setAttributes( f.attributes() );

    //add it to vector file writer
    if ( vfw )
    {
      vfw->addFeature( newFeature );
    }
  }
}
Example #9
0
void topolTest::fillFeatureList( QgsVectorLayer* layer, const QgsRectangle& extent )
{
  QgsFeatureIterator fit;
  if ( extent.isEmpty() )
  {
    fit = layer->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QgsAttributeList() ) );
  }
  else
  {
    fit = layer->getFeatures( QgsFeatureRequest()
                              .setFilterRect( extent )
                              .setFlags( QgsFeatureRequest::ExactIntersect )
                              .setSubsetOfAttributes( QgsAttributeList() ) );
  }

  QgsFeature f;

  while ( fit.nextFeature( f ) )
  {
    if ( f.constGeometry() )
    {
      mFeatureList1 << FeatureLayer( layer, f );
    }
  }

}
Example #10
0
void QgsSpatialQuery::populateIndexResultDisjoint(
    QgsFeatureIds &qsetIndexResult, QgsFeatureId idTarget, QgsGeometry * geomTarget,
    bool ( QgsGeometry::* op )( const QgsGeometry * ) const )
{
    QList<QgsFeatureId> listIdReference;
    listIdReference = mIndexReference.intersects( geomTarget->boundingBox() );
    if ( listIdReference.isEmpty() )
    {
        qsetIndexResult.insert( idTarget );
        return;
    }
    QgsFeature featureReference;
    const QgsGeometry * geomReference;
    QList<QgsFeatureId>::iterator iterIdReference = listIdReference.begin();
    bool addIndex = true;
    for ( ; iterIdReference != listIdReference.end(); ++iterIdReference )
    {
        mLayerReference->getFeatures( QgsFeatureRequest().setFilterFid( *iterIdReference ) ).nextFeature( featureReference );
        geomReference = featureReference.constGeometry();

        if ( !( geomTarget->*op )( geomReference ) )
        {
            addIndex = false;
            break;
        }
    }
    if ( addIndex )
    {
        qsetIndexResult.insert( idTarget );
    }

} // void QgsSpatialQuery::populateIndexResultDisjoint( ...
Example #11
0
bool QgsVectorLayerEditUtils::deleteVertex( QgsFeatureId atFeatureId, int atVertex )
{
  if ( !L->hasGeometryType() )
    return false;

  QgsGeometry geometry;
  if ( !cache()->geometry( atFeatureId, geometry ) )
  {
    // it's not in cache: let's fetch it from layer
    QgsFeature f;
    if ( !L->getFeatures( QgsFeatureRequest().setFilterFid( atFeatureId ).setSubsetOfAttributes( QgsAttributeList() ) ).nextFeature( f ) || !f.constGeometry() )
      return false; // geometry not found

    geometry = *f.constGeometry();
  }

  if ( !geometry.deleteVertex( atVertex ) )
    return false;

  if ( geometry.geometry() && geometry.geometry()->nCoordinates() == 0 )
  {
    //last vertex deleted, set geometry to null
    geometry.setGeometry( 0 );
  }


  L->editBuffer()->changeGeometry( atFeatureId, &geometry );
  return true;
}
Example #12
0
void QgsMapToolDeleteRing::deleteRing( QgsFeatureId fId, int beforeVertexNr, QgsVectorLayer* vlayer )
{
  QgsFeature f;
  vlayer->getFeatures( QgsFeatureRequest().setFilterFid( fId ) ).nextFeature( f );

  const QgsGeometry* g = f.constGeometry();
  QGis::WkbType wkbtype = g->wkbType();
  int ringNum, partNum = 0;

  if ( wkbtype == QGis::WKBPolygon || wkbtype == QGis::WKBPolygon25D )
  {
    ringNum = ringNumInPolygon( g, beforeVertexNr );
  }
  else if ( wkbtype == QGis::WKBMultiPolygon || wkbtype == QGis::WKBMultiPolygon25D )
  {
    ringNum = ringNumInMultiPolygon( g, beforeVertexNr, partNum );
  }
  else
    return;

  QgsGeometry* editableGeom = f.geometry();
  if ( editableGeom->deleteRing( ringNum, partNum ) )
  {
    vlayer->beginEditCommand( tr( "Ring deleted" ) );
    vlayer->changeGeometry( fId, editableGeom );
    vlayer->endEditCommand();
    mCanvas->refresh();
  }

}
Example #13
0
void QgsSpatialQuery::populateIndexResultDisjoint(
  QgsFeatureIds &qsetIndexResult, QgsFeatureId idTarget, QgsGeometry * geomTarget,
  bool ( QgsGeometryEngine::* op )( const QgsAbstractGeometryV2&, QString* ) const )
{
  QgsFeatureIds listIdReference = mIndexReference.intersects( geomTarget->boundingBox() ).toSet();
  if ( listIdReference.isEmpty() )
  {
    qsetIndexResult.insert( idTarget );
    return;
  }

  //prepare geometry
  QgsGeometryEngine* geomEngine = geomTarget->createGeometryEngine( geomTarget->geometry() );
  geomEngine->prepareGeometry();

  QgsFeature featureReference;
  const QgsGeometry * geomReference;
  QgsFeatureIterator listIt = mLayerReference->getFeatures( QgsFeatureRequest().setFilterFids( listIdReference ) );

  bool addIndex = true;
  while ( listIt.nextFeature( featureReference ) )
  {
    geomReference = featureReference.constGeometry();
    if (( geomEngine->*op )( *( geomReference->geometry() ), 0 ) )
    {
      addIndex = false;
      break;
    }
  }
  if ( addIndex )
  {
    qsetIndexResult.insert( idTarget );
  }
  delete geomEngine;
} // void QgsSpatialQuery::populateIndexResultDisjoint( ...
Example #14
0
void QgsMapToolLabel::createRubberBands()
{
  delete mLabelRubberBand;
  delete mFeatureRubberBand;

  //label rubber band
  QgsRectangle rect = mCurrentLabelPos.labelRect;
  mLabelRubberBand = new QgsRubberBand( mCanvas, QGis::Line );
  mLabelRubberBand->addPoint( QgsPoint( rect.xMinimum(), rect.yMinimum() ) );
  mLabelRubberBand->addPoint( QgsPoint( rect.xMinimum(), rect.yMaximum() ) );
  mLabelRubberBand->addPoint( QgsPoint( rect.xMaximum(), rect.yMaximum() ) );
  mLabelRubberBand->addPoint( QgsPoint( rect.xMaximum(), rect.yMinimum() ) );
  mLabelRubberBand->addPoint( QgsPoint( rect.xMinimum(), rect.yMinimum() ) );
  mLabelRubberBand->setColor( QColor( 0, 255, 0, 65 ) );
  mLabelRubberBand->setWidth( 3 );
  mLabelRubberBand->show();

  //feature rubber band
  QgsVectorLayer* vlayer = currentLayer();
  if ( vlayer )
  {
    QgsFeature f;
    if ( currentFeature( f, true ) )
    {
      const QgsGeometry* geom = f.constGeometry();
      if ( geom )
      {
        mFeatureRubberBand = new QgsRubberBand( mCanvas, geom->type() );
        mFeatureRubberBand->setColor( QColor( 255, 0, 0, 65 ) );
        mFeatureRubberBand->setToGeometry( geom, vlayer );
        mFeatureRubberBand->show();
      }
    }

    //fixpoint rubber band
    QgsPoint fixPoint;
    if ( rotationPoint( fixPoint, false, false ) )
    {
      if ( mCanvas )
      {
        const QgsMapSettings& s = mCanvas->mapSettings();
        if ( s.hasCrsTransformEnabled() )
        {
          fixPoint = s.mapToLayerCoordinates( vlayer, fixPoint );
        }
      }

      QgsGeometry* pointGeom = QgsGeometry::fromPoint( fixPoint );
      mFixPointRubberBand = new QgsRubberBand( mCanvas, QGis::Line );
      mFixPointRubberBand->setColor( QColor( 0, 0, 255, 65 ) );
      mFixPointRubberBand->setToGeometry( pointGeom, vlayer );
      mFixPointRubberBand->show();
      delete pointGeom;
    }
  }
}
Example #15
0
QString TestQgsGrassCommand::toString() const
{
  QString string;
  if ( command == StartEditing )
  {
    string += "StartEditing grassLayerCode: " + values["grassLayerCode"].toString();
    string += " expectedLayerType: " + values["expectedLayerType"].toString();
  }
  else if ( command == CommitChanges )
  {
    string += "CommitChanges";
  }
  else if ( command == RollBack )
  {
    string += "RollBack";
  }
  else if ( command == AddFeature )
  {
    string += "AddFeature ";
    string += expectedFeature.constGeometry()->exportToWkt( 1 );
  }
  else if ( command == DeleteFeature )
  {
    string += "DeleteFeature ";
    string += QString( "fid: %1" ).arg( fid );
  }
  else if ( command == ChangeGeometry )
  {
    string += "ChangeGeometry ";
    string += QString( "fid: %1 geometry: %2" ).arg( fid ).arg( geometry->exportToWkt( 1 ) );
  }
  else if ( command == AddAttribute )
  {
    string += "AddAttribute ";
    string += "name: " + field.name() + " type: " + QVariant::typeToName( field.type() );
  }
  else if ( command == DeleteAttribute )
  {
    string += "DeleteAttribute ";
    string += "name: " + field.name();
  }
  else if ( command == ChangeAttributeValue )
  {
    string += "ChangeAttributeValue ";
    string += "name: " + field.name() + " value: " + value.toString();
  }
  else if ( command == UndoAll )
  {
    string += "UndoAll";
  }
  else if ( command == RedoAll )
  {
    string += "RedoAll";
  }
  return string;
}
void QgsMergeAttributesDialog::createRubberBandForFeature( int featureId )
{
  //create rubber band to highlight the feature
  delete mSelectionRubberBand;
  mSelectionRubberBand = new QgsRubberBand( mMapCanvas, mVectorLayer->geometryType() == QGis::Polygon );
  mSelectionRubberBand->setColor( QColor( 255, 0, 0, 65 ) );
  QgsFeature featureToSelect;
  mVectorLayer->getFeatures( QgsFeatureRequest().setFilterFid( featureId ).setSubsetOfAttributes( QgsAttributeList() ) ).nextFeature( featureToSelect );
  mSelectionRubberBand->setToGeometry( featureToSelect.constGeometry(), mVectorLayer );
}
void QgsOverlayAnalyzer::intersectFeature( QgsFeature& f, QgsVectorFileWriter* vfw,
        QgsVectorLayer* vl, QgsSpatialIndex* index )
{
    if ( !f.constGeometry() )
    {
        return;
    }

    const QgsGeometry* featureGeometry = f.constGeometry();
    QgsGeometry* intersectGeometry = nullptr;
    QgsFeature overlayFeature;

    QList<QgsFeatureId> intersects;
    intersects = index->intersects( featureGeometry->boundingBox() );
    QList<QgsFeatureId>::const_iterator it = intersects.constBegin();
    QgsFeature outFeature;
    for ( ; it != intersects.constEnd(); ++it )
    {
        if ( !vl->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( overlayFeature ) )
        {
            continue;
        }

        if ( featureGeometry->intersects( overlayFeature.constGeometry() ) )
        {
            intersectGeometry = featureGeometry->intersection( overlayFeature.constGeometry() );

            outFeature.setGeometry( intersectGeometry );
            QgsAttributes attributesA = f.attributes();
            QgsAttributes attributesB = overlayFeature.attributes();
            combineAttributeMaps( attributesA, attributesB );
            outFeature.setAttributes( attributesA );

            //add it to vector file writer
            if ( vfw )
            {
                vfw->addFeature( outFeature );
            }
        }
    }
}
Example #18
0
void QgsWFSProvider::featureReceivedAnalyzeOneFeature( QVector<QgsWFSFeatureGmlIdPair> list )
{
  if ( list.size() != 0 )
  {
    QgsFeature feat = list[0].first;
    const QgsGeometry* geometry = feat.constGeometry();
    if ( geometry )
    {
      mWKBType = geometry->wkbType();
    }
  }
}
Example #19
0
bool QgsAbstractFeatureIterator::nextFeature( QgsFeature& f )
{
    bool dataOk = false;
    if ( mRequest.limit() >= 0 && mFetchedCount >= mRequest.limit() )
    {
        return false;
    }

    if ( mUseCachedFeatures )
    {
        if ( mFeatureIterator != mCachedFeatures.constEnd() )
        {
            f = mFeatureIterator->mFeature;
            ++mFeatureIterator;
            dataOk = true;
        }
        else
        {
            dataOk = false;
            // even the zombie dies at this point...
            mZombie = false;
        }
    }
    else
    {
        switch ( mRequest.filterType() )
        {
        case QgsFeatureRequest::FilterExpression:
            dataOk = nextFeatureFilterExpression( f );
            break;

        case QgsFeatureRequest::FilterFids:
            dataOk = nextFeatureFilterFids( f );
            break;

        default:
            dataOk = fetchFeature( f );
            break;
        }
    }

    // simplify the geometry using the simplifier configured
    if ( dataOk && mLocalSimplification )
    {
        if ( f.constGeometry() )
            simplify( f );
    }
    if ( dataOk )
        mFetchedCount++;

    return dataOk;
}
Example #20
0
void QgsGeometryAnalyzer::centroidFeature( QgsFeature& f, QgsVectorFileWriter* vfw )
{
  if ( !f.constGeometry() )
  {
    return;
  }

  const QgsGeometry* featureGeometry = f.constGeometry();
  QgsGeometry* tmpGeometry = 0;

  tmpGeometry = featureGeometry->centroid();

  QgsFeature newFeature;
  newFeature.setGeometry( tmpGeometry );
  newFeature.setAttributes( f.attributes() );

  //add it to vector file writer
  if ( vfw )
  {
    vfw->addFeature( newFeature );
  }
}
Example #21
0
void QgsGeometryAnalyzer::dissolveFeature( QgsFeature& f, int nProcessedFeatures, QgsGeometry** dissolveGeometry )
{
  if ( !f.constGeometry() )
  {
    return;
  }

  const QgsGeometry* featureGeometry = f.constGeometry();

  if ( nProcessedFeatures == 0 )
  {
    size_t geomSize = featureGeometry->wkbSize();
    *dissolveGeometry = new QgsGeometry();
    unsigned char* wkb = new unsigned char[geomSize];
    memcpy( wkb, featureGeometry->asWkb(), geomSize );
    ( *dissolveGeometry )->fromWkb( wkb, geomSize );
  }
  else
  {
    *dissolveGeometry = ( *dissolveGeometry )->combine( featureGeometry );
  }
}
Example #22
0
bool QgsSpatialQuery::hasValidGeometry( QgsFeature &feature )
{
  if ( !feature.isValid() )
    return false;

  const QgsGeometry *geom = feature.constGeometry();

  if ( !geom || geom->isGeosEmpty() )
    return false;

  return true;

} // bool QgsSpatialQuery::hasValidGeometry(QgsFeature &feature)
Example #23
0
int QgsVectorLayerEditUtils::addPart( QgsCurveV2* ring, QgsFeatureId featureId )
{
  if ( !L->hasGeometryType() )
    return 6;

  QgsGeometry geometry;
  bool firstPart = false;
  if ( !cache()->geometry( featureId, geometry ) ) // maybe it's in cache
  {
    // it's not in cache: let's fetch it from layer
    QgsFeature f;
    if ( !L->getFeatures( QgsFeatureRequest().setFilterFid( featureId ).setSubsetOfAttributes( QgsAttributeList() ) ).nextFeature( f ) )
      return 6; //not found

    if ( !f.constGeometry() || f.constGeometry()->isEmpty() )
    {
      //no existing geometry, so adding first part to null geometry
      firstPart = true;
    }
    else
    {
      geometry = *f.geometry();
    }
  }

  int errorCode = geometry.addPart( ring, L->geometryType() );
  if ( errorCode == 0 )
  {
    if ( firstPart && QgsWKBTypes::isSingleType( QGis::fromOldWkbType( L->wkbType() ) )
         && L->dataProvider()->doesStrictFeatureTypeCheck() )
    {
      //convert back to single part if required by layer
      geometry.convertToSingleType();
    }
    L->editBuffer()->changeGeometry( featureId, &geometry );
  }
  return errorCode;
}
Example #24
0
QgsGeometry* QgsMapToolDeleteRing::ringUnderPoint( QgsPoint p, QgsFeatureId& fid, int& partNum, int& ringNum )
{
  //There is no clean way to find if we are inside the ring of a feature,
  //so we iterate over all the features visible in the canvas
  //If several rings are found at this position, the smallest one is chosen,
  //in order to be able to delete a ring inside another ring
  QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( toLayerCoordinates( vlayer, mCanvas->extent() ) ) );
  QgsFeature f;
  const QgsGeometry* g;
  QScopedPointer<QgsGeometry> ringGeom;
  QgsMultiPolygon pol;
  QgsPolygon tempPol;
  QScopedPointer<QgsGeometry> tempGeom;
  double area = std::numeric_limits<double>::max();
  while ( fit.nextFeature( f ) )
  {
    g = f.constGeometry();
    if ( !g )
      continue;
    if ( g->wkbType() == QGis::WKBPolygon ||  g->wkbType()  == QGis::WKBPolygon25D )
    {
      pol = QgsMultiPolygon() << g->asPolygon();
    }
    else
    {
      pol = g->asMultiPolygon();
    }

    for ( int i = 0; i < pol.size() ; ++i )
    {//for each part
      if ( pol[i].size() > 1 )
      {
        for ( int j = 1; j < pol[i].size();++j )
        {
          tempPol = QgsPolygon() << pol[i][j];
          tempGeom.reset( QgsGeometry::fromPolygon( tempPol ) );
          if ( tempGeom->area() < area && tempGeom->contains( &p ) )
          {
            fid = f.id();
            partNum = i;
            ringNum = j;
            area = tempGeom->area();
            ringGeom.reset( tempGeom.take() );
          }
        }
      }
    }
  }
  return ringGeom.take();
}
Example #25
0
void QgsGeometryAnalyzer::simplifyFeature( QgsFeature& f, QgsVectorFileWriter* vfw, double tolerance )
{
  if ( !f.constGeometry() )
  {
    return;
  }

  const QgsGeometry* featureGeometry = f.constGeometry();
  QgsGeometry* tmpGeometry = 0;

  // simplify feature
  tmpGeometry = featureGeometry->simplify( tolerance );

  QgsFeature newFeature;
  newFeature.setGeometry( tmpGeometry );
  newFeature.setAttributes( f.attributes() );

  //add it to vector file writer
  if ( vfw )
  {
    vfw->addFeature( newFeature );
  }
}
Example #26
0
int QgsVectorLayerEditUtils::addRing( QgsCurveV2* ring, const QgsFeatureIds& targetFeatureIds, QgsFeatureId* modifiedFeatureId )
{
  if ( !L->hasGeometryType() )
  {
    delete ring;
    return 5;
  }

  int addRingReturnCode = 5; //default: return code for 'ring not inserted'
  QgsFeature f;

  QgsFeatureIterator fit;
  if ( !targetFeatureIds.isEmpty() )
  {
    //check only specified features
    fit = L->getFeatures( QgsFeatureRequest().setFilterFids( targetFeatureIds ) );
  }
  else
  {
    //check all intersecting features
    QgsRectangle bBox = ring->boundingBox();
    fit = L->getFeatures( QgsFeatureRequest().setFilterRect( bBox ).setFlags( QgsFeatureRequest::ExactIntersect ) );
  }

  //find first valid feature we can add the ring to
  while ( fit.nextFeature( f ) )
  {
    if ( !f.constGeometry() )
      continue;

    //add ring takes ownership of ring, and deletes it if there's an error
    addRingReturnCode = f.geometry()->addRing( static_cast< QgsCurveV2* >( ring->clone() ) );
    if ( addRingReturnCode == 0 )
    {
      L->editBuffer()->changeGeometry( f.id(), f.geometry() );
      if ( modifiedFeatureId )
        *modifiedFeatureId = f.id();

      //setModified( true, true );
      break;
    }
  }

  delete ring;
  return addRingReturnCode;
}
bool QgsOgrFeatureIterator::fetchFeature( QgsFeature& feature )
{
  feature.setValid( false );

  if ( mClosed )
    return false;

  if ( mRequest.filterType() == QgsFeatureRequest::FilterFid )
  {
    OGRFeatureH fet = OGR_L_GetFeature( ogrLayer, FID_TO_NUMBER( mRequest.filterFid() ) );
    if ( !fet )
    {
      close();
      return false;
    }

    if ( readFeature( fet, feature ) )
      OGR_F_Destroy( fet );

    feature.setValid( true );
    close(); // the feature has been read: we have finished here
    return true;
  }

  OGRFeatureH fet;

  while (( fet = OGR_L_GetNextFeature( ogrLayer ) ) )
  {
    if ( !readFeature( fet, feature ) )
      continue;

    if ( !mRequest.filterRect().isNull() && !feature.constGeometry() )
      continue;

    // we have a feature, end this cycle
    feature.setValid( true );
    OGR_F_Destroy( fet );
    return true;

  } // while

  close();
  return false;
}
Example #28
0
bool QgsVectorLayerEditUtils::moveVertex( const QgsPointV2& p, QgsFeatureId atFeatureId, int atVertex )
{
  if ( !L->hasGeometryType() )
    return false;

  QgsGeometry geometry;
  if ( !cache()->geometry( atFeatureId, geometry ) )
  {
    // it's not in cache: let's fetch it from layer
    QgsFeature f;
    if ( !L->getFeatures( QgsFeatureRequest().setFilterFid( atFeatureId ).setSubsetOfAttributes( QgsAttributeList() ) ).nextFeature( f ) || !f.constGeometry() )
      return false; // geometry not found

    geometry = *f.constGeometry();
  }

  geometry.moveVertex( p, atVertex );

  L->editBuffer()->changeGeometry( atFeatureId, &geometry );
  return true;
}
Example #29
0
QgsSpatialIndex* topolTest::createIndex( QgsVectorLayer* layer, const QgsRectangle& extent )
{
  QgsSpatialIndex* index = new QgsSpatialIndex();

  QgsFeatureIterator fit;
  if ( extent.isEmpty() )
  {
    fit = layer->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QgsAttributeList() ) );
  }
  else
  {
    fit = layer->getFeatures( QgsFeatureRequest()
                              .setFilterRect( extent )
                              .setFlags( QgsFeatureRequest::ExactIntersect )
                              .setSubsetOfAttributes( QgsAttributeList() ) );
  }


  int i = 0;
  QgsFeature f;
  while ( fit.nextFeature( f ) )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );

    if ( testCancelled() )
    {
      delete index;
      return 0;
    }

    if ( f.constGeometry() )
    {
      index->insertFeature( f );
      mFeatureMap2[f.id()] = FeatureLayer( layer, f );
    }
  }

  return index;
}
Example #30
0
bool QgsSpatialQuery::hasValidGeometry( QgsFeature &feature )
{
    if ( ! feature.isValid() )
    {
        return false;
    }

    const QgsGeometry *geom = feature.constGeometry();

    if ( NULL == geom )
    {
        return false;
    }

    if ( geom->isGeosEmpty() )
    {
        return false;
    }

    return true;

} // bool QgsSpatialQuery::hasValidGeometry(QgsFeature &feature)