在vcpkg包管理工具的环境下使用VisualStudio,vcpkg确认已安装gdal:x64-windows库。
#include <drogon/drogon.h>
#include <stdio.h>
#include <stdarg.h>
#include <geos_c.h>
#include <iostream>
#include <math.h>
using namespace std;
static void geos_msg_handler(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
}
double getPointX(double* dxdy) {
return *dxdy;
}
double getPointY(double* dxdy) {
return *(dxdy + 1);
}
double* getPointXY(GEOSGeometry* pt, GEOSWKTWriter* writer) {
char* wkt = GEOSWKTWriter_write(writer, pt);
//在这里,点对应的wkt字符串的小数部分固定是18位字符
char* x = new char[18];
char* y = new char[18];
int state = 0;
int count = 0;
//第7位字符到第43位字符都是数字部分
for (int i = 7; i < 44; i++) {
if (state == 0) {
*(x + count) = wkt[i];
count++;
}
else {
*(y + count) = wkt[i];
count++;
}
if (wkt[i] == ' ') {
count = 0;
state = 1;
}
}
double* dxdy = new double[2];
*dxdy = atof(x);
*(dxdy + 1) = atof(y);
return dxdy;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
initGEOS(geos_msg_handler, geos_msg_handler);
GEOSWKTReader* reader = GEOSWKTReader_create();
GEOSGeometry* line_geo = GEOSWKTReader_read(reader, "LINESTRING(0.512114 0.5,1 1,1.5 1.5,2.5 0.5,4.5 1.5)");
//GEOSGeometry* polygon_geo = GEOSWKTReader_read(reader, "MULTIPOLYGON(((0 0,1 0,1 1,0 1,0 0)),((2 0,3 0,3 1,2 1,2 0)),((4 1,5 1,5 2,4 2,4 1)))");
GEOSGeometry* polygon_geo = GEOSWKTReader_read(reader, "MULTIPOLYGON(((0 0,1 0,1 1,0 1,0 0)),((2 0,3 0,3 1,2 1,2 0)),((4 1,5 1,5 2,4 2,4 1)))");
GEOSGeometry* multi_line = GEOSIntersection(line_geo, polygon_geo);
GEOSWKTWriter* writer = GEOSWKTWriter_create();
int line_num = GEOSGetNumGeometries(multi_line);//线条的个数.
for (int i = 0; i < line_num; i++) {
const GEOSGeometry* line = GEOSGetGeometryN(multi_line, i);
int point_num = GEOSGetNumCoordinates(line);
cout << "第"<<i<<"条线:" << endl;
for (int j = 0; j < point_num; j++) {
GEOSGeometry* pt = GEOSGeomGetPointN(line, j);
double* xy = getPointXY(pt, writer);
cout << "x:" << xy[0] << "\t" << "y:" << xy[1] << endl;
}
}
finishGEOS();
return 0;
}
运行效果: