예제 #1
0
///////////////////////////////////////////////////////////////////////////////
// Eine Shapedatei öffnen
HRESULT CShapeDataSource::OpenFile(const char *pszNewName, bool fUpdate, bool fTestOpen)
{
	_ASSERTE(NULL != pszNewName);
	if (NULL == pszNewName)
		return E_POINTER;

SHPHandle hSHP = NULL;
DBFHandle hDBF = NULL;

	if (fUpdate)
		hSHP = SHPOpen (pszNewName, "r+");
	else
		hSHP = SHPOpen (pszNewName, "r");
	if (NULL == hSHP)
		return S_FALSE;
	
// Open the .dbf file, if it exists.
	if (fUpdate)
		hDBF = DBFOpen (pszNewName, "rb+");
	else
		hDBF = DBFOpen (pszNewName, "rb");

// Extract the basename of the file.
	COM_TRY {
	// Create the layer object and add layer to data source layer list.
	os_path path (pszNewName);

		m_Layers.push_back (new CShapeLayer(path.base().c_str(), hSHP, hDBF, fUpdate));

	} COM_CATCH;
	return S_OK;
}
예제 #2
0
/**
 * Program start! 
 * Defines static variables constant through out processing
 * of canopy height models.
 * 
 * Initializes:
 * - shape file containing tree crowns
 * - minimum easting
 * - minimum norhting
 * - block size
 */
static PyObject* Py_setup(PyObject* self, PyObject* args)
{
	printf("SETUP.\n");
	
	char * shpFile;
	
	if(!PyArg_ParseTuple(args, "siddif", &shpFile, &BLOCK_SIZE, &MIN_E, &MIN_N, &OUT_RES, &Z_THRESH))
	{
		PyErr_SetString(PyExc_IOError, "Could not parse parameters.");
		return NULL;
	}

	
	H_SHP = SHPOpen(shpFile, "rb");
	if(!H_SHP)
	{
		PyErr_SetString(PyExc_IOError, "Could not open shape file.");
		return NULL;
	}
	
	if(!setup())
		return NULL;
	
	return Py_BuildValue("i", N_RECORDS);
}
예제 #3
0
bool vtUtilityMap::ImportPolesFromSHP(const char *fname)
{
	SHPHandle hSHP;
	int		nEntities, nShapeType;
	DPoint2 point;

	// SHPOpen doesn't yet support utf-8 or wide filenames, so convert
	vtString fname_local = UTF8ToLocal(fname);

	hSHP = SHPOpen(fname_local, "rb");
	if (!hSHP)
		return false;

	SHPGetInfo(hSHP, &nEntities, &nShapeType, NULL, NULL);
	if (nShapeType != SHPT_POINT)
		return false;

	for (int i = 0; i < nEntities; i++)
	{
		SHPObject *psShape = SHPReadObject(hSHP, i);
		point.x = psShape->padfX[0];
		point.y = psShape->padfY[0];
		vtPole *pole = new vtPole;
		pole->m_p = point;
		m_Poles.Append(pole);
		SHPDestroyObject(psShape);
	}
	SHPClose(hSHP);
	return true;
}
예제 #4
0
    void parse(const std::string& path, Visitor& visitor) const
    {
        SHPHandle shpFile = SHPOpen(path.c_str(), "rb");
        if (shpFile == NULL)
            throw std::domain_error("Cannot open shp file.");

        int shapeType, entityCount;
        double adfMinBound[4], adfMaxBound[4];
        SHPGetInfo(shpFile, &entityCount, &shapeType, adfMinBound, adfMaxBound);

        DBFHandle dbfFile = DBFOpen(path.c_str(), "rb");
        if (dbfFile == NULL)
            throw std::domain_error("Cannot open dbf file.");

        if (DBFGetFieldCount(dbfFile) == 0)
            throw std::domain_error("There are no fields in dbf table.");

        if (entityCount != DBFGetRecordCount(dbfFile))
            throw std::domain_error("dbf file has different entity count.");

        for (int k = 0; k < entityCount; k++)
        {
            SHPObject* shape = SHPReadObject(shpFile, k);
            if (shape == NULL)
                throw std::domain_error("Unable to read shape:" + to_string(k));

            Tags tags = parseTags(dbfFile, k);
            visitShape(*shape, tags, visitor);

            SHPDestroyObject(shape);
        }

        DBFClose(dbfFile);
        SHPClose(shpFile);
    }
