int QgsUniqueValueRenderer::readXML( const QDomNode& rnode, QgsVectorLayer& vl )
{
  mGeometryType = vl.geometryType();
  QDomNode classnode = rnode.namedItem( "classificationfield" );
  QString classificationField = classnode.toElement().text();

  QgsVectorDataProvider* theProvider = vl.dataProvider();
  if ( !theProvider )
  {
    return 1;
  }

  int classificationId = vl.fieldNameIndex( classificationField );
  if ( classificationId == -1 )
  {
    //go on. Because with joins, it might be the joined layer is not loaded yet
  }
  setClassificationField( classificationId );

  QDomNode symbolnode = rnode.namedItem( "symbol" );
  while ( !symbolnode.isNull() )
  {
    QgsSymbol* msy = new QgsSymbol( mGeometryType );
    msy->readXML( symbolnode, &vl );
    insertValue( msy->lowerValue(), msy );
    symbolnode = symbolnode.nextSibling();
  }
  updateSymbolAttributes();
  vl.setRenderer( this );
  return 0;
}
int QgsContinuousColorRenderer::readXML( const QDomNode& rnode, QgsVectorLayer& vl )
{
  mGeometryType = vl.geometryType();
  QDomNode classnode = rnode.namedItem( "classificationfield" );
  QString classificationField = classnode.toElement().text();

  QgsVectorDataProvider* theProvider = vl.dataProvider();
  if ( !theProvider )
  {
    return 1;
  }
  int classificationId = vl.fieldNameIndex( classificationField );
  if ( classificationId == -1 )
  {
    //go on. Because with joins, it might be the joined layer is not loaded yet
  }
  setClassificationField( classificationId );

  //polygon outline
  QDomNode polyoutlinenode = rnode.namedItem( "polygonoutline" );
  QString polyoutline = polyoutlinenode.toElement().text();
  if ( polyoutline == "0" )
  {
    mDrawPolygonOutline = false;
  }
  else if ( polyoutline == "1" )
  {
    mDrawPolygonOutline = true;
  }

  //read the settings for the renderitem of the minimum value
  QDomNode lowernode = rnode.namedItem( "lowestsymbol" );
  QDomNode lsymbolnode = lowernode.namedItem( "symbol" );
  if ( ! lsymbolnode.isNull() )
  {
    QgsSymbol* lsy = new QgsSymbol( mGeometryType );
    lsy->readXML( lsymbolnode, &vl );
    setMinimumSymbol( lsy );
  }
  QDomNode uppernode = rnode.namedItem( "highestsymbol" );
  QDomNode usymbolnode = uppernode.namedItem( "symbol" );
  if ( ! usymbolnode.isNull() )
  {
    QgsSymbol* usy = new QgsSymbol( mGeometryType );
    usy->readXML( usymbolnode, &vl );
    setMaximumSymbol( usy );
  }
  vl.setRenderer( this );
  return 0;
}
int QgsGraduatedSymbolRenderer::readXML( const QDomNode& rnode, QgsVectorLayer& vl )
{
  mGeometryType = vl.geometryType();
  QDomNode modeNode = rnode.namedItem( "mode" );
  QString modeValue = modeNode.toElement().text();
  QDomNode classnode = rnode.namedItem( "classificationfield" );
  QString classificationField = classnode.toElement().text();

  QgsVectorDataProvider* theProvider = vl.dataProvider();
  if ( !theProvider )
  {
    return 1;
  }
  if ( modeValue == "Empty" )
  {
    mMode = QgsGraduatedSymbolRenderer::Empty;
  }
  else if ( modeValue == "Quantile" )
  {
    mMode = QgsGraduatedSymbolRenderer::Quantile;
  }
  else //default
  {
    mMode = QgsGraduatedSymbolRenderer::EqualInterval;
  }

  int classificationId = theProvider->fieldNameIndex( classificationField );
  if ( classificationId == -1 )
  {
    return 2; //@todo: handle gracefully in gui situation where user needs to nominate field
  }
  setClassificationField( classificationId );

  QDomNode symbolnode = rnode.namedItem( "symbol" );
  while ( !symbolnode.isNull() )
  {
    QgsSymbol* sy = new QgsSymbol( mGeometryType );
    sy->readXML( symbolnode, &vl );
    addSymbol( sy );

    symbolnode = symbolnode.nextSibling();
  }
  updateSymbolAttributes();
  vl.setRenderer( this );
  return 0;
}
int QgsGraduatedSymbolRenderer::readXML( const QDomNode& rnode, QgsVectorLayer& vl )
{
  mGeometryType = vl.geometryType();
  QDomNode modeNode = rnode.namedItem( "mode" );
  QString modeValue = modeNode.toElement().text();
  QDomNode classnode = rnode.namedItem( "classificationfield" );
  QString classificationField = classnode.toElement().text();

  QgsVectorDataProvider* theProvider = vl.dataProvider();
  if ( !theProvider )
  {
    return 1;
  }
  if ( modeValue == "Empty" )
  {
    mMode = QgsGraduatedSymbolRenderer::Empty;
  }
  else if ( modeValue == "Quantile" )
  {
    mMode = QgsGraduatedSymbolRenderer::Quantile;
  }
  else //default
  {
    mMode = QgsGraduatedSymbolRenderer::EqualInterval;
  }

  int classificationId = vl.fieldNameIndex( classificationField );
  if ( classificationId == -1 )
  {
    //go on. Because with joins, it might be the joined layer is not loaded yet
  }
  setClassificationField( classificationId );

  QDomNode symbolnode = rnode.namedItem( "symbol" );
  while ( !symbolnode.isNull() )
  {
    QgsSymbol* sy = new QgsSymbol( mGeometryType );
    sy->readXML( symbolnode, &vl );
    addSymbol( sy );

    symbolnode = symbolnode.nextSibling();
  }
  updateSymbolAttributes();
  vl.setRenderer( this );
  return 0;
}
Esempio n. 5
0
int main(int argc, char ** argv) 
{
  // Start the Application
  QgsApplication app(argc, argv, true);

  QString myPluginsDir        = "/home/timlinux/apps/lib/qgis";
  QString myLayerPath         = "/home/timlinux/gisdata/brazil/BR_Cidades/";
  QString myLayerBaseName     = "Brasil_Cap";
  QString myProviderName      = "ogr";
  // Instantiate Provider Registry
  QgsProviderRegistry::instance(myPluginsDir);
  // create a maplayer instance
  QgsVectorLayer * mypLayer = 
      new QgsVectorLayer(myLayerPath, myLayerBaseName, myProviderName);
  QgsSingleSymbolRenderer *mypRenderer = new QgsSingleSymbolRenderer(mypLayer->geometryType());
  QList <QgsMapCanvasLayer> myLayerSet;
  mypLayer->setRenderer(mypRenderer);
  if (mypLayer->isValid())
  {
    qDebug("Layer is valid");
  }
  else
  {
    qDebug("Layer is NOT valid");
  }

  // Add the Vector Layer to the Layer Registry
  QgsMapLayerRegistry::instance()->addMapLayer(mypLayer, TRUE);
  // Add the Layer to the Layer Set
  myLayerSet.append(QgsMapCanvasLayer(mypLayer, TRUE));

  // Create the Map Canvas
  QgsMapCanvas * mypMapCanvas = new QgsMapCanvas(0, 0);
  mypMapCanvas->setExtent(mypLayer->extent());
  mypMapCanvas->enableAntiAliasing(true);
  mypMapCanvas->setCanvasColor(QColor(255, 255, 255));
  mypMapCanvas->freeze(false);
  // Set the Map Canvas Layer Set
  mypMapCanvas->setLayerSet(myLayerSet);
  mypMapCanvas->setVisible(true);
  mypMapCanvas->refresh();

  // Start the Application Event Loop
  return app.exec();
}
int QgsSingleSymbolRenderer::readXML( const QDomNode& rnode, QgsVectorLayer& vl )
{
  mGeometryType = vl.geometryType();
  QgsSymbol* sy = new QgsSymbol( mGeometryType );

  QDomNode synode = rnode.namedItem( "symbol" );

  if ( synode.isNull() )
  {
    QgsDebugMsg( "No symbol node in project file's renderitem Dom" );
    // XXX abort?
  }
  else
  {
    sy->readXML( synode, &vl );
  }
  updateSymbolAttributes();

  //create a renderer and add it to the vector layer
  addSymbol( sy );
  vl.setRenderer( this );
  return 0;
}
void MainWindow::addLayer()
{
  QString myLayerPath         = "../data";
  QString myLayerBaseName     = "test";
  QString myProviderName      = "ogr";
  
  QgsVectorLayer * mypLayer = new QgsVectorLayer(myLayerPath, myLayerBaseName, myProviderName);

  if (mypLayer->isValid())
  {
    qDebug("Layer is valid");
  }
  else
  {
    qDebug("Layer is NOT valid");
    return;
  }
  
  //set up a renderer for the layer
  QgsSingleSymbolRenderer *mypRenderer = new QgsSingleSymbolRenderer(mypLayer->geometryType());
  QList<QgsMapCanvasLayer> myLayerSet;
  mypLayer->setRenderer(mypRenderer);
  
  //
  //set up labelling for the layer
  //

  //get the label instance associated with the layer
  QgsLabel * mypLabel;
  mypLabel = mypLayer->label();
  //and the label attributes associated with the label
  QgsLabelAttributes * mypLabelAttributes;
  mypLabelAttributes = mypLabel->layerAttributes();
  //note in QGIS 1.4 and up you should use mypLabel->labelAttributes rather

  //get the field list associated with the layer
  //we'll print the names out to console for diagnostic purposes
  QgsFieldMap myFields = mypLayer->dataProvider()->fields();
  for (unsigned int i = 0; i < myFields.size(); i++ )
  {
    qDebug("Field Name: " +  QString(myFields[i].name()).toLocal8Bit() );
  }
  //just use the last field's name in the fields list as the label field! 
  qDebug("set label field to " + QString(myFields[myFields.size()-1].name()).toLocal8Bit());
  mypLabel->setLabelField( QgsLabel::Text,  myFields.size()-1);
  //set the colour of the label text
  mypLabelAttributes->setColor(Qt::black);
  //create a 'halo' effect around each label so it
  //can still be read on dark backgrounds
  mypLabelAttributes->setBufferEnabled(true);
  mypLabelAttributes->setBufferColor(Qt::yellow);
  int myType = QgsLabelAttributes::PointUnits;
  mypLabelAttributes->setBufferSize(1,myType);
  
  /*
   * Here are a bunch of other things you can set based on values on a database field
   * the second parameter in each case would be the field name from which the 
   * attribute can be retrieved.
  mypLabel->setLabelField( QgsLabel::Family, "fontFamily" );
  mypLabel->setLabelField( QgsLabel::Bold,  "fontIsBold" );
  mypLabel->setLabelField( QgsLabel::Italic, "fontIsItalic"  );
  mypLabel->setLabelField( QgsLabel::Underline, "fontIsUnderlined"  );
  mypLabel->setLabelField( QgsLabel::Size, "fontSize" );
  mypLabel->setLabelField( QgsLabel::BufferSize,"fontBufferSize" );
  mypLabel->setLabelField( QgsLabel::XCoordinate, "labelX" );
  mypLabel->setLabelField( QgsLabel::YCoordinate, "labelY");
  mypLabel->setLabelField( QgsLabel::XOffset, "labelXOffset");
  mypLabel->setLabelField( QgsLabel::YOffset, "labelYOffset");
  mypLabel->setLabelField( QgsLabel::Alignment, "labelAlignment" );
  mypLabel->setLabelField( QgsLabel::Angle, "labelAngle");
  */
  
  //lastly we enable labelling!
  mypLayer->enableLabels(true);
  
  // Add the Vector Layer to the Layer Registry
  QgsMapLayerRegistry::instance()->addMapLayer(mypLayer, TRUE);

  // Add the Layer to the Layer Set
  myLayerSet.append(QgsMapCanvasLayer( mypLayer ) );
  // set teh canvas to the extent of our layer
  mpMapCanvas->setExtent(mypLayer->extent());
  // Set the Map Canvas Layer Set
  mpMapCanvas->setLayerSet(myLayerSet);
}
Esempio n. 8
0
void QgsDwgImportDialog::createGroup( QgsLayerTreeGroup *group, const QString &name, const QStringList &layers, bool visible )
{
  QgsLayerTreeGroup *layerGroup = group->addGroup( name );
  QgsDebugMsg( QStringLiteral( " %1" ).arg( name ) ) ;
  Q_ASSERT( layerGroup );

  QString layerFilter;
  if ( !layers.isEmpty() )
  {
    QStringList exprlist;
    const auto constLayers = layers;
    for ( QString layer : constLayers )
    {
      exprlist.append( QStringLiteral( "'%1'" ).arg( layer.replace( QLatin1String( "'" ), QLatin1String( "''" ) ) ) );
    }
    layerFilter = QStringLiteral( "layer IN (%1) AND " ).arg( exprlist.join( QStringLiteral( "," ) ) );
  }

  QgsVectorLayer *l = nullptr;
  QgsSymbol *sym = nullptr;

  l = layer( layerGroup, layerFilter, QStringLiteral( "hatches" ) );
  if ( l )
  {
    QgsSimpleFillSymbolLayer *sfl = new QgsSimpleFillSymbolLayer();
    sfl->setDataDefinedProperty( QgsSymbolLayer::PropertyFillColor, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    sfl->setStrokeStyle( Qt::NoPen );
    sym = new QgsFillSymbol();
    sym->changeSymbolLayer( 0, sfl );
    l->setRenderer( new QgsSingleSymbolRenderer( sym ) );
  }

  l = layer( layerGroup, layerFilter, QStringLiteral( "lines" ) );
  if ( l )
  {
    QgsSimpleLineSymbolLayer *sll = new QgsSimpleLineSymbolLayer();
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeColor, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    sll->setPenJoinStyle( Qt::MiterJoin );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeWidth, QgsProperty::fromField( QStringLiteral( "linewidth" ) ) );
    // sll->setUseCustomDashPattern( true );
    // sll->setCustomDashPatternUnit( QgsSymbolV2::MapUnit );
    // sll->setDataDefinedProperty( QgsSymbolLayer::PropertyCustomDash, QgsProperty::fromField( "linetype" ) );
    sym = new QgsLineSymbol();
    sym->changeSymbolLayer( 0, sll );
    sym->setOutputUnit( QgsUnitTypes::RenderMillimeters );
    l->setRenderer( new QgsSingleSymbolRenderer( sym ) );
  }

  l = layer( layerGroup, layerFilter, QStringLiteral( "polylines" ) );
  if ( l )
  {
    sym = new QgsLineSymbol();

    QgsSimpleLineSymbolLayer *sll = new QgsSimpleLineSymbolLayer();
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeColor, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    sll->setPenJoinStyle( Qt::MiterJoin );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeWidth, QgsProperty::fromField( QStringLiteral( "width" ) ) );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyLayerEnabled, QgsProperty::fromExpression( QStringLiteral( "width>0" ) ) );
    sll->setOutputUnit( QgsUnitTypes::RenderMapUnits );
    // sll->setUseCustomDashPattern( true );
    // sll->setCustomDashPatternUnit( QgsSymbolV2::MapUnit );
    // sll->setDataDefinedProperty( QgsSymbolLayer::PropertyCustomDash, QgsProperty::fromField( "linetype" ) );
    sym->changeSymbolLayer( 0, sll );

    sll = new QgsSimpleLineSymbolLayer();
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeColor, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    sll->setPenJoinStyle( Qt::MiterJoin );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeWidth, QgsProperty::fromField( QStringLiteral( "linewidth" ) ) );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyLayerEnabled, QgsProperty::fromExpression( QStringLiteral( "width=0" ) ) );
    sll->setOutputUnit( QgsUnitTypes::RenderMillimeters );
    sym->appendSymbolLayer( sll );

    l->setRenderer( new QgsSingleSymbolRenderer( sym ) );
  }

  l = layer( layerGroup, layerFilter, QStringLiteral( "texts" ) );
  if ( l )
  {
    l->setRenderer( new QgsNullSymbolRenderer() );

    QgsTextFormat tf;
    tf.setSizeUnit( QgsUnitTypes::RenderMapUnits );

    QgsPalLayerSettings pls;
    pls.setFormat( tf );

    pls.drawLabels = true;
    pls.fieldName = QStringLiteral( "text" );
    pls.wrapChar = QStringLiteral( "\\P" );

    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::Size, QgsProperty::fromField( QStringLiteral( "height" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::Color, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::MultiLineHeight, QgsProperty::fromExpression( QStringLiteral( "CASE WHEN interlin<0 THEN 1 ELSE interlin*1.5 END" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::PositionX, QgsProperty::fromExpression( QStringLiteral( "$x" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::PositionY, QgsProperty::fromExpression( QStringLiteral( "$y" ) ) );

    // DXF TEXT
    // vertical: 0 = Base, 1 = Bottom, 2 = Middle, 3 = Top,  default Base
    // horizontal: 0 = Left, 1 = Center, 2 = Right, 3 = Aligned (if Base), 4 = Middle (if Base), default Left

    // DXF MTEXT
    // 1 = Top left;    2 = Top center;    3 = Top right
    // 4 = Middle left; 5 = Middle center; 6 = Middle right
    // 7 = Bottom left; 8 = Bottom center; 9 = Bottom right

    // QGIS Quadrant
    // 0 QuadrantAboveLeft, 1 QuadrantAbove, 2 QuadrantAboveRight,
    // 3 QuadrantLeft,      4 QuadrantOver,  5 QuadrantRight,
    // 6 QuadrantBelowLeft, 7 QuadrantBelow, 8 QuadrantBelowRight,

    pls.dataDefinedProperties().setProperty(
      QgsPalLayerSettings::Hali,
      QgsProperty::fromExpression( QStringLiteral(
                                     "CASE"
                                     " WHEN etype=%1 THEN"
                                     " CASE"
                                     " WHEN textgen % 3=2 THEN 'Center'"
                                     " WHEN textgen % 3=0 THEN 'Right'"
                                     " ELSE 'Left'"
                                     " END"
                                     " ELSE"
                                     " CASE"
                                     " WHEN alignh=1 THEN 'Center'"
                                     " WHEN alignh=2 THEN 'Right'"
                                     " ELSE 'Left'"
                                     " END"
                                     " END"
                                   ).arg( DRW::MTEXT )
                                 )
    );

    pls.dataDefinedProperties().setProperty(
      QgsPalLayerSettings::Vali,
      QgsProperty::fromExpression( QStringLiteral(
                                     "CASE"
                                     " WHEN etype=%1 THEN"
                                     " CASE"
                                     " WHEN textgen<4 THEN 'Top'"
                                     " WHEN textgen<7 THEN 'Half'"
                                     " ELSE 'Bottom'"
                                     " END"
                                     " ELSE"
                                     " CASE"
                                     " WHEN alignv=1 THEN 'Bottom'"
                                     " WHEN alignv=2 THEN 'Half'"
                                     " WHEN alignv=3 THEN 'Top'"
                                     " ELSE 'Base'"
                                     " END"
                                     " END"
                                   ).arg( DRW::MTEXT )
                                 )
    );

    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::LabelRotation, QgsProperty::fromExpression( QStringLiteral( "360-angle" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::AlwaysShow, QgsProperty::fromExpression( QStringLiteral( "1" ) ) );

    l->setLabeling( new QgsVectorLayerSimpleLabeling( pls ) );
    l->setLabelsEnabled( true );
  }

  l = layer( layerGroup, layerFilter, QStringLiteral( "points" ) );
  if ( l )
  {
    // FIXME: use PDMODE?
    l->setRenderer( new QgsNullSymbolRenderer() );
  }

  if ( !cbExpandInserts->isChecked() )
    layer( layerGroup, layerFilter, QStringLiteral( "inserts" ) );

  if ( !layerGroup->children().isEmpty() )
  {
    layerGroup->setExpanded( false );
    layerGroup->setItemVisibilityChecked( visible );
  }
  else
  {
    layerGroup->parent()->takeChild( layerGroup );
    delete layerGroup;
  }
}
Esempio n. 9
0
QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& userStyleElem, QgsRasterLayer* rasterLayer ) const
{
  QgsDebugMsg( "Entering." );

  if ( !rasterLayer )
  {
    return nullptr;
  }

  //get <ContourSymbolizer> element
  QDomNodeList contourNodeList = userStyleElem.elementsByTagName( QStringLiteral( "ContourSymbolizer" ) );
  if ( contourNodeList.size() < 1 )
  {
    return nullptr;
  }

  QDomElement contourSymbolizerElem = contourNodeList.item( 0 ).toElement();
  if ( contourSymbolizerElem.isNull() )
  {
    return nullptr;
  }

  double equidistance, minValue, maxValue, offset;
  QString propertyName;

  equidistance = contourSymbolizerElem.attribute( QStringLiteral( "equidistance" ) ).toDouble();
  minValue = contourSymbolizerElem.attribute( QStringLiteral( "minValue" ) ).toDouble();
  maxValue = contourSymbolizerElem.attribute( QStringLiteral( "maxValue" ) ).toDouble();
  offset = contourSymbolizerElem.attribute( QStringLiteral( "offset" ) ).toDouble();
  propertyName = contourSymbolizerElem.attribute( QStringLiteral( "propertyName" ) );

  if ( equidistance <= 0.0 )
  {
    return nullptr;
  }

  QTemporaryFile* tmpFile1 = new QTemporaryFile();
  tmpFile1->open();
  mFilesToRemove.push_back( tmpFile1 );
  QString tmpBaseName = tmpFile1->fileName();
  QString tmpFileName = tmpBaseName + ".shp";

  //hack: use gdal_contour first to write into a temporary file
  /* todo: use GDALContourGenerate( hBand, dfInterval, dfOffset,
                                nFixedLevelCount, adfFixedLevels,
                                bNoDataSet, dfNoData,
                                hLayer, 0, nElevField,
                                GDALTermProgress, nullptr );*/


  //do the stuff that is also done in the main method of gdal_contour...
  /* -------------------------------------------------------------------- */
  /*      Open source raster file.                                        */
  /* -------------------------------------------------------------------- */
  GDALRasterBandH hBand;
  GDALDatasetH hSrcDS;

  int numberOfLevels = 0;
  double currentLevel = 0.0;

  if ( maxValue > minValue )
  {
    //find first level
    currentLevel = ( int )(( minValue - offset ) / equidistance + 0.5 ) * equidistance + offset;
    while ( currentLevel <= maxValue )
    {
      ++numberOfLevels;
      currentLevel += equidistance;
    }
  }

  double *adfFixedLevels = new double[numberOfLevels];
  int    nFixedLevelCount = numberOfLevels;
  currentLevel = ( int )(( minValue - offset ) / equidistance + 0.5 ) * equidistance + offset;
  for ( int i = 0; i < numberOfLevels; ++i )
  {
    adfFixedLevels[i] = currentLevel;
    currentLevel += equidistance;
  }
  int nBandIn = 1;
  double dfInterval = equidistance, dfNoData = 0.0, dfOffset = offset;

  int /* b3D = FALSE, */ bNoDataSet = FALSE, bIgnoreNoData = FALSE;

  hSrcDS = GDALOpen( rasterLayer->source().toUtf8().constData(), GA_ReadOnly );
  if ( !hSrcDS )
  {
    delete [] adfFixedLevels;
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a file not available on the server." ) );
  }

  hBand = GDALGetRasterBand( hSrcDS, nBandIn );
  if ( !hBand )
  {
    CPLError( CE_Failure, CPLE_AppDefined,
              "Band %d does not exist on dataset.",
              nBandIn );
  }

  if ( !bNoDataSet && !bIgnoreNoData )
    dfNoData = GDALGetRasterNoDataValue( hBand, &bNoDataSet );

  /* -------------------------------------------------------------------- */
  /*      Try to get a coordinate system from the raster.                 */
  /* -------------------------------------------------------------------- */
  OGRSpatialReferenceH hSRS = nullptr;

  const char *pszWKT = GDALGetProjectionRef( hBand );

  if ( pszWKT && strlen( pszWKT ) != 0 )
    hSRS = OSRNewSpatialReference( pszWKT );

  /* -------------------------------------------------------------------- */
  /*      Create the outputfile.                                          */
  /* -------------------------------------------------------------------- */
  OGRDataSourceH hDS;
  OGRSFDriverH hDriver = OGRGetDriverByName( "ESRI Shapefile" );
  OGRFieldDefnH hFld;
  OGRLayerH hLayer;
  int nElevField = -1;

  if ( !hDriver )
  {
    //fprintf( FCGI_stderr, "Unable to find format driver named 'ESRI Shapefile'.\n" );
    delete [] adfFixedLevels;
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a file not available on the server." ) );
  }

  hDS = OGR_Dr_CreateDataSource( hDriver, tmpFileName.toUtf8().constData(), nullptr );
  if ( !hDS )
  {
    delete [] adfFixedLevels;
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request cannot create data source." ) );
  }

  hLayer = OGR_DS_CreateLayer( hDS, "contour", hSRS,
                               /* b3D ? wkbLineString25D : */ wkbLineString,
                               nullptr );
  if ( !hLayer )
  {
    delete [] adfFixedLevels;
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request could not create contour file." ) );
  }

  hFld = OGR_Fld_Create( "ID", OFTInteger );
  OGR_Fld_SetWidth( hFld, 8 );
  OGR_L_CreateField( hLayer, hFld, FALSE );
  OGR_Fld_Destroy( hFld );

  if ( !propertyName.isEmpty() )
  {
    hFld = OGR_Fld_Create( propertyName.toUtf8().constData(), OFTReal );
    OGR_Fld_SetWidth( hFld, 12 );
    OGR_Fld_SetPrecision( hFld, 3 );
    OGR_L_CreateField( hLayer, hFld, FALSE );
    OGR_Fld_Destroy( hFld );
    nElevField = 1;
  }

  /* -------------------------------------------------------------------- */
  /*      Invoke.                                                         */
  /* -------------------------------------------------------------------- */
  GDALContourGenerate( hBand, dfInterval, dfOffset,
                       nFixedLevelCount, adfFixedLevels,
                       bNoDataSet, dfNoData,
                       hLayer, 0, nElevField,
                       GDALTermProgress, nullptr );

  delete [] adfFixedLevels;

  OGR_DS_Destroy( hDS );
  GDALClose( hSrcDS );

  //todo: store those three files elsewhere...
  //mark shp, dbf and shx to delete after the request
  mFilePathsToRemove.push_back( tmpBaseName + ".shp" );
  mFilePathsToRemove.push_back( tmpBaseName + ".dbf" );
  mFilePathsToRemove.push_back( tmpBaseName + ".shx" );

  QgsVectorLayer* contourLayer = new QgsVectorLayer( tmpFileName, QStringLiteral( "layer" ), QStringLiteral( "ogr" ) );

  //create renderer
  QgsFeatureRenderer* theRenderer = rendererFromUserStyle( userStyleElem, contourLayer );
  contourLayer->setRenderer( theRenderer );

  //add labeling if requested
  labelSettingsFromUserStyle( userStyleElem, contourLayer );

  QgsDebugMsg( "Returning the contour layer" );
  return contourLayer;
}
Esempio n. 10
0
QList<QgsMapLayer*> QgsSLDConfigParser::mapLayerFromStyle( const QString& lName, const QString& styleName, bool useCache ) const
{
  QList<QgsMapLayer*> fallbackLayerList;
  QList<QgsMapLayer*> resultList;

  //first check if this layer is a named layer with a user style
  QList<QDomElement> namedLayerElemList = findNamedLayerElements( lName );
  for ( int i = 0; i < namedLayerElemList.size(); ++i )
  {
    QDomElement userStyleElement = findUserStyleElement( namedLayerElemList[i], styleName );
    if ( !userStyleElement.isNull() )
    {
      fallbackLayerList = mFallbackParser->mapLayerFromStyle( lName, QLatin1String( "" ), false );
      if ( !fallbackLayerList.isEmpty() )
      {
        QgsVectorLayer* v = dynamic_cast<QgsVectorLayer*>( fallbackLayerList.at( 0 ) );
        if ( v )
        {
          QgsFeatureRenderer* r = rendererFromUserStyle( userStyleElement, v );
          v->setRenderer( r );
          labelSettingsFromUserStyle( userStyleElement, v );

          resultList.push_back( v );
          return resultList;
        }
        else
        {
          QgsRasterLayer* r = dynamic_cast<QgsRasterLayer*>( fallbackLayerList.at( 0 ) ); //a raster layer?
          if ( r )
          {
            rasterSymbologyFromUserStyle( userStyleElement, r );

            //Using a contour symbolizer, there may be a raster and a vector layer
            QgsVectorLayer* v = contourLayerFromRaster( userStyleElement, r );
            if ( v )
            {
              resultList.push_back( v ); //contour layer must be added before raster
              mLayersToRemove.push_back( v ); //don't cache contour layers at the moment
            }
            resultList.push_back( r );
            return resultList;
          }
        }
      }
    }

    // try with a predefined named style
    QDomElement namedStyleElement = findNamedStyleElement( namedLayerElemList[i], styleName );
    if ( !namedStyleElement.isNull() )
    {
      fallbackLayerList = mFallbackParser->mapLayerFromStyle( lName, styleName, false );
      if ( !fallbackLayerList.isEmpty() )
      {
        resultList << fallbackLayerList;
        return resultList;
      }
    }
  }

  QDomElement userLayerElement = findUserLayerElement( lName );

  if ( userLayerElement.isNull() )
  {
    //maybe named layer and named style is defined in the fallback SLD?
    if ( mFallbackParser )
    {
      resultList = mFallbackParser->mapLayerFromStyle( lName, styleName, useCache );
    }

    return resultList;
  }

  QDomElement userStyleElement = findUserStyleElement( userLayerElement, styleName );

  QgsMapLayer* theMapLayer = mapLayerFromUserLayer( userLayerElement, lName, useCache );
  if ( !theMapLayer )
  {
    return resultList;
  }

  QgsFeatureRenderer* theRenderer = nullptr;

  QgsRasterLayer* theRasterLayer = dynamic_cast<QgsRasterLayer*>( theMapLayer );
  if ( theRasterLayer )
  {
    QgsDebugMsg( "Layer is a rasterLayer" );
    if ( !userStyleElement.isNull() )
    {
      QgsDebugMsg( "Trying to add raster symbology" );
      rasterSymbologyFromUserStyle( userStyleElement, theRasterLayer );
      //todo: possibility to have vector layer or raster layer
      QgsDebugMsg( "Trying to find contour symbolizer" );
      QgsVectorLayer* v = contourLayerFromRaster( userStyleElement, theRasterLayer );
      if ( v )
      {
        QgsDebugMsg( "Returning vector layer" );
        resultList.push_back( v );
        mLayersToRemove.push_back( v );
      }
    }
    resultList.push_back( theMapLayer );

    return resultList;
  }

  QgsVectorLayer* theVectorLayer = dynamic_cast<QgsVectorLayer*>( theMapLayer );
  if ( userStyleElement.isNull() )//apply a default style
  {
    QgsSymbol* symbol = QgsSymbol::defaultSymbol( theVectorLayer->geometryType() );
    theRenderer = new QgsSingleSymbolRenderer( symbol );
  }
  else
  {
    QgsDebugMsg( "Trying to get a renderer from the user style" );
    theRenderer = rendererFromUserStyle( userStyleElement, theVectorLayer );
    //apply labels if <TextSymbolizer> tag is present
    labelSettingsFromUserStyle( userStyleElement, theVectorLayer );
  }

  if ( !theRenderer )
  {
    QgsDebugMsg( "Error, could not create a renderer" );
    delete theVectorLayer;
    return resultList;
  }
  theVectorLayer->setRenderer( theRenderer );
  QgsDebugMsg( "Returning the vectorlayer" );
  resultList.push_back( theVectorLayer );
  return resultList;
}