I have a custom class that extends NSObject
and implements the MKOverlay
protocol. As a result, I need to implement the protocol's boundingMapRect
property which is an MKMapRect
. To create an MKMapRect
I can of course use MKMapRectMake
to make one. However, I don't know how to create an MKMapRect
using that data I have which is two points, each specified by a latitude and longitude. MKMapRectMake
's docs state:
MKMapRect MKMapRectMake( double x, double y, double width, double height ); Parameters x The point along the east-west axis of the map projection to use for the origin. y The point along the north-south axis of the map projection to use for the origin. width The width of the rectangle (measured using map points). height The height of the rectangle (measured using map points). Return Value A map rectangle with the specified values.
The latitude and longitude values I have to spec out the MKMapRect
are:
24.7433195, -124.7844079 49.3457868, -66.9513812
The target MKMapRect
would therefore need to spec out an area that looks about like this:
So, to reiterate, how do I use my lat/lon values to create an MKMapRect
that I can set as MKOverlay
protocol's @property (nonatomic, readonly) MKMapRect boundingMapRect
property?
This should do it:
// these are your two lat/long coordinates CLLocationCoordinate2D coordinate1 = CLLocationCoordinate2DMake(lat1,long1); CLLocationCoordinate2D coordinate2 = CLLocationCoordinate2DMake(lat2,long2); // convert them to MKMapPoint MKMapPoint p1 = MKMapPointForCoordinate (coordinate1); MKMapPoint p2 = MKMapPointForCoordinate (coordinate2); // and make a MKMapRect using mins and spans MKMapRect mapRect = MKMapRectMake(fmin(p1.x,p2.x), fmin(p1.y,p2.y), fabs(p1.x-p2.x), fabs(p1.y-p2.y));
this uses the lesser of the two x and y coordinates for your start point, and calculates the x/y spans between the two points for the width and height.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With