예제 #5
0
void shapefileClip::OpenShapeFile(SHPHandle &hSHP)
{
	if ((hSHP = SHPOpen(m_landmaskShpName.c_str(),"rb")) == NULL){
		cerr << "Shapefile " << m_landmaskShpName.c_str() << " could not be opened." << endl
		<< "Line: " << __LINE__ << " " << __FILE__ << endl;
	}
}
예제 #6
0
파일: dialog.cpp 프로젝트: jotr/qt-test
void loadMapData(std::string path, QPolygonF* poly)
{
    SHPHandle shp = SHPOpen(path.c_str(), "rb");
    if (shp != 0) {
        qDebug() << "Loaded map: " << path.c_str();
    } else {
        qDebug() << "Could not load map: " << path.c_str();
        return;
    }
    int entities, type;
    double minBound[4], maxBound[4];
    SHPGetInfo(shp, &entities, &type, minBound, maxBound);
//    qDebug() << "Type: " << type << " Entities: " << entities;

    SHPObject* o = SHPReadObject(shp, 0);

    int parts = o->nParts;

//    qDebug() << "Parts: " << parts;

    int currentPart = 0;
    int start = o->panPartStart[currentPart];
    int end = parts == 1 ? o->nVertices : o->panPartStart[currentPart + 1];

//    qDebug() << "Start: " << start << " End: " << end << " Vertices: " << o->nVertices;

    for(int i = start; i < end; i++) {
        double x = o->padfX[i];
        double y = o->padfY[i];
        *poly << QPointF(x, y);
    }
}
예제 #7
0
// ---------------------------------------------------------------------------
// Constructeur
// ------------
bSHPTable	::bSHPTable(	const char* path,
							const char* name,
							bool create, 
							double* reso,
							double* ox,
							double* oy,
							int* tsrid,
							int* asrid,
							int* status)
			:bStdTable(*reso,*ox,*oy,*tsrid,*asrid,status){
_bTrace_("bSHPTable::bSHPTable",false);
int			ptype=db2shp(*status);
	
char	fpath[1024];
	
	sprintf(fpath,"%s%s",path,name);
//_tm_(fpath);
	_shp=SHPOpen(fpath,"rb+");
	if(!_shp){
//_te_("SHPOpen failed for rb+");
		_shp=SHPOpen(fpath,"rb");
	}
//_tm_("SHPOpen passed");
	if(_shp){
int		count;
double	bmin[4],bmax[4];
//_tm_("SHPGetInfo");
		SHPGetInfo(_shp,&count,&ptype,bmin,bmax);
//_tm_(count+" objects of "+ptype+" kind");
		*status=shp2db(ptype);
		return;
	}
//_te_("SHPOpen failed for rb");

	if(!create){
		*status=-1;
_te_(fpath+" : table not found");
		return;
	}
	_shp=SHPCreate(fpath,ptype);
	if(!_shp){
_te_(fpath+" : creation failed");
		*status=-1;
		return;
	}
	*status=0;
}
int count_shape_points(char *shape_name)
{
    int entidades;
    SHPHandle arquivo_shp;
    arquivo_shp=SHPOpen(shape_name, "r");
    SHPGetInfo(arquivo_shp,&entidades,NULL,NULL,NULL);
    return entidades;
}
예제 #9
0
//  Function to read outlets from a shapefile - overloaded to return an array of integer ID's
int readoutlets(char *outletsfile, int *noutlets, double*& x, double*& y, int*& id)
{
	SHPHandle shp = SHPOpen(outletsfile, "rb");
	char dbffile[MAXLN];
	nameadd(dbffile, outletsfile, ".dbf");
	DBFHandle dbf = DBFOpen(dbffile, "rb");
	if ((shp != NULL) && (dbf != NULL)) {
		int nEntities = 0;
		int nShapeType = 0;
		SHPGetInfo(shp, &nEntities, &nShapeType, NULL, NULL );
		if (nShapeType != SHPT_POINT)
		{
			fprintf(stderr, "Outlets shapefile %s is not a point shapefile\n", outletsfile);
			fflush(stderr);
			return 1;
		}
	long p_size;
	long countPts = 0;

	int nfld = DBFGetFieldCount(dbf);
	//int idfld = DBFGetFieldIndex(dbf, "id");
	int idfld = DBFGetFieldIndex(dbf, "OBJECTID"); // ZhuLJ, 2015/6/16
	for( int i=0; i<nEntities; i++) {
		SHPObject * shape = SHPReadObject(shp, i);
		countPts += shape->nVertices;
		SHPDestroyObject(shape);
	}
	x = new double[countPts];
	y = new double[countPts];
	if (idfld >= 0)
		id = new int[countPts];
    int nxy=0;
	for( int i=0; i<nEntities; i++) {
		SHPObject * shape = SHPReadObject(shp, i);
		p_size = shape->nVertices;
		for( int j=0; j<p_size; j++) {
			x[nxy] = shape->padfX[j];
			y[nxy] = shape->padfY[j];
			if (idfld >= 0)
			{
				id[nxy] = DBFReadIntegerAttribute(dbf, i, idfld);
			}
			nxy++;
		}
		SHPDestroyObject(shape);
	}
	*noutlets=nxy;
	SHPClose(shp);
	return 0;
	}
	else { 
		fprintf(stderr, "Error opening outlets shapefile: %s\n", outletsfile);
		fflush(stderr);
		return 1;
	}	
}
예제 #10
0
파일: shape.c 프로젝트: peko/tttm2
shapes_v
shape_load_globe(const char* filename) {

    shapes_v globe;
    kv_init(globe);

    double  adfMinBound[4],
            adfMaxBound[4];

    // Read file
    SHPHandle hSHP = SHPOpen( filename, "rb" );
    if(hSHP == NULL) goto end_loading;

    // Print shape bounds
    int country_count, shapes_vype;
    SHPGetInfo( hSHP, &country_count, &shapes_vype, adfMinBound, adfMaxBound );
    
    fprintf(stderr, "Load %d countries\n", country_count);
    // Iterate through countries
    for(int i = 0; i < country_count; i++ ) {
                        
        SHPObject *shp = SHPReadObject(hSHP, i);
        if(shp == NULL) goto end_loading;

        if(shp->nParts == 0) continue;

        // first part starts at point 0
        if(shp->panPartStart[0] != 0) goto end_loading;

        // collect parts of country
        uint32_t parts = shp->nParts;
        for (uint32_t j=0; j<parts; j++) {
            // start index
            uint32_t s = shp->panPartStart[j];
            // end index - start of next minus one, or end
            uint32_t e = (j+1 < parts) ?
                shp->panPartStart[j+1]:
                shp->nVertices;
            shape_v shape;
            kv_init(shape);
            // collect points of part
            for(uint32_t i=s; i<e; i++){
                point_t p = (point_t){shp->padfX[i], shp->padfY[i]};
                kv_push(point_t, shape, p);
            }
            kv_push(shape_v, globe, shape);
        }
        SHPDestroyObject( shp );
    }
    SHPClose( hSHP );

end_loading:
    return globe;
}
예제 #11
0
bool vtUtilityMap::ImportLinesFromSHP(const char *fname)
{
	SHPHandle hSHP;
	int		nEntities, nShapeType;
	int		i, j, verts;

	// SHPOpen doesn't yet support utf-8 or wide filenames, so convert
	vtString fname_local = UTF8ToLocal(fname);

	hSHP = SHPOpen(fname_local, "rb");
	if (!hSHP)
		return false;

	SHPGetInfo(hSHP, &nEntities, &nShapeType, NULL, NULL);
	if (nShapeType != SHPT_ARC)
		return false;

	for (i = 0; i < nEntities; i++)
	{
		SHPObject *psShape = SHPReadObject(hSHP, i);

		verts = psShape->nVertices;
		vtLine *line = new vtLine;
		line->SetSize(verts);

		// Store each SHP Poly Coord in Line
		for (j = 0; j < verts; j++)
		{
			line->GetAt(j).x = psShape->padfX[j];
			line->GetAt(j).y = psShape->padfY[j];
		}
		SHPDestroyObject(psShape);

		// Guess source and destination poles by using location
		line->m_src = ClosestPole(line->GetAt(0));
		line->m_dst = ClosestPole(line->GetAt(verts-1));

		// avoid degenerate lines
		if (line->m_src == line->m_dst)
		{
			delete line;
			continue;
		}

		// tweak start and end of line to match poles
		line->SetAt(0, line->m_src->m_p);
		line->SetAt(verts-1, line->m_dst->m_p);

		m_Lines.Append(line);
	}
	SHPClose(hSHP);
	return true;
}
jboolean Java_org_maptools_shapelib_android_util_TestUtils_updateShapefile(JNIEnv * env, jclass clazz,
                                                                jstring file, jobject listObject) {
    // open an existing shapefile and dbf (e.g. /sdcard/foo/bar)
    const char *fileStr = (*env)->GetStringUTFChars(env, file, 0);
    SHPHandle hSHP = SHPOpen(fileStr, "rb+");
    DBFHandle hDBF = DBFOpen(fileStr, "rb+");
    (*env)->ReleaseStringUTFChars(env, file, fileStr);

    process(env, hSHP, hDBF, file, listObject);

    SHPClose(hSHP);
    DBFClose(hDBF);
}
예제 #13
0
void surfaceVectorField::OpenShape()
{
/*
	FILE *fx=fopen(ShapeFileName, "w");
     if(fx)
	     fclose(fx);
	fx=fopen(DataBaseName, "w");
     if(fx)
	     fclose(fx);
*/
     hSHP=SHPOpen(ShapeFileName.c_str(), "rb+");
     hDBF=DBFOpen(DataBaseName.c_str(), "rb+");
}
double *get_coordinate_point(int point_id, char *name_of_shp)
{
    SHPObject *point;
    SHPHandle arquivo_shp;
    static double p[4];
    arquivo_shp=SHPOpen(name_of_shp, "r");
    point = SHPReadObject(arquivo_shp,point_id);
       p[0] = point->padfX[0];
       p[1] = point->padfY[0];
       p[2] = point->padfZ[0];
SHPClose(arquivo_shp);
return p;
}
예제 #15
0
int GetSHPType(const char *filename)
{
	// SHPOpen doesn't yet support utf-8 or wide filenames, so convert
	vtString fname_local = UTF8ToLocal(filename);

	SHPHandle hSHP = SHPOpen(fname_local, "rb");
	if (hSHP == NULL)
		return SHPT_NULL;

	int nEntities, nShapeType;

	SHPGetInfo(hSHP, &nEntities, &nShapeType, NULL, NULL);
	SHPClose(hSHP);
	return nShapeType;
}
예제 #16
0
static int display_info(const char * fpath, const struct stat * sb, int tflag, struct FTW * ftwbuf)
{
  if (fpath[ftwbuf->base] == '.') return 0;
  if (strcmp(fpath + strlen(fpath) - 4, ".dbf") != 0) return 0;
  
  char file[400];
  strncpy(file, fpath + strlen(data_path), 400);
  file[strlen(file)-4] = 0;
  
  DBFHandle dbf = DBFOpen(fpath, "rb");
  SHPHandle shp = SHPOpen(fpath, "rb");
  
  general_count++;
  
  char * formatc = mg_get_var(dconn, "format");
  int json = 0;
  if (formatc != NULL && strcmp(formatc, "json") == 0)
    json = 1;
  free(formatc);
  
  if (json)
  {
    mg_printf(dconn, "%s\n  {", ((general_count==1) ? "" : ","));
    mg_printf(dconn, "\"file\":\"%s\"", file);
    
    if (dbf) mg_printf(dconn, ", \"dbfRecords\":%d", dbf->nRecords);
    if (dbf) mg_printf(dconn, ", \"dbfFields\":%d", dbf->nFields);
    
    mg_printf(dconn, ", \"image 0\": \"/image?file=%s&id=0\"", file);
    mg_printf(dconn, ", \"full image\": \"/image?file=%s\"", file);
    mg_printf(dconn, "}");
  }
  else
  {
    mg_printf(dconn, "<tr>");
    mg_printf(dconn, "<td>%s</td>", file);
    if (dbf) mg_printf(dconn, "<td><a href='/shapefiles/fields?file=%s'>fields</a></td>", file);
    if (shp) mg_printf(dconn, "<td><a href='/shapefiles/png?file=%s'>image</a></td>\n", file);
    mg_printf(dconn, "</tr>");
  }
  
  if (shp) SHPClose(shp);
  if (dbf) DBFClose(dbf);
  
  return 0; // To tell nftw() to continue
}
예제 #17
0
파일: Rshapeinfo.c 프로젝트: cran/maptools
SEXP Rshapeinfo1(SEXP shpname)

