Skip to content

Instantly share code, notes, and snippets.

@TimSC
Last active February 11, 2019 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TimSC/7fb8884dc85753bbb7104d82660f7faf to your computer and use it in GitHub Desktop.
Save TimSC/7fb8884dc85753bbb7104d82660f7faf to your computer and use it in GitHub Desktop.
Basic usage of shapelib
//By Tim Sheerman-Chase, released under CC0
//Compile: g++ shapelib_example.cpp -lshp -o shapelib_example
#include <iostream>
#include <vector>
#include <string>
#include "shapefil.h"
using namespace std;
int main(int argc, const char **argv)
{
string fina = "map.shp";
SHPHandle h = SHPOpen(fina.c_str(), "rb");
if(h==nullptr)
{
cout << "Failed to open shp" << endl;
return -1;
}
int nEntities=0, nShapeType=0;
SHPGetInfo(h, &nEntities, &nShapeType, nullptr, nullptr);
cout << nEntities << endl;
for(int i=0; i<nEntities; i++)
{
SHPObject *obj = SHPReadObject(h, i);
if(obj == nullptr) continue;
int &shpType = obj->nSHPType; //Shape Type (SHPT_* - see list above)
int &shapeId = obj->nShapeId; //Shape Number (-1 is unknown/unassigned)
int &parts = obj->nParts; //# of Parts (0 implies single part with no info)
int *panPartStart = obj->panPartStart; //Start Vertex of part
int *panPartType = obj->panPartType; //Part Type (SHPP_RING if not SHPT_MULTIPATCH)
int &vertices = obj->nVertices; //Vertex list
double &xMin = obj->dfXMin; //Bounds in X, Y, Z and M dimensions
double &yMin = obj->dfYMin;
double &zMin = obj->dfZMin;
double &xMax = obj->dfXMax;
double &yMax = obj->dfYMax;
double &zMax = obj->dfZMax;
cout << SHPTypeName(shpType) << "," << xMin << "," << xMax << "," << yMin << "," << yMax << endl;
cout << i << "," << vertices << "," << parts << endl;
std::vector<int> partStart, partType;
for(int k=0; k<parts; k++)
{
partStart.push_back(panPartStart[k]);
partType.push_back(panPartType[k]);
//cout << panPartStart[k] << "," << SHPPartTypeName(panPartType[k]) << endl;
}
int part = -1;
for(int j=0; j<vertices; j++)
{
if((part+1) < partStart.size() and partStart[part+1] == j)
part ++;
int pt = -1;
if(part >= 0)
pt = partType[part];
//cout << part << "," << obj->padfX[j] << "," << obj->padfY[j] << "," << obj->padfZ[j] << endl;
//cout << SHPPartTypeName(pt) << endl;
}
SHPDestroyObject(obj);
}
SHPClose(h);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment