int main(int argc, char **argv) { // Get data from ogr OGRRegisterAll(); std::cout << "Opening: " << argv[1] << std::endl; OGRDataSource *shp = OGRSFDriverRegistrar::Open(argv[1], FALSE); IsValid(shp, "Error opening file."); std::cout << "Shape contains " << shp->GetLayerCount() << " layers." << std::endl; OGRLayer *layer = shp->GetLayerByName(argv[2]); IsValid(layer, "Couldn't grab layer"); OGRSpatialReference *srcSRS = NULL; srcSRS = layer->GetSpatialRef(); // Set up writing const char *kDriverName = "ESRI Shapefile"; OGRSFDriver *shpDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(kDriverName); IsValid(shpDriver, "Couldn't grab the shapefile driver."); IsValid(argv[3], "Please provide a output shp."); std::cout << "Writing to: " << argv[3] << std::endl; OGRDataSource *shpOut = shpDriver->CreateDataSource(argv[3], NULL); IsValid(shpOut, "Couldn't open output file"); OGRLayer *outLayer = shpOut->CreateLayer(layer->GetName(), srcSRS, wkbMultiLineString, NULL); IsValid(outLayer, "Couldn't create an output layer"); // copy over the fields from the source file OGRFeatureDefn *source = layer->GetLayerDefn(); for(int i=0; i < source->GetFieldCount(); i++){ OGRFieldDefn *field = source->GetFieldDefn(i); if(outLayer->CreateField(field) != OGRERR_NONE) { std::cout << "Couldn't make layer" << std::endl; exit(1); }; } // Loop through features and grab the hull and put it into CGAL then // skeletonize the points OGRFeature *feature; int count = 0; while((feature = layer->GetNextFeature()) != NULL) { OGRMultiPolygon *geometry = dynamic_cast<OGRMultiPolygon *>(OGRGeometryFactory::forceToMultiPolygon(feature->GetGeometryRef())); IsValid(geometry, "No geometry."); OGRFeature *outFeature = OGRFeature::CreateFeature(outLayer->GetLayerDefn()); IsValid(outFeature, "Couldn't make a feature."); for(int i=0; i < source->GetFieldCount(); i++){ OGRField *field = feature->GetRawFieldRef(i); outFeature->SetField(i, field); } OGRGeometry* line = NULL; for(int i=0; i < geometry->getNumGeometries(); i++){ OGRGeometry* segment = BuildMultiLine(geometry->getGeometryRef(i)); if(segment != NULL){ if(line == NULL) { line = new OGRLineString; } OGRGeometry* tmp = line->Union(segment); if(tmp != NULL){ delete line; line = tmp; } delete segment; } } outFeature->SetGeometry(line); if(outLayer->CreateFeature(outFeature) != OGRERR_NONE){ std::cout << "Couldn't create feature." << std::endl; exit(1); } // clean up OGRFeature::DestroyFeature(outFeature); std::cout << std::endl << ++count << std::endl; } // cleanup OGRDataSource::DestroyDataSource(shp); OGRDataSource::DestroyDataSource(shpOut); return 0; }
void init_ogr(const std::string& outfile) { OGRRegisterAll(); const char* driver_name = "SQLite"; OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name); if (driver == NULL) { std::cerr << driver_name << " driver not available.\n"; exit(1); } CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); const char* options[] = { "SPATIALITE=TRUE", NULL }; m_data_source = driver->CreateDataSource(outfile.c_str(), const_cast<char**>(options)); if (m_data_source == NULL) { std::cerr << "Creation of output file failed.\n"; exit(1); } m_layer_point = init_layer("planet_osm_point", m_fields_nodes, wkbPoint); m_layer_line = init_layer("planet_osm_line", m_fields_ways, wkbLineString); m_layer_polygon = init_layer("planet_osm_polygon", m_fields_areas, wkbMultiPolygon); stringv fields_roads; fields_roads.push_back("railway"); fields_roads.push_back("highway"); fields_roads.push_back("boundary"); m_layer_roads = init_layer("planet_osm_roads", fields_roads, wkbLineString); }
OGRDataSourceH OGR_Dr_CreateDataSource( OGRSFDriverH hDriver, const char *pszName, char ** papszOptions ) { VALIDATE_POINTER1( hDriver, "OGR_Dr_CreateDataSource", NULL ); OGRSFDriver* poDriver = (OGRSFDriver *) hDriver; CPLAssert( NULL != poDriver ); OGRDataSource* poDS = NULL; poDS = poDriver->CreateDataSource( pszName, papszOptions ); /* This fix is explained in Ticket #1223 */ if( NULL != poDS ) { poDS->SetDriver( poDriver ); CPLAssert( NULL != poDS->GetDriver() ); } else { CPLDebug( "OGR", "CreateDataSource operation failed. NULL pointer returned." ); } return (OGRDataSourceH) poDS; }
shared_ptr<OGRDataSource> OgrUtilities::createDataSource(QString url) { const char* driverName = NULL; int i = 0; while (extensions[i][0] != NULL) { if (url.endsWith(extensions[i][0])) { driverName = extensions[i][1]; } i++; } i = 0; while (beginName[i][0] != NULL) { if (url.startsWith(beginName[i][0])) { driverName = beginName[i][1]; } i++; } if (driverName == NULL) { throw HootException("No driver found for: " + url); } OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driverName); if (driver == 0) { throw HootException("Error getting driver by name: " + QString(driverName)); } // if the user specifies a shapefile then crop off the .shp and create a directory. if (url.toLower().endsWith(".shp")) { url = url.mid(0, url.length() - 4); } shared_ptr<OGRDataSource> result(driver->CreateDataSource(url.toAscii())); if (result == NULL) { throw HootException("Unable to create data source: " + url + " (" + QString(CPLGetLastErrorMsg()) + ")"); } result->SetDriver(driver); if (QString(driverName) == "FileGDB") { long v = GDAL_VERSION_MAJOR * 1000000 + GDAL_VERSION_MINOR * 1000 + GDAL_VERSION_REV; long lowest = 1 * 1000000 + 10 * 1000 + 1; if (v < lowest) { LOG_WARN("Writing to FileGDB with GDAL v" << GDAL_RELEASE_NAME << ". FileGDB with a GDAL " "v1.9.0 is known to create files that can't be read by ArcMap 10.2. " "GDAL v1.10.1 is known to work."); } } return result; }
int OGRGPSBabelWriteDataSource::Create( const char * pszName, char **papszOptions ) { OGRSFDriver* poGPXDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("GPX"); if (poGPXDriver == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "GPX driver is necessary for GPSBabel write support"); return FALSE; } if (!EQUALN(pszName, "GPSBABEL:", 9)) { const char* pszOptionGPSBabelDriverName = CSLFetchNameValue(papszOptions, "GPSBABEL_DRIVER"); if (pszOptionGPSBabelDriverName != NULL) pszGPSBabelDriverName = CPLStrdup(pszOptionGPSBabelDriverName); else { CPLError(CE_Failure, CPLE_AppDefined, "GPSBABEL_DRIVER dataset creation option expected"); return FALSE; } pszFilename = CPLStrdup(pszName); } else { const char* pszSep = strchr(pszName + 9, ':'); if (pszSep == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Wrong syntax. Expected GPSBabel:driver_name[,options]*:file_name"); return FALSE; } pszGPSBabelDriverName = CPLStrdup(pszName + 9); *(strchr(pszGPSBabelDriverName, ':')) = '\0'; pszFilename = CPLStrdup(pszSep+1); } /* A bit of validation to avoid command line injection */ if (!OGRGPSBabelDataSource::IsValidDriverName(pszGPSBabelDriverName)) return FALSE; const char* pszOptionUseTempFile = CSLFetchNameValue(papszOptions, "USE_TEMPFILE"); if (pszOptionUseTempFile == NULL) pszOptionUseTempFile = CPLGetConfigOption("USE_TEMPFILE", NULL); if (pszOptionUseTempFile && CSLTestBoolean(pszOptionUseTempFile)) osTmpFileName = CPLGenerateTempFilename(NULL); else osTmpFileName.Printf("/vsimem/ogrgpsbabeldatasource_%p", this); poGPXDS = poGPXDriver->CreateDataSource(osTmpFileName.c_str(), papszOptions); if (poGPXDS == NULL) return FALSE; this->pszName = CPLStrdup(pszName); return TRUE; }
bool COGR_DataSource::Create(const CSG_String &File, const CSG_String &DriverName) { OGRSFDriver *pDriver; Destroy(); if( (pDriver = g_OGR_Driver.Get_Driver(DriverName)) != NULL ) { m_pDataSource = pDriver->CreateDataSource(SG_STR_SGTOMB(File), NULL); } return( m_pDataSource != NULL ); }
OGRDataSource * VectorCreate( const char * pszFormat, const char * pszFilename, char ** papszOptions/*=NULL*/ ) { OGRSFDriver * poDriver = GetVectorDriver(pszFormat); OGRDataSource * poOGRDataSource = poDriver->CreateDataSource(pszFilename, papszOptions); #ifdef TRACEON //测试时使用文件型数据库,没有图层时打开有问题,因此在这里放一个图层 //这样才能打开,不用测试可以关闭,在release中没有 poOGRDataSource->CreateLayer("TEMP", NULL, wkbUnknown, NULL); #endif return poOGRDataSource; }
OGRDataSource *AoIIntersection::buildIntersectionDataSource ( const char *outFmt ) { // get driver registrar OGRSFDriverRegistrar *reg = OGRSFDriverRegistrar::GetRegistrar(); // create an OGRDataSource OGRSFDriver *driverToUse = reg->GetDriverByName( outFmt ); if ( driverToUse ) { return( driverToUse->CreateDataSource( "C:\\Minerva\\Data\\intersection.mem", NULL ) ); } return 0; }
JNIEXPORT jlong JNICALL Java_es_gva_cit_jogr_OGRSFDriver_createDataSourceNat (JNIEnv *env, jobject obj, jlong cPtr, jstring pszName){ OGRSFDriver *drv = (OGRSFDriver *) 0 ; drv = *(OGRSFDriver **)&cPtr; OGRDataSource *ds; long ptr_ds; const char *name = env->GetStringUTFChars( pszName, 0); ds = drv->CreateDataSource(name); env->ReleaseStringUTFChars( pszName, name); if(ds==NULL)return -1; ptr_ds = (long)&(*ds); return (jlong)ptr_ds; }
MyOGRHandler(const std::string& filename) : m_data_source(NULL), m_layer_point(NULL), m_filter(true), m_tohstore() { OGRRegisterAll(); OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("PostgreSQL"); if (driver == NULL) { std::cerr << "PostgreSQL OGR driver not available.\n"; exit(1); } // using COPY is much faster than INSERT CPLSetConfigOption("PG_USE_COPY", "YES"); const char* options[] = { NULL }; m_data_source = driver->CreateDataSource(filename.c_str(), const_cast<char**>(options)); if (m_data_source == NULL) { std::cerr << "Database open failed.\n"; exit(1); } // OGR can't create a table with hstore column, so we do it ourselves here OGRLayer* dummy = m_data_source->ExecuteSQL("CREATE TABLE nodes (id VARCHAR, tags hstore);", NULL, NULL); if (dummy) { m_data_source->ReleaseResultSet(dummy); } dummy = m_data_source->ExecuteSQL("SELECT AddGeometryColumn('nodes', 'geom', 4326, 'POINT', 2);", NULL, NULL); if (dummy) { m_data_source->ReleaseResultSet(dummy); } m_layer_point = m_data_source->GetLayerByName("nodes"); if (!m_layer_point) { std::cerr << "Something went wrong setting up the 'nodes' layer.\n"; exit(1); } // using transactions makes this much faster than without m_layer_point->StartTransaction(); m_filter.add(false, "created_by"); m_filter.add(false, "odbl"); }
void output_ogr(const std::string& filename, const std::string& driver_name, const segvec& removed_segments, const segvec& added_segments) { OGRRegisterAll(); OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str()); if (!driver) { std::cerr << driver_name << " driver not available.\n"; exit(return_code_fatal); } //const char* options[] = { "SPATIALITE=yes", "OGR_SQLITE_SYNCHRONOUS=OFF", "INIT_WITH_EPSG=no", nullptr }; const char* options[] = { nullptr }; auto data_source = std::unique_ptr<OGRDataSource, OGRDataSourceDestroyer>(driver->CreateDataSource(filename.c_str(), const_cast<char**>(options))); if (!data_source) { std::cerr << "Creation of output file failed.\n"; exit(return_code_fatal); } SRS srs; auto layer = data_source->CreateLayer("changes", srs.out(), wkbLineString, const_cast<char**>(options)); if (!layer) { std::cerr << "Creating layer 'changes' failed.\n"; exit(return_code_fatal); } OGRFieldDefn field_change("change", OFTInteger); field_change.SetWidth(1); if (layer->CreateField(&field_change) != OGRERR_NONE ) { std::cerr << "Creating field 'change' on 'changes' layer failed.\n"; exit(return_code_fatal); } layer->StartTransaction(); for (const auto& segment : removed_segments) { add_segment(layer, 0, segment); } for (const auto& segment : added_segments) { add_segment(layer, 1, segment); } layer->CommitTransaction(); }
OGRDataSource* initialize_database(const std::string& output_format, const std::string& output_filename) { OGRRegisterAll(); OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(output_format.c_str()); if (!driver) { std::cerr << output_format << " driver not available.\n"; exit(1); } CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); const char* options[] = { "SPATIALITE=TRUE", nullptr }; OGRDataSource* data_source = driver->CreateDataSource(output_filename.c_str(), const_cast<char**>(options)); if (!data_source) { std::cerr << "Creation of output file failed.\n"; exit(1); } return data_source; }
void CDlg_GISDataExchange::ExportToGISFile(LPCTSTR lpszCSVFileName,LPCTSTR lpszShapeFileName, CString GISTypeString ) { #ifndef _WIN64 m_MessageList.ResetContent (); CWaitCursor wait; CCSVParser parser; int i= 0; // open csv file if (parser.OpenCSVFile(lpszCSVFileName)) { CString message_str; OGRSFDriver *poDriver; OGRRegisterAll(); poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(GISTypeString ); if( poDriver == NULL ) { message_str.Format ( "%s driver not available.", GISTypeString ); m_MessageList.AddString (message_str); return; } OGRDataSource *poDS; poDS = poDriver->CreateDataSource(lpszShapeFileName, NULL ); if( poDS == NULL ) { message_str.Format ( "Creation of GIS output file %s failed.\nPlease do not overwrite the exiting file and please select a new file name.", lpszShapeFileName ); m_MessageList.AddString (message_str); return; } ///// export to link layer // link layer OGRLayer *poLayer; poLayer = poDS->CreateLayer( "link", NULL, wkbLineString, NULL ); if( poLayer == NULL ) { m_MessageList.AddString ("link Layer creation failed"); return; } vector<string> HeaderVector = parser.GetHeaderVector(); std::vector <CString> LongFieldVector; for(unsigned int i = 0; i < HeaderVector.size(); i++) { if(HeaderVector[i].find ("geometry") != string::npos|| HeaderVector[i].find ("name") != string::npos || HeaderVector[i].find ("code") != string::npos) { OGRFieldDefn oField (HeaderVector[i].c_str (), OFTString); CString str; if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { str.Format("Creating field %s failed", oField.GetNameRef()); m_MessageList.AddString (str); return; } }else { CString field_string = HeaderVector[i].c_str (); OGRFieldDefn oField (field_string, OFTReal); CString str; if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { str.Format("Creating field %s failed", oField.GetNameRef()); m_MessageList.AddString (str); return; } } if(HeaderVector[i].size()>=11) { LongFieldVector.push_back (HeaderVector[i].c_str ()); } } message_str.Format ("%d fields have been created.",HeaderVector.size()); m_MessageList.AddString (message_str); if(LongFieldVector.size() >=1) { message_str.Format("Warning: Arc GIS file only supports field names with not more than 10 characters.\nThe following fields have long field names. "); m_MessageList.AddString (message_str); for(unsigned l = 0; l< LongFieldVector.size(); l++) { message_str.Format ("%s",LongFieldVector[l]); m_MessageList.AddString (message_str); } } int count = 0 ; while(parser.ReadRecord()) { //create feature OGRFeature *poFeature; poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); //step 1: write all fields except geometry for(unsigned int i = 0; i < HeaderVector.size(); i++) { if(HeaderVector[i]!="geometry") { if(HeaderVector[i].find ("name") != string::npos || HeaderVector[i].find ("code") != string::npos) { std::string str_value; parser.GetValueByFieldName(HeaderVector[i],str_value); // TRACE("field: %s, value = %s\n",HeaderVector[i].c_str (),str_value.c_str ()); poFeature->SetField(i,str_value.c_str ()); }else { double value = 0; parser.GetValueByFieldName(HeaderVector[i],value); // TRACE("field: %s, value = %f\n",HeaderVector[i].c_str (),value); CString field_name = HeaderVector[i].c_str (); poFeature->SetField(i,value); } } } string geo_string; std::vector<CCoordinate> CoordinateVector; if(parser.GetValueByFieldName("geometry",geo_string)) { // overwrite when the field "geometry" exists CGeometry geometry(geo_string); CoordinateVector = geometry.GetCoordinateList(); if( m_GIS_data_type == GIS_Point_Type && CoordinateVector.size ()==1) { OGRPoint pt; pt.setX( CoordinateVector[0].X ); pt.setY( CoordinateVector[0].Y); poFeature->SetGeometry( &pt ); } if( m_GIS_data_type == GIS_Line_Type) { OGRLineString line; for(unsigned int si = 0; si< CoordinateVector.size(); si++) { line.addPoint (CoordinateVector[si].X , CoordinateVector[si].Y); } poFeature->SetGeometry( &line ); } if( m_GIS_data_type == GIS_Polygon_Type) { OGRPolygon polygon; OGRLinearRing ring; for(unsigned int si = 0; si< CoordinateVector.size(); si++) { ring.addPoint (CoordinateVector[si].X , CoordinateVector[si].Y,1); } polygon.addRing(&ring); poFeature->SetGeometry( &polygon ); } } else { // no geometry field /// create geometry data from m_GIS_data_type == GIS_Point_Type if( m_GIS_data_type == GIS_Point_Type ) { double x, y; if(parser.GetValueByFieldName("x",x) && parser.GetValueByFieldName("y",y) ) { OGRPoint pt; pt.setX( CoordinateVector[0].X ); pt.setY( CoordinateVector[0].Y); poFeature->SetGeometry( &pt ); }else { AfxMessageBox("Pleaes prepare fields x and y in the csv file in order to create a node GIS layer.", MB_ICONINFORMATION); return; } } ///create geometry if( m_GIS_data_type == GIS_Line_Type) { int number_of_shape_points = 0; if(parser.GetValueByFieldName("number_of_shape_points", number_of_shape_points)) { if(number_of_shape_points>=2) { OGRLineString line; for(int s= 1; s<= number_of_shape_points; s++) { CString str_x, str_y; str_x.Format ("x%d",s); str_y.Format ("y%d",s); double x = 0; double y = 0; string string_x, string_y; string_x = m_pDoc->CString2StdString (str_x); string_y = m_pDoc->CString2StdString (str_y); if(parser.GetValueByFieldName(string_x, x) && parser.GetValueByFieldName(string_y, y)) { line.addPoint(x,y); }else { AfxMessageBox("Pleaes prepare fields x1,y1,x2,y2,...,xn,yn in the csv file in order to create a link GIS layer.", MB_ICONINFORMATION); return; } } poFeature->SetGeometry( &line ); } }else { AfxMessageBox("Pleaes prepare fields number_of_shape_points, x1,y1,x2,y2,...,xn,yn in the csv file in order to create a link GIS layer.", MB_ICONINFORMATION); return; } } // if( m_GIS_data_type == GIS_Polygon_Type) { OGRPolygon polygon; OGRLinearRing ring; int number_of_shape_points = 0; if(parser.GetValueByFieldName("number_of_shape_points", number_of_shape_points)) { if(number_of_shape_points>=2) { OGRLineString line; for(int s= 0; s< number_of_shape_points; s++) { CString str_x, str_y; str_x.Format ("x%d",str_x); str_y.Format ("y%d",str_y); double x = 0; double y = 0; string string_x, string_y; string_x = m_pDoc->CString2StdString (str_x); string_y = m_pDoc->CString2StdString (str_y); if(parser.GetValueByFieldName(string_x, x) && parser.GetValueByFieldName(string_y, y)) { ring.addPoint (x,y,1); }else { AfxMessageBox("Pleaes prepare fields x1,y1,x2,y2,...,xn,yn in the csv file in order to create a zone GIS layer.", MB_ICONINFORMATION); return; } } polygon.addRing(&ring); poFeature->SetGeometry( &polygon ); } } } } if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE ) { AfxMessageBox("Failed to create line feature in shapefile.\n"); return; } OGRFeature::DestroyFeature( poFeature ); count++; } message_str.Format ("%d records have been created.",count); m_MessageList.AddString (message_str); OGRDataSource::DestroyDataSource( poDS ); CString ShapeFile = lpszShapeFileName; CString ShapeFileFolder = ShapeFile.Left(ShapeFile.ReverseFind('\\') + 1); ShellExecute( NULL, "explore", ShapeFileFolder, NULL, NULL, SW_SHOWNORMAL ); } #endif }
int main(int argc, char *argv[]) { LogPolicy::GetInstance().Unmute(); try { // enable logging if (argc < 3) { SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " <osrm> <osrm.restrictions>"; return -1; } SimpleLogger().Write() << "Using restrictions from file: " << argv[2]; std::ifstream restriction_ifstream(argv[2], std::ios::binary); const FingerPrint fingerprint_orig; FingerPrint fingerprint_loaded; restriction_ifstream.read((char *)&fingerprint_loaded, sizeof(FingerPrint)); // check fingerprint and warn if necessary if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig)) { SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. " "Reprocess to get rid of this warning."; } if (!restriction_ifstream.good()) { throw osrm::exception("Could not access <osrm-restrictions> files"); } uint32_t usable_restrictions = 0; restriction_ifstream.read((char *)&usable_restrictions, sizeof(uint32_t)); restriction_list.resize(usable_restrictions); // load restrictions if (usable_restrictions > 0) { restriction_ifstream.read((char *)&(restriction_list[0]), usable_restrictions * sizeof(TurnRestriction)); } restriction_ifstream.close(); std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary); if (!input_stream.is_open()) { throw osrm::exception("Cannot open osrm file"); } // load graph data std::vector<ImportEdge> edge_list; const NodeID number_of_nodes = readBinaryOSRMGraphFromStream(input_stream, edge_list, bollard_node_list, traffic_lights_list, &coordinate_list, restriction_list); input_stream.close(); BOOST_ASSERT_MSG(restriction_list.size() == usable_restrictions, "size of restriction_list changed"); SimpleLogger().Write() << restriction_list.size() << " restrictions, " << bollard_node_list.size() << " bollard nodes, " << traffic_lights_list.size() << " traffic lights"; traffic_lights_list.clear(); traffic_lights_list.shrink_to_fit(); // Building an node-based graph DeallocatingVector<TarjanEdge> graph_edge_list; for (const NodeBasedEdge &input_edge : edge_list) { if (input_edge.source == input_edge.target) { continue; } if (input_edge.forward) { graph_edge_list.emplace_back(input_edge.source, input_edge.target, (std::max)((int)input_edge.weight, 1), input_edge.name_id); } if (input_edge.backward) { graph_edge_list.emplace_back(input_edge.target, input_edge.source, (std::max)((int)input_edge.weight, 1), input_edge.name_id); } } edge_list.clear(); edge_list.shrink_to_fit(); BOOST_ASSERT_MSG(0 == edge_list.size() && 0 == edge_list.capacity(), "input edge vector not properly deallocated"); tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); auto graph = std::make_shared<TarjanDynamicGraph>(number_of_nodes, graph_edge_list); edge_list.clear(); edge_list.shrink_to_fit(); SimpleLogger().Write() << "Starting SCC graph traversal"; RestrictionMap restriction_map(restriction_list); auto tarjan = osrm::make_unique<TarjanSCC<TarjanDynamicGraph>>(graph, restriction_map, bollard_node_list); tarjan->run(); SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() << " many components"; SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " SCCs of size 1"; // output TIMER_START(SCC_RUN_SETUP); // remove files from previous run if exist DeleteFileIfExists("component.dbf"); DeleteFileIfExists("component.shx"); DeleteFileIfExists("component.shp"); Percent p(graph->GetNumberOfNodes()); OGRRegisterAll(); const char *pszDriverName = "ESRI Shapefile"; OGRSFDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if (nullptr == poDriver) { throw osrm::exception("ESRI Shapefile driver not available"); } OGRDataSource *poDS = poDriver->CreateDataSource("component.shp", nullptr); if (nullptr == poDS) { throw osrm::exception("Creation of output file failed"); } OGRSpatialReference *poSRS = new OGRSpatialReference(); poSRS->importFromEPSG(4326); OGRLayer *poLayer = poDS->CreateLayer("component", poSRS, wkbLineString, nullptr); if (nullptr == poLayer) { throw osrm::exception("Layer creation failed."); } TIMER_STOP(SCC_RUN_SETUP); SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP)/1000. << "s"; uint64_t total_network_distance = 0; p.reinit(graph->GetNumberOfNodes()); TIMER_START(SCC_OUTPUT); for (const NodeID source : osrm::irange(0u, graph->GetNumberOfNodes())) { p.printIncrement(); for (const auto current_edge : graph->GetAdjacentEdgeRange(source)) { const TarjanDynamicGraph::NodeIterator target = graph->GetTarget(current_edge); if (source < target || graph->EndEdges(target) == graph->FindEdge(target, source)) { total_network_distance += 100 * FixedPointCoordinate::ApproximateEuclideanDistance( coordinate_list[source].lat, coordinate_list[source].lon, coordinate_list[target].lat, coordinate_list[target].lon); BOOST_ASSERT(current_edge != SPECIAL_EDGEID); BOOST_ASSERT(source != SPECIAL_NODEID); BOOST_ASSERT(target != SPECIAL_NODEID); const unsigned size_of_containing_component = std::min(tarjan->get_component_size(source), tarjan->get_component_size(target)); // edges that end on bollard nodes may actually be in two distinct components if (size_of_containing_component < 1000) { OGRLineString lineString; lineString.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION, coordinate_list[source].lat / COORDINATE_PRECISION); lineString.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION, coordinate_list[target].lat / COORDINATE_PRECISION); OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn()); poFeature->SetGeometry(&lineString); if (OGRERR_NONE != poLayer->CreateFeature(poFeature)) { throw osrm::exception("Failed to create feature in shapefile."); } OGRFeature::DestroyFeature(poFeature); } } } } OGRSpatialReference::DestroySpatialReference(poSRS); OGRDataSource::DestroyDataSource(poDS); TIMER_STOP(SCC_OUTPUT); SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT)/1000. << "s"; SimpleLogger().Write() << "total network distance: " << (uint64_t)total_network_distance / 100 / 1000. << " km"; SimpleLogger().Write() << "finished component analysis"; } catch (const std::exception &e) { SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); } return 0; }
void writePolygons(RegionMap* regionMap) { char* driverName = (char *)ogrDriver->c_str(); char* outFilePath = (char *)outFile->c_str(); cout << "Creating output file \"" << outFilePath << "\" (\"" << driverName << "\" format)..."; OGRSFDriver* driver = (OGRSFDriver*)OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(ogrDriver->c_str()); if (driver == NULL) { localExit(new string(string("FATAL: OGR driver \"") + string(driverName) + string("\" is not available.\n")), 1); } char* dataSourceName = NULL; bool cleanupDataSource = false; if (ogrDriver->compare("KML") == 0 && kmlStyleFile != NULL) { dataSourceName = tmpnam(NULL); //mkstemp(dataSourceName); cleanupDataSource = true; } else if (ogrDriver->compare("ESRI Shapefile") == 0) { string* dsStr = removeFromLastOccurrence(outFilePath, '/'); dsStr = removeFromLastOccurrence((char *)dsStr->c_str(), '\\'); dataSourceName = (char *)dsStr->c_str(); } else { dataSourceName = outFilePath; } OGRDataSource* ds = driver->CreateDataSource(dataSourceName); if(ds == NULL) { localExit(new string(string("FATAL: Unable to create output file \"") + string(outFilePath) + string("\"\n")), 1); } cout << "[ok]\n"; OGRCoordinateTransformation* transform = NULL; const string* rmSpatialRefStr = regionMap->getSpatialRef(); if (rmSpatialRefStr != NULL && rmSpatialRefStr->compare("") != 0) { OGRSpatialReference* spatialRef = new OGRSpatialReference(rmSpatialRefStr->c_str()); transform = OGRCreateCoordinateTransformation(spatialRef, outSpatialRef); } char* layerName = (char *)pointToFilename(outFilePath, true)->c_str(); OGRLayer* layer = ds->CreateLayer(layerName, outSpatialRef, wkbPolygon); layer->CreateField(new OGRFieldDefn("RegionID", OFTInteger), 0); layer->CreateField(new OGRFieldDefn("Category", OFTString), 0); layer->CreateField(new OGRFieldDefn("Threshold", OFTReal), 0); cout << "Writing polygon data to file..."; int count = 0; int currRegionID = 0; int numRegions = regionMap->getNumRegions(); while (currRegionID < numRegions) { Region *currRegion = regionMap->getRegion(currRegionID); Polygon* poly = currRegion->toPolygon(); if(poly == NULL) { currRegionID += 1; continue; } count++; OGRFeature* feature = new OGRFeature(layer->GetLayerDefn()); feature->SetField(feature->GetFieldIndex("RegionID"), currRegionID); feature->SetField(feature->GetFieldIndex("Category"), currRegion->getCategory()->getName()->c_str()); feature->SetField(feature->GetFieldIndex("Threshold"), currRegion->getCategory()->minThreshold()); OGRGeometry* geom = BuildOgrPolygon(poly, transform); feature->SetGeometry(geom); if (layer->CreateFeature(feature) != OGRERR_NONE) localExit(new string("ERROR: Unable to create feature for region #\n"), 2); //OGRFeature::DestroyFeature(feature); currRegionID += 1; if (currRegionID % 100 == 0) cout << "."; } //CPLFree(transform); //CPLFree(layer); OGRDataSource::DestroyDataSource(ds); cout << "[ok] Wrote "<< count << " polygons\n"; if(kmlStyleFile != NULL) { #ifdef USE_XALAN XALAN_USING_XERCES(XMLPlatformUtils) XALAN_USING_XALAN(XalanTransformer) XMLPlatformUtils::Initialize(); XalanTransformer::initialize(); XalanTransformer theXalanTransformer; cout << "Transforing KML file ..." << outFile->c_str(); if(theXalanTransformer.transform(dataSourceName, kmlStyleFile->c_str(), outFile->c_str()) != 0) { cout << "[!!]\n"; cout << "ERROR doing XSLT transform using " << kmlStyleFile->c_str() << "\n"; } else { cout << "...[ok]\n"; } #endif /* USE_XALAN */ #ifdef USE_LIBXSLT xsltStylesheetPtr cur = NULL; xmlDocPtr doc, res; const char *params[16 + 1]; params[0] = NULL; xmlSubstituteEntitiesDefault(1); xmlLoadExtDtdDefaultValue = 1; cur = xsltParseStylesheetFile((const xmlChar *) kmlStyleFile->c_str()); doc = xmlParseFile(dataSourceName); res = xsltApplyStylesheet(cur, doc, params); FILE* f = fopen(outFile->c_str(), "w"); xsltSaveResultToFile(f, res, cur); fclose(f); xsltFreeStylesheet(cur); xmlFreeDoc(res); xmlFreeDoc(doc); xsltCleanupGlobals(); xmlCleanupParser(); #endif /* USE_LIBXSLT */ } if(cleanupDataSource) { if(!remove(dataSourceName)) { fprintf(stderr, "Error deleting temporary file: %s\n", dataSourceName); } } }
// export bool ImportExportGdal::export_(const QList<Feature *>& featList) { const char *pszDriverName = "SQLite"; OGRSFDriver *poDriver; OGRRegisterAll(); poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if( poDriver == NULL ) { qDebug( "%s driver not available.", pszDriverName ); return false; } OGRDataSource *poDS; QFile::remove(QString(HOMEDIR + "/test.sqlite")); poDS = poDriver->CreateDataSource( QString(HOMEDIR + "/test.sqlite").toUtf8().constData(), NULL ); if( poDS == NULL ) { qDebug( "Creation of output file failed." ); return false; } poDS->ExecuteSQL("PRAGMA synchronous = OFF", NULL, NULL); OGRSpatialReference *poSRS; poSRS = new OGRSpatialReference(); poSRS->importFromEPSG(4326); char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "SPATIALITE", "YES" ); papszOptions = CSLSetNameValue( papszOptions, "FORMAT", "SPATIALITE" ); papszOptions = CSLSetNameValue( papszOptions, "SPATIAL_INDEX", "YES" ); OGRLayer *poLayer; poLayer = poDS->CreateLayer( "osm", poSRS, wkbUnknown, papszOptions); CSLDestroy( papszOptions ); if( poLayer == NULL ) { qDebug( "Layer creation failed." ); return false; } OGRFieldDefn oField("osm_id", OFTReal); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { qDebug( "Creating field failed." ); return false; } oField.Set("osm_version", OFTInteger ); poLayer->CreateField( &oField ); oField.Set("osm_timestamp", OFTInteger ); poLayer->CreateField( &oField ); OGRFeature *poFeature; foreach (Feature* F, featList) { poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); poFeature->SetField( "osm_id", (qreal)(F->id().numId)); #ifndef FRISIUS_BUILD poFeature->SetField( "osm_version", F->versionNumber()); poFeature->SetField( "osm_timestamp", (int)F->time().toTime_t()); #endif if (CHECK_NODE(F)) { Node* N = STATIC_CAST_NODE(F); OGRPoint pt; pt.setX(N->position().x()); pt.setY(N->position().y()); poFeature->SetGeometry( &pt ); } else if (CHECK_WAY(F)) { Way* W = STATIC_CAST_WAY(F); OGRLineString ls; ls.setNumPoints(W->size()); for (int i=0; i<W->size(); ++i) { ls.setPoint(i, W->getNode(i)->position().x(), W->getNode(i)->position().y(), 0); } poFeature->SetGeometry( &ls ); } if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE ) { qDebug( "Failed to create feature in output." ); return false; } OGRFeature::DestroyFeature( poFeature ); }
int main( int nArgc, char ** papszArgv ) { int nFirstSourceDataset = -1, bLayersWildcarded = TRUE, iArg; const char *pszFormat = "ESRI Shapefile"; const char *pszTileIndexField = "LOCATION"; const char *pszOutputName = NULL; int write_absolute_path = FALSE; int skip_different_projection = FALSE; char* current_path = NULL; int accept_different_schemas = FALSE; int bFirstWarningForNonMatchingAttributes = TRUE; /* Check strict compilation and runtime library version as we use C++ API */ if (! GDAL_CHECK_VERSION(papszArgv[0])) exit(1); /* -------------------------------------------------------------------- */ /* Register format(s). */ /* -------------------------------------------------------------------- */ OGRRegisterAll(); /* -------------------------------------------------------------------- */ /* Processing command line arguments. */ /* -------------------------------------------------------------------- */ for( iArg = 1; iArg < nArgc; iArg++ ) { if( EQUAL(papszArgv[iArg], "--utility_version") ) { printf("%s was compiled against GDAL %s and is running against GDAL %s\n", papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME")); return 0; } else if( EQUAL(papszArgv[iArg],"-f") && iArg < nArgc-1 ) { pszFormat = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-write_absolute_path")) { write_absolute_path = TRUE; } else if( EQUAL(papszArgv[iArg],"-skip_different_projection")) { skip_different_projection = TRUE; } else if( EQUAL(papszArgv[iArg],"-accept_different_schemas")) { accept_different_schemas = TRUE; } else if( EQUAL(papszArgv[iArg],"-tileindex") && iArg < nArgc-1 ) { pszTileIndexField = papszArgv[++iArg]; } else if( EQUAL(papszArgv[iArg],"-lnum") || EQUAL(papszArgv[iArg],"-lname") ) { iArg++; bLayersWildcarded = FALSE; } else if( papszArgv[iArg][0] == '-' ) Usage(); else if( pszOutputName == NULL ) pszOutputName = papszArgv[iArg]; else if( nFirstSourceDataset == -1 ) nFirstSourceDataset = iArg; } if( pszOutputName == NULL || nFirstSourceDataset == -1 ) Usage(); /* -------------------------------------------------------------------- */ /* Try to open as an existing dataset for update access. */ /* -------------------------------------------------------------------- */ OGRDataSource *poDstDS; OGRLayer *poDstLayer = NULL; poDstDS = OGRSFDriverRegistrar::Open( pszOutputName, TRUE ); /* -------------------------------------------------------------------- */ /* If that failed, find the driver so we can create the tile index.*/ /* -------------------------------------------------------------------- */ if( poDstDS == NULL ) { OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar(); OGRSFDriver *poDriver = NULL; int iDriver; for( iDriver = 0; iDriver < poR->GetDriverCount() && poDriver == NULL; iDriver++ ) { if( EQUAL(poR->GetDriver(iDriver)->GetName(),pszFormat) ) { poDriver = poR->GetDriver(iDriver); } } if( poDriver == NULL ) { fprintf( stderr, "Unable to find driver `%s'.\n", pszFormat ); fprintf( stderr, "The following drivers are available:\n" ); for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ ) { fprintf( stderr, " -> `%s'\n", poR->GetDriver(iDriver)->GetName() ); } exit( 1 ); } if( !poDriver->TestCapability( ODrCCreateDataSource ) ) { fprintf( stderr, "%s driver does not support data source creation.\n", pszFormat ); exit( 1 ); } /* -------------------------------------------------------------------- */ /* Now create it. */ /* -------------------------------------------------------------------- */ poDstDS = poDriver->CreateDataSource( pszOutputName, NULL ); if( poDstDS == NULL ) { fprintf( stderr, "%s driver failed to create %s\n", pszFormat, pszOutputName ); exit( 1 ); } if( poDstDS->GetLayerCount() == 0 ) { OGRFieldDefn oLocation( pszTileIndexField, OFTString ); oLocation.SetWidth( 200 ); if( nFirstSourceDataset < nArgc && papszArgv[nFirstSourceDataset][0] == '-' ) { nFirstSourceDataset++; } OGRSpatialReference* poSrcSpatialRef = NULL; /* Fetches the SRS of the first layer and use it when creating the tileindex layer */ if (nFirstSourceDataset < nArgc) { OGRDataSource* poDS = OGRSFDriverRegistrar::Open( papszArgv[nFirstSourceDataset], FALSE ); if (poDS) { int iLayer; for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { int bRequested = bLayersWildcarded; OGRLayer *poLayer = poDS->GetLayer(iLayer); for( iArg = 1; iArg < nArgc && !bRequested; iArg++ ) { if( EQUAL(papszArgv[iArg],"-lnum") && atoi(papszArgv[iArg+1]) == iLayer ) bRequested = TRUE; else if( EQUAL(papszArgv[iArg],"-lname") && EQUAL(papszArgv[iArg+1], poLayer->GetLayerDefn()->GetName()) ) bRequested = TRUE; } if( !bRequested ) continue; if ( poLayer->GetSpatialRef() ) poSrcSpatialRef = poLayer->GetSpatialRef()->Clone(); break; } } OGRDataSource::DestroyDataSource( poDS ); } poDstLayer = poDstDS->CreateLayer( "tileindex", poSrcSpatialRef ); poDstLayer->CreateField( &oLocation, OFTString ); OGRSpatialReference::DestroySpatialReference( poSrcSpatialRef ); } } /* -------------------------------------------------------------------- */ /* Identify target layer and field. */ /* -------------------------------------------------------------------- */ int iTileIndexField; poDstLayer = poDstDS->GetLayer(0); if( poDstLayer == NULL ) { fprintf( stderr, "Can't find any layer in output tileindex!\n" ); exit( 1 ); } iTileIndexField = poDstLayer->GetLayerDefn()->GetFieldIndex( pszTileIndexField ); if( iTileIndexField == -1 ) { fprintf( stderr, "Can't find %s field in tile index dataset.\n", pszTileIndexField ); exit( 1 ); } OGRFeatureDefn* poFeatureDefn = NULL; /* Load in memory existing file names in SHP */ int nExistingLayers = 0; char** existingLayersTab = NULL; OGRSpatialReference* alreadyExistingSpatialRef = NULL; int alreadyExistingSpatialRefValid = FALSE; nExistingLayers = poDstLayer->GetFeatureCount(); if (nExistingLayers) { int i; existingLayersTab = (char**)CPLMalloc(nExistingLayers * sizeof(char*)); for(i=0;i<nExistingLayers;i++) { OGRFeature* feature = poDstLayer->GetNextFeature(); existingLayersTab[i] = CPLStrdup(feature->GetFieldAsString( iTileIndexField)); if (i == 0) { OGRDataSource *poDS; char* filename = CPLStrdup(existingLayersTab[i]); int j; for(j=strlen(filename)-1;j>=0;j--) { if (filename[j] == ',') break; } if (j >= 0) { int iLayer = atoi(filename + j + 1); filename[j] = 0; poDS = OGRSFDriverRegistrar::Open(filename, FALSE ); if (poDS) { OGRLayer *poLayer = poDS->GetLayer(iLayer); if (poLayer) { alreadyExistingSpatialRefValid = TRUE; alreadyExistingSpatialRef = (poLayer->GetSpatialRef()) ? poLayer->GetSpatialRef()->Clone() : NULL; if (poFeatureDefn == NULL) poFeatureDefn = poLayer->GetLayerDefn()->Clone(); } OGRDataSource::DestroyDataSource( poDS ); } } } } } if (write_absolute_path) { current_path = CPLGetCurrentDir(); if (current_path == NULL) { fprintf( stderr, "This system does not support the CPLGetCurrentDir call. " "The option -write_absolute_path will have no effect\n"); write_absolute_path = FALSE; } } /* ==================================================================== */ /* Process each input datasource in turn. */ /* ==================================================================== */ for(; nFirstSourceDataset < nArgc; nFirstSourceDataset++ ) { int i; OGRDataSource *poDS; if( papszArgv[nFirstSourceDataset][0] == '-' ) { nFirstSourceDataset++; continue; } char* fileNameToWrite; VSIStatBuf sStatBuf; if (write_absolute_path && CPLIsFilenameRelative( papszArgv[nFirstSourceDataset] ) && VSIStat( papszArgv[nFirstSourceDataset], &sStatBuf ) == 0) { fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path,papszArgv[nFirstSourceDataset])); } else { fileNameToWrite = CPLStrdup(papszArgv[nFirstSourceDataset]); } poDS = OGRSFDriverRegistrar::Open( papszArgv[nFirstSourceDataset], FALSE ); if( poDS == NULL ) { fprintf( stderr, "Failed to open dataset %s, skipping.\n", papszArgv[nFirstSourceDataset] ); CPLFree(fileNameToWrite); continue; } /* -------------------------------------------------------------------- */ /* Check all layers, and see if they match requests. */ /* -------------------------------------------------------------------- */ int iLayer; for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ ) { int bRequested = bLayersWildcarded; OGRLayer *poLayer = poDS->GetLayer(iLayer); for( iArg = 1; iArg < nArgc && !bRequested; iArg++ ) { if( EQUAL(papszArgv[iArg],"-lnum") && atoi(papszArgv[iArg+1]) == iLayer ) bRequested = TRUE; else if( EQUAL(papszArgv[iArg],"-lname") && EQUAL(papszArgv[iArg+1], poLayer->GetLayerDefn()->GetName()) ) bRequested = TRUE; } if( !bRequested ) continue; /* Checks that the layer is not already in tileindex */ for(i=0;i<nExistingLayers;i++) { char szLocation[5000]; sprintf( szLocation, "%s,%d", fileNameToWrite, iLayer ); if (EQUAL(szLocation, existingLayersTab[i])) { fprintf(stderr, "Layer %d of %s is already in tileindex. Skipping it.\n", iLayer, papszArgv[nFirstSourceDataset]); break; } } if (i != nExistingLayers) { continue; } OGRSpatialReference* spatialRef = poLayer->GetSpatialRef(); if (alreadyExistingSpatialRefValid) { if ((spatialRef != NULL && alreadyExistingSpatialRef != NULL && spatialRef->IsSame(alreadyExistingSpatialRef) == FALSE) || ((spatialRef != NULL) != (alreadyExistingSpatialRef != NULL))) { fprintf(stderr, "Warning : layer %d of %s is not using the same projection system as " "other files in the tileindex. This may cause problems when " "using it in MapServer for example.%s\n", iLayer, papszArgv[nFirstSourceDataset], (skip_different_projection) ? " Skipping it" : ""); if (skip_different_projection) { continue; } } } else { alreadyExistingSpatialRefValid = TRUE; alreadyExistingSpatialRef = (spatialRef) ? spatialRef->Clone() : NULL; } /* -------------------------------------------------------------------- */ /* Check if all layers in dataset have the same attributes schema. */ /* -------------------------------------------------------------------- */ if( poFeatureDefn == NULL ) { poFeatureDefn = poLayer->GetLayerDefn()->Clone(); } else if ( !accept_different_schemas ) { OGRFeatureDefn* poFeatureDefnCur = poLayer->GetLayerDefn(); assert(NULL != poFeatureDefnCur); int fieldCount = poFeatureDefnCur->GetFieldCount(); if( fieldCount != poFeatureDefn->GetFieldCount()) { fprintf( stderr, "Number of attributes of layer %s of %s does not match ... skipping it.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]); if (bFirstWarningForNonMatchingAttributes) { fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n" "but this may result in a tileindex incompatible with MapServer\n"); bFirstWarningForNonMatchingAttributes = FALSE; } continue; } int bSkip = FALSE; for( int fn = 0; fn < poFeatureDefnCur->GetFieldCount(); fn++ ) { OGRFieldDefn* poField = poFeatureDefn->GetFieldDefn(fn); OGRFieldDefn* poFieldCur = poFeatureDefnCur->GetFieldDefn(fn); /* XXX - Should those pointers be checked against NULL? */ assert(NULL != poField); assert(NULL != poFieldCur); if( poField->GetType() != poFieldCur->GetType() || poField->GetWidth() != poFieldCur->GetWidth() || poField->GetPrecision() != poFieldCur->GetPrecision() || !EQUAL( poField->GetNameRef(), poFieldCur->GetNameRef() ) ) { fprintf( stderr, "Schema of attributes of layer %s of %s does not match ... skipping it.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]); if (bFirstWarningForNonMatchingAttributes) { fprintf( stderr, "Note : you can override this behaviour with -accept_different_schemas option\n" "but this may result in a tileindex incompatible with MapServer\n"); bFirstWarningForNonMatchingAttributes = FALSE; } bSkip = TRUE; break; } } if (bSkip) continue; } /* -------------------------------------------------------------------- */ /* Get layer extents, and create a corresponding polygon */ /* geometry. */ /* -------------------------------------------------------------------- */ OGREnvelope sExtents; OGRPolygon oRegion; OGRLinearRing oRing; if( poLayer->GetExtent( &sExtents, TRUE ) != OGRERR_NONE ) { fprintf( stderr, "GetExtent() failed on layer %s of %s, skipping.\n", poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset] ); continue; } oRing.addPoint( sExtents.MinX, sExtents.MinY ); oRing.addPoint( sExtents.MinX, sExtents.MaxY ); oRing.addPoint( sExtents.MaxX, sExtents.MaxY ); oRing.addPoint( sExtents.MaxX, sExtents.MinY ); oRing.addPoint( sExtents.MinX, sExtents.MinY ); oRegion.addRing( &oRing ); /* -------------------------------------------------------------------- */ /* Add layer to tileindex. */ /* -------------------------------------------------------------------- */ char szLocation[5000]; OGRFeature oTileFeat( poDstLayer->GetLayerDefn() ); sprintf( szLocation, "%s,%d", fileNameToWrite, iLayer ); oTileFeat.SetGeometry( &oRegion ); oTileFeat.SetField( iTileIndexField, szLocation ); if( poDstLayer->CreateFeature( &oTileFeat ) != OGRERR_NONE ) { fprintf( stderr, "Failed to create feature on tile index ... terminating." ); OGRDataSource::DestroyDataSource( poDstDS ); exit( 1 ); } } /* -------------------------------------------------------------------- */ /* Cleanup this data source. */ /* -------------------------------------------------------------------- */ CPLFree(fileNameToWrite); OGRDataSource::DestroyDataSource( poDS ); } /* -------------------------------------------------------------------- */ /* Close tile index and clear buffers. */ /* -------------------------------------------------------------------- */ OGRDataSource::DestroyDataSource( poDstDS ); OGRFeatureDefn::DestroyFeatureDefn( poFeatureDefn ); if (alreadyExistingSpatialRef != NULL) OGRSpatialReference::DestroySpatialReference( alreadyExistingSpatialRef ); CPLFree(current_path); if (nExistingLayers) { int i; for(i=0;i<nExistingLayers;i++) { CPLFree(existingLayersTab[i]); } CPLFree(existingLayersTab); } return 0; }
void ShapefileWriter::writePolygons(shared_ptr<const OsmMap> map, const QString& path) { OGRRegisterAll(); _removeShapefile(path); const char *pszDriverName = "ESRI Shapefile"; OGRSFDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if( poDriver == NULL ) { throw HootException(QString("%1 driver not available.").arg(pszDriverName)); } OGRDataSource* poDS = poDriver->CreateDataSource(path.toAscii(), NULL ); if( poDS == NULL ) { throw HootException(QString("Data source creation failed. %1").arg(path)); } OgrOptions options; options["ENCODING"] = "UTF-8"; OGRLayer *poLayer; QString layerName; layerName = QFileInfo(path).baseName(); poLayer = poDS->CreateLayer(layerName.toAscii(), map->getProjection().get(), wkbMultiPolygon, options.getCrypticOptions()); if( poLayer == NULL ) { throw HootException(QString("Layer creation failed. %1").arg(path)); } QStringList shpColumns; QStringList columns = getColumns(map, ElementType::Unknown); for (int i = 0; i < columns.size(); i++) { OGRFieldDefn oField(columns[i].toAscii(), OFTString); oField.SetWidth(64); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { throw HootException(QString("Error creating field (%1).").arg(columns[i])); } shpColumns.append(poLayer->GetLayerDefn()->GetFieldDefn(i)->GetNameRef()); } if (_includeInfo) { OGRFieldDefn oField("error_circ", OFTReal); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { throw HootException(QString("Error creating field (error:circular).")); } _circularErrorIndex = poLayer->GetLayerDefn()->GetFieldCount() - 1; } const WayMap& ways = map->getWays(); for (WayMap::const_iterator it = ways.begin(); it != ways.end(); it++) { shared_ptr<Way> way = it->second; if (OsmSchema::getInstance().isArea(way)) { _writeWayPolygon(map, way, poLayer, columns, shpColumns); } } const RelationMap& relations = map->getRelationMap(); for (RelationMap::const_iterator it = relations.begin(); it != relations.end(); it++) { shared_ptr<Relation> relation = it->second; if (relation->isMultiPolygon()) { _writeRelationPolygon(map, relation, poLayer, columns, shpColumns); } } OGRDataSource::DestroyDataSource(poDS); }
void ShapefileWriter::writePoints(shared_ptr<const OsmMap> map, const QString& path) { OGRRegisterAll(); _removeShapefile(path); const char *pszDriverName = "ESRI Shapefile"; OGRSFDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if( poDriver == NULL ) { throw HootException(QString("%1 driver not available.").arg(pszDriverName)); } OGRDataSource* poDS = poDriver->CreateDataSource(path.toAscii(), NULL ); if( poDS == NULL ) { throw HootException(QString("Data source creation failed. %1").arg(path)); } OgrOptions options; options["ENCODING"] = "UTF-8"; OGRLayer *poLayer; QString layerName; layerName = QFileInfo(path).baseName(); poLayer = poDS->CreateLayer(layerName.toAscii(), map->getProjection().get(), wkbPoint, options.getCrypticOptions()); if( poLayer == NULL ) { throw HootException(QString("Layer creation failed. %1").arg(path)); } QStringList shpColumns; QStringList columns = getColumns(map, ElementType::Node); for (int i = 0; i < columns.size(); i++) { OGRFieldDefn oField(columns[i].toAscii(), OFTString); oField.SetWidth(64); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { throw HootException(QString("Error creating field (%1).").arg(columns[i])); } shpColumns.append(poLayer->GetLayerDefn()->GetFieldDefn(i)->GetNameRef()); } if (_includeInfo) { OGRFieldDefn oField("error_circ", OFTReal); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { throw HootException(QString("Error creating field (error:circular).")); } _circularErrorIndex = poLayer->GetLayerDefn()->GetFieldCount() - 1; } const NodeMap& nodes = map->getNodeMap(); for (NodeMap::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { const shared_ptr<Node>& node = it->second; if (node->getTags().getNonDebugCount() > 0) { OGRFeature* poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); // set all the column values. for (int i = 0; i < columns.size(); i++) { if (node->getTags().contains(columns[i])) { QByteArray c = shpColumns[i].toAscii(); QByteArray v = node->getTags()[columns[i]].toUtf8(); poFeature->SetField(c.constData(), v.constData()); } } if (_includeInfo) { poFeature->SetField(_circularErrorIndex, node->getCircularError()); } // convert the geometry. OGRGeometry* geom = new OGRPoint(node->getX(), node->getY()); if (poFeature->SetGeometryDirectly(geom) != OGRERR_NONE) { throw HootException(QString("Error setting geometry")); } if (poLayer->CreateFeature(poFeature) != OGRERR_NONE) { throw HootException(QString("Error creating feature")); } OGRFeature::DestroyFeature(poFeature); } } OGRDataSource::DestroyDataSource(poDS); }
MyOGRHandler(const std::string& driver_name, const std::string& filename) { OGRRegisterAll(); OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str()); if (!driver) { std::cerr << driver_name << " driver not available.\n"; exit(1); } CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); const char* options[] = { "SPATIALITE=TRUE", nullptr }; m_data_source = driver->CreateDataSource(filename.c_str(), const_cast<char**>(options)); if (!m_data_source) { std::cerr << "Creation of output file failed.\n"; exit(1); } OGRSpatialReference sparef; sparef.importFromProj4(m_factory.proj_string().c_str()); m_layer_point = m_data_source->CreateLayer("postboxes", &sparef, wkbPoint, nullptr); if (!m_layer_point) { std::cerr << "Layer creation failed.\n"; exit(1); } OGRFieldDefn layer_point_field_id("id", OFTReal); layer_point_field_id.SetWidth(10); if (m_layer_point->CreateField(&layer_point_field_id) != OGRERR_NONE) { std::cerr << "Creating id field failed.\n"; exit(1); } OGRFieldDefn layer_point_field_operator("operator", OFTString); layer_point_field_operator.SetWidth(30); if (m_layer_point->CreateField(&layer_point_field_operator) != OGRERR_NONE) { std::cerr << "Creating operator field failed.\n"; exit(1); } /* Transactions might make things faster, then again they might not. Feel free to experiment and benchmark and report back. */ m_layer_point->StartTransaction(); m_layer_linestring = m_data_source->CreateLayer("roads", &sparef, wkbLineString, nullptr); if (!m_layer_linestring) { std::cerr << "Layer creation failed.\n"; exit(1); } OGRFieldDefn layer_linestring_field_id("id", OFTReal); layer_linestring_field_id.SetWidth(10); if (m_layer_linestring->CreateField(&layer_linestring_field_id) != OGRERR_NONE) { std::cerr << "Creating id field failed.\n"; exit(1); } OGRFieldDefn layer_linestring_field_type("type", OFTString); layer_linestring_field_type.SetWidth(30); if (m_layer_linestring->CreateField(&layer_linestring_field_type) != OGRERR_NONE) { std::cerr << "Creating type field failed.\n"; exit(1); } m_layer_linestring->StartTransaction(); m_layer_polygon = m_data_source->CreateLayer("buildings", &sparef, wkbMultiPolygon, nullptr); if (!m_layer_polygon) { std::cerr << "Layer creation failed.\n"; exit(1); } OGRFieldDefn layer_polygon_field_id("id", OFTInteger); layer_polygon_field_id.SetWidth(10); if (m_layer_polygon->CreateField(&layer_polygon_field_id) != OGRERR_NONE) { std::cerr << "Creating id field failed.\n"; exit(1); } OGRFieldDefn layer_polygon_field_type("type", OFTString); layer_polygon_field_type.SetWidth(30); if (m_layer_polygon->CreateField(&layer_polygon_field_type) != OGRERR_NONE) { std::cerr << "Creating type field failed.\n"; exit(1); } m_layer_polygon->StartTransaction(); }
void ShapefileWriter::writeLines(shared_ptr<const OsmMap> map, const QString& path) { OGRRegisterAll(); _removeShapefile(path); const char *pszDriverName = "ESRI Shapefile"; OGRSFDriver *poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if( poDriver == NULL ) { throw HootException(QString("%1 driver not available.").arg(pszDriverName)); } OGRDataSource* poDS = poDriver->CreateDataSource(path.toAscii(), NULL ); if( poDS == NULL ) { throw HootException(QString("Data source creation failed. %1").arg(path)); } OGRLayer *poLayer; OgrOptions options; options["ENCODING"] = "UTF-8"; QString layerName; layerName = QFileInfo(path).baseName(); poLayer = poDS->CreateLayer(layerName.toAscii(), map->getProjection().get(), wkbLineString, options.getCrypticOptions()); if( poLayer == NULL ) { throw HootException(QString("Layer creation failed. %1").arg(path)); } QStringList shpColumns; QStringList columns = getColumns(map, ElementType::Way); for (int i = 0; i < columns.size(); i++) { OGRFieldDefn oField(columns[i].toAscii(), OFTString); oField.SetWidth(64); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { throw HootException(QString("Error creating field (%1).").arg(columns[i])); } shpColumns.append(poLayer->GetLayerDefn()->GetFieldDefn(i)->GetNameRef()); } if (_includeInfo) { OGRFieldDefn oField("error_circ", OFTReal); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { throw HootException(QString("Error creating field (error:circular).")); } _circularErrorIndex = poLayer->GetLayerDefn()->GetFieldCount() - 1; } const WayMap& ways = map->getWays(); for (WayMap::const_iterator it = ways.begin(); it != ways.end(); it++) { shared_ptr<Way> way = it->second; if (OsmSchema::getInstance().isArea(way) == false) { OGRFeature* poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); // set all the column values. for (int i = 0; i < columns.size(); i++) { if (way->getTags().contains(columns[i])) { QByteArray c = shpColumns[i].toAscii(); QByteArray v = way->getTags()[columns[i]].toUtf8(); poFeature->SetField(c.constData(), v.constData()); } } if (_includeInfo) { poFeature->SetField(_circularErrorIndex, way->getCircularError()); } // convert the geometry. std::string wkt = ElementConverter(map).convertToLineString(way)->toString(); char* t = (char*)wkt.data(); OGRGeometry* geom; if (OGRGeometryFactory::createFromWkt(&t, poLayer->GetSpatialRef(), &geom) != OGRERR_NONE) { throw HootException(QString("Error parsing WKT (%1)").arg(QString::fromStdString(wkt))); } if (poFeature->SetGeometryDirectly(geom) != OGRERR_NONE) { throw HootException(QString("Error setting geometry")); } if (poLayer->CreateFeature(poFeature) != OGRERR_NONE) { throw HootException(QString("Error creating feature")); } OGRFeature::DestroyFeature(poFeature); } } OGRDataSource::DestroyDataSource(poDS); }
TeOGRDriver::TeOGRDriver(const std::string& fileName, const bool &writing, const std::string &OGRDriverName) : TeGeoDataDriver(), fileName_(fileName), ogrLayer_(0) { // Registers all format drivers built into OGR. OGRRegisterAll(); ogrDS_=0; if(writing == false) { // Open OGR Datasource ogrDS_ = OGRSFDriverRegistrar::Open(fileName.c_str()); /* TODO: The data set may has one or more layers. Is necessary a revision on TeGeoDataDriver interface? For while, only first layer is considered by the driver. */ if(ogrDS_ != 0) { int nLayers = ogrDS_->GetLayerCount(); if(nLayers > 0) { ogrLayer_ = ogrDS_->GetLayer(0); // Gets the first layer } } if(ogrLayer_ == 0) { std::string errorMessage = CPLGetLastErrorMsg(); return; } // Number of objects numObjects_ = ogrLayer_->GetFeatureCount(); // Box OGREnvelope* env = new OGREnvelope(); ogrLayer_->GetExtent(env); box_ = Convert2TerraLib(env); delete env; // Geometric representation rep_ = Convert2TerraLib(ogrLayer_->GetLayerDefn()->GetGeomType()); attrList_ = Convert2TerraLib(ogrLayer_->GetLayerDefn()); } else { OGRSFDriver* poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(OGRDriverName.c_str()); ogrDS_ = poDriver->CreateDataSource(fileName.c_str(), NULL ); } if(ogrLayer_ == 0) { dataProjection_ = new TeNoProjection(); return; } OGRSpatialReference* srs = ogrLayer_->GetSpatialRef(); if(srs == 0) { dataProjection_ = new TeNoProjection(); return; } if(srs->AutoIdentifyEPSG() == OGRERR_UNSUPPORTED_SRS) { dataProjection_ = new TeNoProjection(); return; } dataProjection_ = TeProjectionFactory::make(atoi(srs->GetAuthorityCode(0))); }
TestOverviewHandler(const std::string& driver_name, const std::string& filename) { OGRRegisterAll(); OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str()); if (!driver) { std::cerr << driver_name << " driver not available.\n"; exit(1); } CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); const char* options[] = { "SPATIALITE=TRUE", nullptr }; m_data_source = driver->CreateDataSource(filename.c_str(), const_cast<char**>(options)); if (!m_data_source) { std::cerr << "Creation of output file failed.\n"; exit(1); } OGRSpatialReference sparef; sparef.SetWellKnownGeogCS("WGS84"); // nodes layer m_layer_nodes = m_data_source->CreateLayer("nodes", &sparef, wkbPoint, nullptr); if (!m_layer_nodes) { std::cerr << "Layer creation failed.\n"; exit(1); } OGRFieldDefn layer_nodes_field_id("id", OFTReal); layer_nodes_field_id.SetWidth(10); if (m_layer_nodes->CreateField(&layer_nodes_field_id) != OGRERR_NONE) { std::cerr << "Creating id field failed.\n"; exit(1); } // labels layer m_layer_labels = m_data_source->CreateLayer("labels", &sparef, wkbPoint, nullptr); if (!m_layer_labels) { std::cerr << "Layer creation failed.\n"; exit(1); } OGRFieldDefn layer_labels_field_id("id", OFTReal); layer_labels_field_id.SetWidth(10); if (m_layer_labels->CreateField(&layer_labels_field_id) != OGRERR_NONE) { std::cerr << "Creating id field failed.\n"; exit(1); } OGRFieldDefn layer_labels_field_label("label", OFTString); layer_labels_field_label.SetWidth(30); if (m_layer_labels->CreateField(&layer_labels_field_label) != OGRERR_NONE) { std::cerr << "Creating label field failed.\n"; exit(1); } // ways layer m_layer_ways = m_data_source->CreateLayer("ways", &sparef, wkbLineString, nullptr); if (!m_layer_ways) { std::cerr << "Layer creation failed.\n"; exit(1); } OGRFieldDefn layer_way_field_id("id", OFTReal); layer_way_field_id.SetWidth(10); if (m_layer_ways->CreateField(&layer_way_field_id) != OGRERR_NONE) { std::cerr << "Creating id field failed.\n"; exit(1); } OGRFieldDefn layer_way_field_test("test", OFTInteger); layer_way_field_test.SetWidth(3); if (m_layer_ways->CreateField(&layer_way_field_test) != OGRERR_NONE) { std::cerr << "Creating test field failed.\n"; exit(1); } }