{
    SEXP res, nms;
    SHPHandle	hSHP;
    int    nShapeType, nEntities, i, pc=0;
    double  adfMinBound[4], adfMaxBound[4];
    PROTECT(res = NEW_LIST(5)); pc++;
    PROTECT(nms = NEW_CHARACTER(5)); pc++;
    SET_STRING_ELT(nms, 0, COPY_TO_USER_STRING("fname"));
    SET_STRING_ELT(nms, 1, COPY_TO_USER_STRING("type"));
    SET_STRING_ELT(nms, 2, COPY_TO_USER_STRING("entities"));
    SET_STRING_ELT(nms, 3, COPY_TO_USER_STRING("minbounds"));
    SET_STRING_ELT(nms, 4, COPY_TO_USER_STRING("maxbounds"));
    setAttrib(res, R_NamesSymbol, nms);
    SET_VECTOR_ELT(res, 0, NEW_CHARACTER(1));
    SET_VECTOR_ELT(res, 1, NEW_INTEGER(1));
    SET_VECTOR_ELT(res, 2, NEW_INTEGER(1));
    SET_VECTOR_ELT(res, 3, NEW_NUMERIC(4));
    SET_VECTOR_ELT(res, 4, NEW_NUMERIC(4));
    SET_STRING_ELT(VECTOR_ELT(res, 0), 0, STRING_ELT(shpname, 0));
    
/*      const char 	*pszPlus; */
/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    hSHP = SHPOpen(CHAR(STRING_ELT(shpname, 0)), "rb" );

    if( hSHP == NULL ) error("Error opening SHP file");

/* -------------------------------------------------------------------- */
/*      Print out the file bounds.                                      */
/* -------------------------------------------------------------------- */
    SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound ); 
    INTEGER_POINTER(VECTOR_ELT(res, 1))[0] = nShapeType;
    INTEGER_POINTER(VECTOR_ELT(res, 2))[0] = nEntities;
    for (i=0; i<4; i++) { 
        NUMERIC_POINTER(VECTOR_ELT(res, 3))[i] = adfMinBound[i];
        NUMERIC_POINTER(VECTOR_ELT(res, 4))[i] = adfMaxBound[i];
    }

    SHPClose( hSHP );   
    UNPROTECT(pc);
    return(res);
}
예제 #18
0
static int shapelib_open(lua_State *ls)
{
    const char *filename = luaL_checkstring(ls, 1);

    SHPHandle shp = SHPOpen(filename, "rb+");

    if (shp) {
        SHPHandle *shp_ptr = lua_newuserdata(ls, sizeof(SHPHandle *));
        *shp_ptr = shp;

        luaL_getmetatable(ls, "shapelib.shphandle");
        lua_setmetatable(ls, -2);

        return 1;
    }

    return luaL_error(ls, "could not open shapefile: %s", filename);
}
예제 #19
0
//  Function to read outlets from a shapefile
int readoutlets(char *outletsfile, int *noutlets, double*& x, double*& y)
{
	SHPHandle shp;
	shp = SHPOpen(outletsfile, "rb");
	if (shp != NULL) {
		int nEntities = 0;
		int nShapeType = 0;
		SHPGetInfo(shp, &nEntities, &nShapeType, NULL, NULL );
		if (nShapeType != SHPT_POINT) {
			fprintf(stderr, "Outlets shapefile %s is not a point shapefile\n", outletsfile);
			fflush(stderr);
			return 1;
		}
		long p_size;
		long countPts = 0;
		for( int i=0; i<nEntities; i++) {
			SHPObject * shape = SHPReadObject(shp, i);
			countPts += shape->nVertices;
			SHPDestroyObject(shape);
		}
		x = new double[countPts];
		y = new double[countPts];
		int nxy=0;
		for( int i=0; i<nEntities; i++) {
			SHPObject * shape = SHPReadObject(shp, i);
			p_size = shape->nVertices;
			for( int j=0; j<p_size; j++) {
				x[nxy] = shape->padfX[j];
				y[nxy] = shape->padfY[j];
				nxy++;
			}
			SHPDestroyObject(shape);
		}
		*noutlets=nxy;
		SHPClose(shp);
		return 0;
	}
	else { 
		fprintf(stderr, "Error opening outlets shapefile %s.\n", outletsfile);
		fflush(stderr);
		return 1;
	}	
}
예제 #20
0
파일: Rshapeinfo.c 프로젝트: cran/maptools
void Rshapeinfo(char **shpnm, int *Shapetype, int *Entities, double
		*MinBound, double *MaxBound)

