0

Consider the following:

  • Point A DbGeography (office address)
  • Point B DbGeography (customer's address outside of office's service area)
  • Polygon C DbGeography (office's service area)

Using the above points and polygon, how can I find the closest distance of B to C's edge? I assume that first I need to find the line between A and B, then find where the line intersects C (= D) and then calculate the distance from D to B?

Since my usage of SQL Server's spatial capabilities is limited and I'm using Entity Framework, I'm not sure how to express that in code. I also assume that I'd have to use SqlGeography for this since DbGeography is kind of limited. I'd probably end up writing an extension to DbGeography.

I'd appreciate any suggestions (would love code examples) of how I can accomplish the above task.

Gup3rSuR4c
  • 9,145
  • 10
  • 68
  • 126

1 Answers1

2

So, after messing around with this for the past three hours, I found a solution. Here's the code for anyone who cares:

public static class DbGeographyExtensions {
    /// <summary>
    /// Returns a double? value containing the shortest distance from the edge of this polygon to the specified point
    /// </summary>
    public static double? ToShortestDistanceFromPoint(
        this DbGeography polygon,
        DbGeography point) {
        if ((polygon != null)
            && (point != null)) {
            /// Convert the DbGeography to SqlGeography
            SqlGeography sqlPolygon = SqlGeography.STPolyFromText(new SqlChars(polygon.AsText()), polygon.CoordinateSystemId);
            SqlGeography sqlPoint = SqlGeography.STPointFromText(new SqlChars(point.AsText()), point.CoordinateSystemId);

            /// Get the shortest line from the edge of the polygon to the point
            SqlGeography shortestPoint = sqlPoint.ShortestLineTo(sqlPolygon);

            /// Return the length of the line (distance returns 0 because it excludes the area of the line)
            return (double?)shortestPoint.STLength();
        }

        return null;
    }
}
Gup3rSuR4c
  • 9,145
  • 10
  • 68
  • 126