## GIS中要素的捕捉以及C++实现

double Point2Segment(const OGRPoint &point,OGRPoint& pt0,OGRPoint& pt1)
{
OGRPoint vecD(pt1.getX()-pt0.getX(),
pt1.getY()-pt0.getY());  //线段的向量
OGRPoint vecP(point.getX()-pt0.getX(),point.getY()-pt0.getY());//点到线段起始点的向量
double valueD = sqrt(vecD.getX()*vecD.getX()+vecD.getY()*vecD.getY());
double valueP = sqrt(vecP.getX()*vecP.getX()+vecP.getY()*vecP.getY());
double dotMultiplay = vecD.getX()*vecP.getX()+vecD.getY()*vecP.getY();

double t = dotMultiplay/valueD;  //计算向量的投影

//如果线段开始点接近点point
if (t <= 0)
{
return valueP;
}

//如果线段结束点接近点point
if (t >= valueD)
{
OGRPoint vecP(point.getX()-pt1.getX(),point.getY()-pt1.getY());
return sqrt(vecP.getX()*vecP.getX()+vecP.getY()*vecP.getY());
}

//返回垂足距离
return valueP - t*t/valueD;
}

double Point2LineString(const OGRPoint& point,OGRLineString* poString)
{
double distance = 65535;
for (int i = 0; i < poString->getNumPoints()-1; i ++)
{
OGRPoint pt0, pt1;
poString->getPoint(i,&pt0);
poString->getPoint(i+1,&pt1);

//此处这个矩形作为搜索的一个工具
OGREnvelope envSearch;
envSearch.MinX = point.getX()-distance;
envSearch.MaxX = point.getX()+distance;
envSearch.MinY = point.getY()-distance;
envSearch.MaxY = point.getY()+distance;
OGREnvelope envSegment; //线段所在的矩形
envSegment.MinX = min(pt0.getX(),pt1.getX());
envSegment.MaxX = max(pt0.getX(),pt1.getX());
envSegment.MinY = min(pt0.getY(),pt1.getY());
envSegment.MaxY = max(pt0.getY(),pt1.getY());

//包含在或者与搜索矩形相交的线段才考虑求距离
if (envSearch.Contains(envSegment) ||
envSearch.Intersects(envSegment))
{
double dist = Point2Segment(point,pt0,pt1);
if (distance >= dist)
{
distance = dist;
}
}
}

return distance;
}