{
    SHPHandle	hSHP;
    int    nShapeType, nEntities, i;
    double  adfMinBound[4], adfMaxBound[4];
/*      const char 	*pszPlus; */
/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    hSHP = SHPOpen( shpnm[0] , "rb" );

    if( hSHP == NULL )
    {
/*	REprintf( "Unable to open:%s\n", shpnm[0] );
	exit( 1 ); */
	error("No such file");
    }

/* -------------------------------------------------------------------- */
/*      Print out the file bounds.                                      */
/* -------------------------------------------------------------------- */
      SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound ); 
    
      *Entities = nEntities; 
      *Shapetype = nShapeType;
      for (i=0;i<4;i++){ 
        MinBound[i]=adfMinBound[i];
        MaxBound[i]=adfMaxBound[i];
    }

/*    Rprintf ("Info for %s\n", shpnm[0]);
    Rprintf("Shapefile Type: %s(%d)   # of Shapes: %ld\n\n",
            SHPTypeName( nShapeType ), nShapeType, nEntities );
    Rprintf("File Bounds: (%15.10lg,%15.10lg)\n\t(%15.10lg,%15.10lg)\n",
	    MinBound[0], MinBound[1], MaxBound[0], MaxBound[1] );*/
    

    SHPClose( hSHP );   
    return;
}
예제 #21
0
void open_baseline_shape(char *inFile, DBFHandle *dbase, SHPHandle *shape)
{
    char *dbaseFile;

    // Open database for adding values
    dbaseFile = (char *) MALLOC(sizeof(char)*(strlen(inFile)+5));
    sprintf(dbaseFile, "%s.dbf", inFile);
    *dbase = DBFOpen(dbaseFile, "r+b");
    if (*dbase == NULL)
        asfPrintError("Could not open database file '%s'\n", dbaseFile);

    // Open shapefile for adding values
    *shape = SHPOpen(inFile, "r+b");
    if (*shape == NULL)
        asfPrintError("Could not open shapefile '%s\n", inFile);

    FREE(dbaseFile);

    return;
}
예제 #22
0
bool ShpLoader::load( const char* filename )
{
  hSHP = SHPOpen(filename, "rb");

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

  float d6[] = 
  {
    hSHP->adBoundsMin[0], hSHP->adBoundsMax[0],
    hSHP->adBoundsMin[1], hSHP->adBoundsMax[1], 
    hSHP->adBoundsMin[2], hSHP->adBoundsMax[2], 
  };

  _bbox = BBox(d6);

  return true;
}
void find_file_shp(char *name,char *name_metadata)
{
    FILE * metadados;
    metadados = fopen (name_metadata,"a");
    char shp_plus_in_folder[100];
    char shp_plus[30];
    SHPHandle arquivo_shp;
    strcpy (shp_plus,name);
    strcat (shp_plus,".shp");
    sprintf(shp_plus_in_folder,"%s",shp_plus);//Para o IGC
    //abre o shp e verifica se o arquivo existe
    arquivo_shp=SHPOpen(shp_plus_in_folder, "r");
        if (arquivo_shp==NULL){
                           printf("Nao consegui abrir %s na pasta SHP (IGC)\n",shp_plus_in_folder);
                           fprintf(metadados,"Nao consegui abrir %s na pasta SHP (IGC)\n",shp_plus_in_folder);
                           exit(0);
                           }
//fim abre shp
strcpy (name,shp_plus_in_folder);
SHPClose(arquivo_shp);
fclose(metadados);
}
예제 #24
0
int isshape(char *inFile)
{
    char *ext = findExt(inFile);
    if (ext && strcmp_case(ext,".shp")!=0) {
        return FALSE;
    }

    char *dbaseFile, *basename;
    int isShape = 0;
    int nEntities, pointType;
    DBFHandle dbase;
    SHPHandle shape;

    dbaseFile = (char *)MALLOC(sizeof(char)*(strlen(inFile)+5));
    basename = get_basename(inFile);
    sprintf(dbaseFile, "%s.dbf", basename);
    dbase = DBFOpen(dbaseFile, "r+b");
    shape = SHPOpen(inFile, "r+b");
    if (dbase != NULL && shape != NULL) {
        SHPGetInfo(shape, &nEntities, &pointType, NULL, NULL);
        if (nEntities >= 1 &&
            (pointType == SHPT_POLYGON   ||
             pointType == SHPT_POINT     ||
             pointType == SHPT_ARC       ||
             pointType == SHPT_MULTIPOINT )
        )
        {
            isShape = 1;
        }
    }
    if (shape) SHPClose(shape);
    if (dbase) DBFClose(dbase);
    FREE(basename);
    FREE(dbaseFile);

    return isShape;
}
예제 #25
0
OGRErr OGRShapeLayer::Repack()

