id | title | brief | sdk | |||||
---|---|---|---|---|---|---|---|---|
DF2AC5D0-D400-A876-7480-810A76E819C2 |
Display a Location |
This recipe shows how to display a location on a map. |
|
To show a location on a map in a MKMapView:
- Create a MKMapView and add it to a view. Setting the AutoresizingMask ensures the control fits nicely in the screen (adjusting for the navigation bar that is added in the sample):
- Add these helper methods to calculate the area to show on the map:
public double MilesToLatitudeDegrees(double miles)
{
double earthRadius = 3960.0; // in miles
double radiansToDegrees = 180.0/Math.PI;
return (miles/earthRadius) * radiansToDegrees;
}
public double MilesToLongitudeDegrees(double miles, double atLatitude)
{
double earthRadius = 3960.0; // in miles
double degreesToRadians = Math.PI/180.0;
double radiansToDegrees = 180.0/Math.PI;
// derive the earth's radius at that point in latitude
double radiusAtLatitude = earthRadius * Math.Cos(atLatitude * degreesToRadians);
return (miles / radiusAtLatitude) * radiansToDegrees;
}
- Create a location coordinate (for example, the latitude & longitude of Paris):
CLLocationCoordinate2D coords = new CLLocationCoordinate2D(48.857, 2.351);
- Determine the area to display (20 miles in this example):
MKCoordinateSpan span = new MKCoordinateSpan(MilesToLatitudeDegrees(20), MilesToLongitudeDegrees(20, coords.Latitude));
- Set the Region property on the map:
mapView.Region = new MKCoordinateRegion(coords, span);
- The map will now show, centered on Paris, France with the default map type (which is the street map).
If you prefer to work in kilometres, it is trivial to convert the helper functions:
/// <summary>Converts kilometres to latitude degrees</summary>
public double KilometresToLatitudeDegrees(double kms)
{
double earthRadius = 6371.0; // in kms
double radiansToDegrees = 180.0/Math.PI;
return (kms/earthRadius) * radiansToDegrees;
}
/// <summary>Converts kilometres to longitudinal degrees at a specified latitude</summary>
public double KilometresToLongitudeDegrees(double kms, double atLatitude)
{
double earthRadius = 6371.0; // in kms
double degreesToRadians = Math.PI/180.0;
double radiansToDegrees = 180.0/Math.PI;
// derive the earth's radius at that point in latitude
double radiusAtLatitude = earthRadius * Math.Cos(atLatitude * degreesToRadians);
return (kms / radiusAtLatitude) * radiansToDegrees;
};