area calculation using lat/long in UIMapview - ios

I am trying to find area of MKPolygonView object added to MapView. Apple documentation has method distanceFromLocation: to find distance between edges of MKPolygonView object. But I could not find anything to calculate area of the overlay.
Does Apple have any documented method for finding area?

Concerning the comments on the question post, the Earth is not a perfect sphere either. In fact, it's not a perfect anything, so "correct" answers aren't possible. What matters is how accurate of an approximation you need. Also, are you interested in a mean sea level type measurement, or do you want the actual contours of the ground (for example if your polygon is put over a mountain, then the same exact size polygon is put over some plains, should the result you calculate be the same or different)?
Depending on how big your polygon is, and which measurement you're looking for, a 2D approximation can be pretty accurate (the smaller the polygon, the closer you'll get). Something to keep in mind, if you want your area in something like square feet, the distance between two longitudinal lines is not constant (63 deg west and 62 deg west are closer (in feet) somewhere in Alaska than they are at the equator). You might have to do a unit conversion to handle this depending on how big your polygon is (or if your polygon could be placed anywhere). If you can't do the 2D approximation, I'm not even sure how you'd do that.
When I did this, I did the 2D approx, and I had to do the unit conversion. If that's the way you go, I can try to dig up some of my old notes and the links I used to get you started.

Related

Translating Lat/Lon coordinates to X,Y plane, with control points

I have an arbitrary map image, which may or may not be accurately projected to some standard geographic mapping. Probably not, though, since it's an artists rendition. Consider this map a 2D image of pixels at 0,0 onward.
I'd like to map lat/lon points in world space to this map. Since the map is not necessarily a known or accurate projection, I've got to come up with some other solution. I figure that establishing control points on the 2D image that correlate to known lat/lon values is step #1. At a minimum, 3, but maybe more, in case it's required to sort out distortion in the map image.
What algorithm or equation would I be looking for to take these control points, and identify the X,Y position on the image from any given lat/lon input?
I expect it to be inaccurate, depending on the number of control points. And I expect, for some weirder images, to have to go and add many control points in certain areas to make it line up right.
When the area depicted is small, (e.g. it fits in a square few km on the side), one thing to try is described below. I'm sorry if you find the description too terse, I wanted to keep it reasonably short.
The idea is to assume the image is in some unknown conformal projection, and to try to approximate it. Of course this may fail, if the image can not, in fact, be reasonably approximated this way.
Given your control points P[], project them into map coordinates Q[] using some conformal projection, and get hold of their image coordinates R[]. To within a metre or so -- given the assumption above -- the R[] can be obtained from the Q[] by a transformation T that is a translation, an (isotropic) scaling and a rotation. You can then find T, say by least squares, using the Q[] and R[]. You have a two stage map from the control point geographic coordinates P[] to their image coordinates R[]: first project using the chosen projection, then apply T. You could use the inverse of this map to go from arbitrary image coordinates to geographical coordinates.
If the image is larger than a few km, you may not get enough accuracy this way. All is not lost. Though a translation, scale and rotation may not suffice, any two conformal projections are related by a (complex) analytic map. So you could try to fit (an approximation to) this map using the control points as above. A suitable approximation might be a complex polynomial, or a complex rational function.
If I were doing this, I think I would first test it on artificial data. For example you could generate images of various sizes, using some projection (differing from the one used above), and see how well you fit the known points in these images.

Calculate angle between three GPS coordinates

perhaps this is a simple question.
I have 3 GPS coordinates (one is the current user location). What I want now is to calculate the angle between the user location and the two GPS coordinates. Imagine the user location in the center of the two other points, the three points can be seen as a triangle. And I want to calculate the angle at the user location.
I hope someone can help me because I have no idea how to do this with spherical coordinates like the GPS coordinates I have.
THX - nekro
For short distances (less than 100km, say) you can safely ignore the spherical nature of the calculation and treat the problem as a 2 cartesian coordinate problem. For large distances the spherical geometry gets pretty gnarly. I could probably figure it out, but I don't want to think that hard right now.
Edit:
All you need to do is to convert both coordinates to KM, and then treat it as a cartesian problem. (At a small scale, you can ignore the curved nature of the "lines" and treat them as normal cartesian grid lines, since the curvature is small enough to ignore at that scale)
The distance per degree of latitude is constant. The distance for a degree of longitude changes based on latitude.
Do a google search on "KM per degree of longitude" and find a link that explains it clearly. Here's one: http://www.colorado.edu/geography/gcraft/warmup/aquifer/html/distance.html
You could use thessien polygons and calculate the geometry on those from a strictly GIS perspective. If you have qgis or arcgis this should be fairly simple. These packages offer APIs which might suit your needs.
You're essentially doing two calculations (bearing to (or from) current position to two other positions) and not crosstrack (distance from a great circle line between to other points).
However, both can be found in Ed William's Aviation Formulary which has the most comprehensive collection of formulas for spherical calculations I've found.
You would be looking for "Course between points" which is listed as:
tc1=mod(atan2(sin(lon1-lon2)*cos(lat2),
cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon1-lon2)), 2*pi)

Finding the geometric mean of points on a globe

