Given two polygons (point, line, or up to 8 vertices) I need to be able to calculate the shortest distance between them via code I write or a call to an API (I haven't been able to find one that does exactly this). Calculating distance between points is easy, polygons to polygons is much more complex.

Here is what I have come up with so far:

First create a function that calculates distance between a point and a line:

Calculating the distance between a point and a virtual line of two lat/lngs

Next, given shapes A and B, find out if the shapes intersect using a ray casting algorithm. If so then return 0 for distance. If they do not intersect, for every vertex in A, find the distance to every edge in B using the above point-line-distance function. Then repeat process but reversed (Every vertex in B to every edge in A). Then take the shortest of these distances. This seems very expensive though especially if finding distances between large numbers of polygons. I'm wondering if there is a better approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.