Point in polygon = place in country
I am planning an application involving an interactive map of the world
which requires identifying the country under the cursor.
I think I have an idea of a viable and efficient algorithm for this. A
slight complication is that in general countries may lie inside each
other. For example Lesotho lies entirely within South Africa.
My map data structure would thus include a (dynamic) array of points
for each country, an index for it, and a smallest bounding rectangle
for it, easily computed on the fly as I read the points. First I
iterate through my list of countries looking for bounding rectangle
hits using very simple code. Very often (most cases) I will only get
one such hit (or no hits if I am at sea), in which case I have nothing
further to do. In the case I have two or more such hits I must return
and test for polygonal hits withing those bounding rectangles: if I
get a hit I compute the area of the bounding rectangle. If I only get
one polygonal hit I am done, while if I get more (i.e. country within
a country) I select the one with the smallest bounding rectangle area
(I'm not sure if that takes care of pathological cases, but it will do
for my application).
To perform my polygonal hit I propose to use the Windows PtInRgn
function I've recently discovered. I've been successful in using this
function but my problem is I'm not sure I'm using it efficiently and
this where I would much appreciate help. I know nothing about Windows
programming and the Windows reference is very coy about what an HRgn
actually is, although I have managed to fathom they are very large -
typically several kilobytes for a random triangle on the screen.
Specifically I appreciate the need to DeleteObject to free resources
after performing PtInRgn. But do I need to SelectObject as well after
CreatePolygonRgn? Also from what I can make out of the documentation I
am supposed to restore the last selected object of HRgn type. But I
have no idea of what that would be before I perform my first polygon
hit test or how I could get hold it. I have to be clear I'm doing this
right because the build up in wasted resources could be huge in a
session with my application.
Help greatly appreciated: we are alone in this wide world, else I
would ask colleagues.
sincerely,
William Boyd