{
    if( !bUpdateAccess )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
            "The REPACK operation is not permitted on a read-only shapefile." );
        return OGRERR_FAILURE;
    }
    
    if( hDBF == NULL )
    {
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "Attempt to repack a shapefile with no .dbf file not supported.");
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Build a list of records to be dropped.                          */
/* -------------------------------------------------------------------- */
    int *panRecordsToDelete = (int *) 
        CPLMalloc(sizeof(int)*(nTotalShapeCount+1));
    int nDeleteCount = 0;
    int iShape = 0;
    OGRErr eErr = OGRERR_NONE;

    for( iShape = 0; iShape < nTotalShapeCount; iShape++ )
    {
        if( DBFIsRecordDeleted( hDBF, iShape ) )
            panRecordsToDelete[nDeleteCount++] = iShape;
    }
    panRecordsToDelete[nDeleteCount] = -1;

/* -------------------------------------------------------------------- */
/*      If there are no records marked for deletion, we take no         */
/*      action.                                                         */
/* -------------------------------------------------------------------- */
    if( nDeleteCount == 0 )
    {
        CPLFree( panRecordsToDelete );
        return OGRERR_NONE;
    }

/* -------------------------------------------------------------------- */
/*      Find existing filenames with exact case (see #3293).            */
/* -------------------------------------------------------------------- */
    CPLString osDirname(CPLGetPath(pszFullName));
    CPLString osBasename(CPLGetBasename(pszFullName));
    
    CPLString osDBFName, osSHPName, osSHXName;
    char **papszCandidates = CPLReadDir( osDirname );
    int i = 0;
    while(papszCandidates != NULL && papszCandidates[i] != NULL)
    {
        CPLString osCandidateBasename = CPLGetBasename(papszCandidates[i]);
        CPLString osCandidateExtension = CPLGetExtension(papszCandidates[i]);
        if (osCandidateBasename.compare(osBasename) == 0)
        {
            if (EQUAL(osCandidateExtension, "dbf"))
                osDBFName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
            else if (EQUAL(osCandidateExtension, "shp"))
                osSHPName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
            else if (EQUAL(osCandidateExtension, "shx"))
                osSHXName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
        }
        
        i++;
    }
    CSLDestroy(papszCandidates);
    papszCandidates = NULL;
    
    if (osDBFName.size() == 0)
    {
        /* Should not happen, really */
        CPLFree( panRecordsToDelete );
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Cleanup any existing spatial index.  It will become             */
/*      meaningless when the fids change.                               */
/* -------------------------------------------------------------------- */
    if( CheckForQIX() )
        DropSpatialIndex();

/* -------------------------------------------------------------------- */
/*      Create a new dbf file, matching the old.                        */
/* -------------------------------------------------------------------- */
    DBFHandle hNewDBF = NULL;
    
    CPLString oTempFile(CPLFormFilename(osDirname, osBasename, NULL));
    oTempFile += "_packed.dbf";

    hNewDBF = DBFCloneEmpty( hDBF, oTempFile );
    if( hNewDBF == NULL )
    {
        CPLFree( panRecordsToDelete );

        CPLError( CE_Failure, CPLE_OpenFailed, 
                  "Failed to create temp file %s.", 
                  oTempFile.c_str() );
        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Copy over all records that are not deleted.                     */
/* -------------------------------------------------------------------- */
    int iDestShape = 0;
    int iNextDeletedShape = 0;

    for( iShape = 0; 
         iShape < nTotalShapeCount && eErr == OGRERR_NONE; 
         iShape++ )
    {
        if( panRecordsToDelete[iNextDeletedShape] == iShape )
            iNextDeletedShape++;
        else
        {
            void *pTuple = (void *) DBFReadTuple( hDBF, iShape );
            if( pTuple == NULL )
                eErr = OGRERR_FAILURE;
            else if( !DBFWriteTuple( hNewDBF, iDestShape++, pTuple ) )
                eErr = OGRERR_FAILURE;
        }                           
    }

    if( eErr != OGRERR_NONE )
    {
        CPLFree( panRecordsToDelete );
        VSIUnlink( oTempFile );
        return eErr;
    }

/* -------------------------------------------------------------------- */
/*      Cleanup the old .dbf and rename the new one.                    */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    DBFClose( hNewDBF );
    hDBF = hNewDBF = NULL;
    
    VSIUnlink( osDBFName );
        
    if( VSIRename( oTempFile, osDBFName ) != 0 )
    {
        CPLDebug( "Shape", "Can not rename DBF file: %s", VSIStrerror( errno ) );
        CPLFree( panRecordsToDelete );
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Now create a shapefile matching the old one.                    */
/* -------------------------------------------------------------------- */
    if( hSHP != NULL )
    {
        SHPHandle hNewSHP = NULL;
        
        if (osSHPName.size() == 0 || osSHXName.size() == 0)
        {
            /* Should not happen, really */
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }

        oTempFile = CPLFormFilename(osDirname, osBasename, NULL);
        oTempFile += "_packed.shp";

        hNewSHP = SHPCreate( oTempFile, hSHP->nShapeType );
        if( hNewSHP == NULL )
        {
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }

/* -------------------------------------------------------------------- */
/*      Copy over all records that are not deleted.                     */
/* -------------------------------------------------------------------- */
        iNextDeletedShape = 0;

        for( iShape = 0; 
             iShape < nTotalShapeCount && eErr == OGRERR_NONE; 
             iShape++ )
        {
            if( panRecordsToDelete[iNextDeletedShape] == iShape )
                iNextDeletedShape++;
            else
            {
                SHPObject *hObject;

                hObject = SHPReadObject( hSHP, iShape );
                if( hObject == NULL )
                    eErr = OGRERR_FAILURE;
                else if( SHPWriteObject( hNewSHP, -1, hObject ) == -1 )
                    eErr = OGRERR_FAILURE;

                if( hObject )
                    SHPDestroyObject( hObject );
            }
        }

        if( eErr != OGRERR_NONE )
        {
            CPLFree( panRecordsToDelete );
            VSIUnlink( CPLResetExtension( oTempFile, "shp" ) );
            VSIUnlink( CPLResetExtension( oTempFile, "shx" ) );
            return eErr;
        }

/* -------------------------------------------------------------------- */
/*      Cleanup the old .shp/.shx and rename the new one.               */
/* -------------------------------------------------------------------- */
        SHPClose( hSHP );
        SHPClose( hNewSHP );
        hSHP = hNewSHP = NULL;

        VSIUnlink( osSHPName );
        VSIUnlink( osSHXName );

        oTempFile = CPLResetExtension( oTempFile, "shp" );
        if( VSIRename( oTempFile, osSHPName ) != 0 )
        {
            CPLDebug( "Shape", "Can not rename SHP file: %s", VSIStrerror( errno ) );
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }
    
        oTempFile = CPLResetExtension( oTempFile, "shx" );
        if( VSIRename( oTempFile, osSHXName ) != 0 )
        {
            CPLDebug( "Shape", "Can not rename SHX file: %s", VSIStrerror( errno ) );
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }
    }
    
    CPLFree( panRecordsToDelete );
    panRecordsToDelete = NULL;

/* -------------------------------------------------------------------- */
/*      Reopen the shapefile                                            */
/*                                                                      */
/* We do not need to reimplement OGRShapeDataSource::OpenFile() here    */  
/* with the fully featured error checking.                              */
/* If all operations above succeeded, then all necessery files are      */
/* in the right place and accessible.                                   */
/* -------------------------------------------------------------------- */
    CPLAssert( NULL == hSHP );
    CPLAssert( NULL == hDBF && NULL == hNewDBF );
    
    CPLPushErrorHandler( CPLQuietErrorHandler );
    
    const char* pszAccess = NULL;
    if( bUpdateAccess )
        pszAccess = "r+";
    else
        pszAccess = "r";
    
    hSHP = SHPOpen ( CPLResetExtension( pszFullName, "shp" ) , pszAccess );
    hDBF = DBFOpen ( CPLResetExtension( pszFullName, "dbf" ) , pszAccess );
    
    CPLPopErrorHandler();
    
    if( NULL == hSHP || NULL == hDBF )
    {
        CPLString osMsg(CPLGetLastErrorMsg());
        CPLError( CE_Failure, CPLE_OpenFailed, "%s", osMsg.c_str() );

        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Update total shape count.                                       */
/* -------------------------------------------------------------------- */
    nTotalShapeCount = hDBF->nRecords;

    return OGRERR_NONE;
}
예제 #26
0
int main(int argc, char **argv)
{
  if (argc == 1) { printf("usage: shapefile_to_kml [FILENAME]\n"); exit(1); }
  
  DBFHandle d = DBFOpen(argv[1], "rb");
  if (d == NULL) { printf("DBFOpen error (%s.dbf)\n", argv[1]); exit(1); }
	
	SHPHandle h = SHPOpen(argv[1], "rb");
  if (h == NULL) { printf("SHPOpen error (%s.dbf)\n", argv[1]); exit(1); }
	
  char filename[60];
  sprintf(filename, "%s.kml", argv[1]);
  printf("%s\n", filename);
  FILE *fp = fopen(filename, "w");
  if (fp == NULL) { printf("fopen error\n"); exit(1); }
	
  int nRecordCount = DBFGetRecordCount(d);
  int nFieldCount = DBFGetFieldCount(d);
  printf("DBF has %d records (with %d fields)\n", nRecordCount, nFieldCount);
	
  fprintf(fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  fprintf(fp, "<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n");

  /*for (int i = 0 ; i < nFieldCount ; i++)
  {
    char pszFieldName[12];
    int pnWidth;
    int pnDecimals;
    DBFFieldType ft = DBFGetFieldInfo(d, i, pszFieldName, &pnWidth, &pnDecimals);
    switch (ft)
    {
      case FTString:
        fprintf(fp, ", %s VARCHAR(%d)", pszFieldName, pnWidth);
        break;
      case FTInteger:
        fprintf(fp, ", %s INT", pszFieldName);
        break;
      case FTDouble:
        fprintf(fp, ", %s FLOAT(15,10)", pszFieldName);
        break;
      case FTLogical:
        break;
      case FTInvalid:
        break;
    }
  }*/
  
  fprintf(fp, "  <Document>\n");
  int i;
  for (i = 0 ; i < nRecordCount ; i++)
  {
    fprintf(fp, "    <Placemark>\n");
    fprintf(fp, "      <name>%s</name>\n", (char *)DBFReadStringAttribute(d, i, 2));
    fprintf(fp, "      <Polygon>\n");
    fprintf(fp, "        <extrude>1</extrude>\n");
    fprintf(fp, "        <altitudeMode>relativeToGround</altitudeMode>\n");
    fprintf(fp, "        <outerBoundaryIs>\n");
    fprintf(fp, "          <LinearRing>\n");
    fprintf(fp, "            <coordinates>\n");
    
    SHPObject	*psShape = SHPReadObject(h, i);
    int j, iPart;
    for (j = 0, iPart = 1; j < psShape->nVertices; j++)
    {
      fprintf(fp, "%f,%f,100\n", psShape->padfX[j], psShape->padfY[j]);
    }
    
    fprintf(fp, "            </coordinates>\n");
    fprintf(fp, "          </LinearRing>\n");
    fprintf(fp, "        </outerBoundaryIs>\n");
    fprintf(fp, "      </Polygon>\n");
    fprintf(fp, "    </Placemark>\n");
  }
  fprintf(fp, "  </Document>\n");
	
  /*int nShapeType;
  int nEntities;
  const char *pszPlus;
  double adfMinBound[4], adfMaxBound[4];
	
  SHPGetInfo(h, &nEntities, &nShapeType, adfMinBound, adfMaxBound);
  printf("SHP has %d entities\n", nEntities);
  
  for (i = 0; i < nEntities; i++)
  {
    SHPObject	*psShape = SHPReadObject(h, i);
    
    //fprintf(fp, "INSERT INTO edges (id) VALUES (%d);\n", i+1);
    
    int j, iPart;
    for (j = 0, iPart = 1; j < psShape->nVertices; j++)
    {
      const char *pszPartType = "";
      
      if (j == 0 && psShape->nParts > 0) pszPartType = SHPPartTypeName(psShape->panPartType[0]);
      if (iPart < psShape->nParts && psShape->panPartStart[iPart] == j)
      {
        pszPartType = SHPPartTypeName(psShape->panPartType[iPart]);
        iPart++;
        pszPlus = "+";
      }
      else
        pszPlus = " ";
      
      //if (j%500==0)
      //  fprintf(fp, "%sINSERT INTO vertexes (edge_id, x, y) VALUES (", (j!=0 ? ");\n": ""));
      //else
      //  fprintf(fp, "),(");
      
      //fprintf(fp, "%d, %f, %f", i+1, psShape->padfX[j], psShape->padfY[j]);
    }
    //fprintf(fp, ");\n");
    
    SHPDestroyObject(psShape);
  }*/
  
  fprintf(fp, "</kml>\n");
	printf("all done\n");
  
  fclose(fp);
  
	if (h != NULL) SHPClose(h);
	if (d != NULL) DBFClose(d);
}
예제 #27
0
int main( int argc, char ** argv )

{
    SHPHandle	hSHP;
    SHPTree	*psTree;
    int		nExpandShapes = 0;
    int		nMaxDepth = 0;
    int		nDoSearch = 0;
    double	adfSearchMin[4], adfSearchMax[4];
    

/* -------------------------------------------------------------------- */
/*	Consume flags.							*/
/* -------------------------------------------------------------------- */
    while( argc > 1 )
    {
        if( strcmp(argv[1],"-v") == 0 )
        {
            nExpandShapes = 1;
            argv++;
            argc--;
        }
        else if( strcmp(argv[1],"-maxdepth") == 0 && argc > 2 )
        {
            nMaxDepth = atoi(argv[2]);
            argv += 2;
            argc -= 2;
        }
        else if( strcmp(argv[1],"-search") == 0 && argc > 5 )
        {
            nDoSearch = 1;

            adfSearchMin[0] = atof(argv[2]);
            adfSearchMin[1] = atof(argv[3]);
            adfSearchMax[0] = atof(argv[4]);
            adfSearchMax[1] = atof(argv[5]);

            adfSearchMin[2] = adfSearchMax[2] = 0.0;
            adfSearchMin[3] = adfSearchMax[3] = 0.0;

            if( adfSearchMin[0] > adfSearchMax[0]
                || adfSearchMin[1] > adfSearchMax[1] )
            {
                printf( "Min greater than max in search criteria.\n" );
                Usage();
            }
            
            argv += 5;
            argc -= 5;
        }
        else
            break;
    }

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( argc < 2 )
    {
        Usage();
    }

/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    hSHP = SHPOpen( argv[1], "rb" );

    if( hSHP == NULL )
    {
	printf( "Unable to open:%s\n", argv[1] );
	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Build a quadtree structure for this file.                       */
/* -------------------------------------------------------------------- */
    psTree = SHPCreateTree( hSHP, 2, nMaxDepth, NULL, NULL );

/* -------------------------------------------------------------------- */
/*      Trim unused nodes from the tree.                                */
/* -------------------------------------------------------------------- */
    SHPTreeTrimExtraNodes( psTree );
        
/* -------------------------------------------------------------------- */
/*      Dump tree by recursive descent.                                 */
/* -------------------------------------------------------------------- */
    if( !nDoSearch )
        SHPTreeNodeDump( psTree, psTree->psRoot, "", nExpandShapes );

/* -------------------------------------------------------------------- */
/*      or do a search instead.                                         */
/* -------------------------------------------------------------------- */
    else
        SHPTreeNodeSearchAndDump( psTree, adfSearchMin, adfSearchMax );

/* -------------------------------------------------------------------- */
/*      cleanup                                                         */
/* -------------------------------------------------------------------- */
    SHPDestroyTree( psTree );

    SHPClose( hSHP );

#ifdef USE_DBMALLOC
    malloc_dump(2);
#endif

    exit( 0 );
}
예제 #28
0
파일: shpinfo.c 프로젝트: dranch/Xastir
int main( int argc, char ** argv )

{
    SHPHandle	hSHP;
//    SHPHandle   cSHP;
    int		nShapeType, nEntities;
//    int     nVertices, nParts, *panParts, i, iPart;
    double	adfBndsMin[4], adfBndsMax[4];
//    double  *padVertices;
//    const char 	*pszPlus;
//    int		cShapeType, cEntities, cVertices, cParts, *cpanParts, ci, cPart;
//    double	*cpadVertices, cadBounds[4];
//    const char 	*cpszPlus;
    char	sType [15]= "";
/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( argc != 2 )
    {
	printf( "shpinfo shp_file\n" );
	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    hSHP = SHPOpen( argv[1], "rb" );

    if( hSHP == NULL )
    {
	printf( "Unable to open:%s\n", argv[1] );
	exit( 1 );
    }

    SHPGetInfo( hSHP, &nEntities, &nShapeType, adfBndsMin, adfBndsMax );
    
    switch ( nShapeType ) {
       case SHPT_POINT:
		strcpy(sType,"Point");
		break;

       case SHPT_ARC:
		strcpy(sType,"Polyline");
		break;

       case SHPT_POLYGON:
		strcpy(sType,"Polygon");
		break;

       case SHPT_MULTIPOINT:
		strcpy(sType,"MultiPoint");
		break;
        }

/* -------------------------------------------------------------------- */
   printf ("Info for %s\n",argv[1]);
   printf ("%s(%d), %d Records in file\n",sType,nShapeType,nEntities);

/* -------------------------------------------------------------------- */
/*      Print out the file bounds.                                      */
/* -------------------------------------------------------------------- */
    printf( "File Bounds: (%15.10lg,%15.10lg)\n\t(%15.10lg,%15.10lg)\n",
	    adfBndsMin[0], adfBndsMin[1], adfBndsMax[0], adfBndsMax[1] );



    SHPClose( hSHP );
    return(0);
}
예제 #29
0
int main( int argc, char ** argv )

{
    SHPHandle	hSHP;
    int		nShapeType, nEntities, i, iPart, bValidate = 0,nInvalidCount=0;
    int         bHeaderOnly = 0;
    const char 	*pszPlus;
    double 	adfMinBound[4], adfMaxBound[4];

    if( argc > 1 && strcmp(argv[1],"-validate") == 0 )
    {
        bValidate = 1;
        argv++;
        argc--;
    }

    if( argc > 1 && strcmp(argv[1],"-ho") == 0 )
    {
        bHeaderOnly = 1;
        argv++;
        argc--;
    }

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( argc != 2 )
    {
        printf( "shpdump [-validate] [-ho] shp_file\n" );
        exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    hSHP = SHPOpen( argv[1], "rb" );

    if( hSHP == NULL )
    {
        printf( "Unable to open:%s\n", argv[1] );
        exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Print out the file bounds.                                      */
/* -------------------------------------------------------------------- */
    SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound );

    printf( "Shapefile Type: %s   # of Shapes: %d\n\n",
            SHPTypeName( nShapeType ), nEntities );
    
    printf( "File Bounds: (%.15g,%.15g,%.15g,%.15g)\n"
            "         to  (%.15g,%.15g,%.15g,%.15g)\n",
            adfMinBound[0], 
            adfMinBound[1], 
            adfMinBound[2], 
            adfMinBound[3], 
            adfMaxBound[0], 
            adfMaxBound[1], 
            adfMaxBound[2], 
            adfMaxBound[3] );

/* -------------------------------------------------------------------- */
/*	Skim over the list of shapes, printing all the vertices.	*/
/* -------------------------------------------------------------------- */
    for( i = 0; i < nEntities && !bHeaderOnly; i++ )
    {
        int		j;
        SHPObject	*psShape;

        psShape = SHPReadObject( hSHP, i );

        if( psShape == NULL )
        {
            fprintf( stderr,
                     "Unable to read shape %d, terminating object reading.\n",
                    i );
            break;
        }

        if( psShape->bMeasureIsUsed )
            printf( "\nShape:%d (%s)  nVertices=%d, nParts=%d\n"
                    "  Bounds:(%.15g,%.15g, %.15g, %.15g)\n"
                    "      to (%.15g,%.15g, %.15g, %.15g)\n",
                    i, SHPTypeName(psShape->nSHPType),
                    psShape->nVertices, psShape->nParts,
                    psShape->dfXMin, psShape->dfYMin,
                    psShape->dfZMin, psShape->dfMMin,
                    psShape->dfXMax, psShape->dfYMax,
                    psShape->dfZMax, psShape->dfMMax );
        else
            printf( "\nShape:%d (%s)  nVertices=%d, nParts=%d\n"
                    "  Bounds:(%.15g,%.15g, %.15g)\n"
                    "      to (%.15g,%.15g, %.15g)\n",
                    i, SHPTypeName(psShape->nSHPType),
                    psShape->nVertices, psShape->nParts,
                    psShape->dfXMin, psShape->dfYMin,
                    psShape->dfZMin,
                    psShape->dfXMax, psShape->dfYMax,
                    psShape->dfZMax );

        if( psShape->nParts > 0 && psShape->panPartStart[0] != 0 )
        {
            fprintf( stderr, "panPartStart[0] = %d, not zero as expected.\n",
                     psShape->panPartStart[0] );
        }

        for( j = 0, iPart = 1; j < psShape->nVertices; j++ )
        {
            const char	*pszPartType = "";

            if( j == 0 && psShape->nParts > 0 )
                pszPartType = SHPPartTypeName( psShape->panPartType[0] );
            
            if( iPart < psShape->nParts
                && psShape->panPartStart[iPart] == j )
            {
                pszPartType = SHPPartTypeName( psShape->panPartType[iPart] );
                iPart++;
                pszPlus = "+";
            }
            else
                pszPlus = " ";

            if( psShape->bMeasureIsUsed )
                printf("   %s (%.15g,%.15g, %.15g, %.15g) %s \n",
                       pszPlus,
                       psShape->padfX[j],
                       psShape->padfY[j],
                       psShape->padfZ[j],
                       psShape->padfM[j],
                       pszPartType );
            else
                printf("   %s (%.15g,%.15g, %.15g) %s \n",
                       pszPlus,
                       psShape->padfX[j],
                       psShape->padfY[j],
                       psShape->padfZ[j],
                       pszPartType );
        }

        if( bValidate )
        {
            int nAltered = SHPRewindObject( hSHP, psShape );

            if( nAltered > 0 )
            {
                printf( "  %d rings wound in the wrong direction.\n",
                        nAltered );
                nInvalidCount++;
            }
        }
        
        SHPDestroyObject( psShape );
    }

    SHPClose( hSHP );

    if( bValidate )
    {
        printf( "%d object has invalid ring orderings.\n", nInvalidCount );
    }

#ifdef USE_DBMALLOC
    malloc_dump(2);
#endif

    exit( 0 );
}
예제 #30
0
파일: shape.c 프로젝트: peko/tttm2
countries_v
shape_load_countries(const char* filename) {

    countries_v countries;
    kv_init(countries);

    double  adfMinBound[4],
            adfMaxBound[4];

    // Read file
    SHPHandle hSHP = SHPOpen( filename, "rb" );
    if(hSHP == NULL) goto end_loading;

    // Print shape bounds
    int country_count, shapes_vype;
    SHPGetInfo( hSHP, &country_count, &shapes_vype, adfMinBound, adfMaxBound );
    
    fprintf(stderr, "Load %d countries\n", country_count);
    // Iterate through countries
    for(int i = 0; i < country_count; i++ ) {
                        
        SHPObject *shp = SHPReadObject(hSHP, i);
        if(shp == NULL) goto end_loading;

        if(shp->nParts == 0) continue;

        // first part starts at point 0
        if(shp->panPartStart[0] != 0) goto end_loading;

        // collect parts of country
        shapes_v shapes;
        kv_init(shapes);
        shapes.min = (point_t){shp->dfXMin, shp->dfYMin};
        shapes.max = (point_t){shp->dfXMax, shp->dfYMax};

        uint32_t parts = shp->nParts;
        double k = 0.0;
        for (uint32_t j=0; j<parts; j++) {
            // start index
            uint32_t s = shp->panPartStart[j];
            // end index - start of next minus one, or end
            uint32_t e = (j+1 < parts) ?
                shp->panPartStart[j+1]:
                shp->nVertices;
            shape_v shape;
            kv_init(shape);
            // collect points of part
            for(uint32_t i=s; i<e; i++){
                point_t p = (point_t){shp->padfX[i], shp->padfY[i]};
                kv_push(point_t, shape, p);
                // cumulitive average for center
                if(k>=1.0) {
                    shapes.center.x = (k-1.0)/k*shapes.center.x + p.x/k;
                    shapes.center.y = (k-1.0)/k*shapes.center.y + p.y/k;
                }else {
                    shapes.center.x = p.x;
                    shapes.center.y = p.y;
                }
                k+=1.0;
            }
            kv_push(shape_v, shapes, shape);
        }
        SHPDestroyObject( shp );
        kv_push(shapes_v, countries, shapes);
    }
    SHPClose( hSHP );

end_loading:
    return countries;
}