I'm starting a project where I am mapping a set of points on the Earth using google maps. I want to find the point on the globe which is the average (shortest total distance to all points), but I'm unsure how to handle it considering the distance may be shorter going the other way around the earth. (-178 degrees to 178 degrees longitude is only 4 degrees longitude apart, not 356). What is the best way to approach this, either via an api call or from a mathematical perspective?
I highly doubt there is a slick geometric argument giving a closed form expression for the desired point. Nonetheless here's a simple-minded algorithm which gives an answer to within any desired precision:
https://gist.github.com/amitkgupta/5019163
If you want a mathematically more satisfying solution, I recommend asking over at http://math.stackexchange.com, or they don't avail you, escalate it to http://mathoverflow.net.
I can suggest simple and fast solution (but not to exact initial task). Find the center of gravity of points, then there may be 2 situations:
it's located at center of sphere - don't know what to do (if initial points distributed close to each other - this will not happen)
in other case - consider vector with center of mass and center of sphere as finish and start points, find where such vector intersects surface of sphere, that point - is the answer.
So, you'll get point somewhat similar to 'mid-point', but only in cases when surface under consideration is very small (may be all point lay within the same city). But it is also has nothing to do with minimal average distances from result to initial points.

Metric for ellipse fitting in OpenCV

OpenCV has a nice in-built ellipse-fitting algorithm called fitEllipse(const Mat& points)
However, it has some major shortcomings, limiting its usefulness. For example, it already requires selected points, so I already have to do a feature extraction myself. HoughCircles detects circles on a given image, pity there is no HoughEllipses.
The other major shortcoming, which stands in the center of my question, is that it does no provide any metric about how accurate the fitting was. It returns an ellipse which best fits the given points, even if the shape does not even remotely look like an ellipse. Is there a way to get the estimated error from the algorithm? I would like to use it as a threshold to filter out shapes which are not even close to be considered ellipses.
I asked this, because maybe there is a simple solution before I try to reinvent the wheel and write my very own fitEllipse function.
If you don't mind getting your hands dirty, you could actually modify the source code for fitEllipse(). The fitEllipse() function uses least-squares to determine the likely ellipses, and the least-squares solution is a tangible distance metric, which is what you want.
If that is something you're willing to do, it would be a very simple code change. Simply add a float whose value is passed back after the function call, where the float stores the current best least-squares value.
fitEllipse gives you the ellipse as a cv::RotatedRect and so you know the angle of rotation of the ellipse, its center and its two axes.
You can compute the sum of the square of the distances between your points and the ellipse, that sum is the metric you are looking for.
The distance between a point and an ellipse is described here http://www.geometrictools.com/Documentation/DistancePointEllipseEllipsoid.pdf and the code is here http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistPointHyperellipsoid.h
You need to go from OpenCV cv::RotatedRect to Ellipse2 of Geometric Tools Engine and then you can compute the distance.
Why don't you do a findContours() to reduce the memory space required? There's your selected points structure right there. If you want to further simplify you can run a ConvexHull() or ApproxPoly() on that. Fit the ellipse to those points, and then I suppose you can check similarity between the two structures to get some kind of estimate. A difference operator between the two Mats would be a (very) rough estimate?
Depending on the application, you might be able to use CAMShift (or mean shift), which fits an ellipse to a region with similar colors.

Will treating MKCoordinateRegion like a rectangle come back to haunt me?

Background: I'm build a series of location-based apps that make heavy use of maps. These maps are annotated with locations fetched from a server, to which I pass regions of the map I need data for (defined as a lat/long and a latDelta/longDelta, much like MKCoordinateRegion, but with a different location of the reference coordinate). I'm writing a bunch of helper methods/classes to use when managing these regions. Compatibility with iOS 3.x is required (meaning MKMapRect is out).
Question: Am I setting myself up for failure by treating MKCoordinateRegions like rectangles? Specifically, I'm treating their geometry as if it was that of a rectangle, assuming they have basically the same properties as rectangles. I've implemented several methods that mirror CGRect's helper methods, such as MKCoordinateRegionUnion/Inset/Outset, etc, and they all pass my unit tests, but I'm starting to question if my underlying assumptions are correct. I know in fact that MKCoordinateRegion does not represent a geometric rectangle, but rather a region of a spherical surface bound by two sets of parallel planes, perpendicular to each other (bonus points if somebody can clue me in on a better term for that).
I'm not experiencing any anomalies yet, but since many apps will be reliant on my understanding of the geometry, I'd rather figure out now if I'm going down the wrong path. The fact that I slept through most of the classes in school dealing with 3d radial geometry doesn't give me much confidence that my intuition is correct.
If you are taking into account the equator, prime meridian and dateline edge cases, I think you will be ok.
Alternatively, you could develop your own MKMapRect like rects. Troy Brant has a great blog post about the how the rects are formed:
http://troybrant.net/blog/2010/01/mkmapview-and-zoom-levels-a-visual-guide/
While the blog post is mainly about zoom levels, all the information there can be used to build up your own map rect library.
As for areas bounded by great circles on the surface of a sphere, they are called spherical polygons. So I guess you could just call them spherical rectangles.

Resources