Skip to content
This repository has been archived by the owner on Oct 20, 2022. It is now read-only.

Latest commit

 

History

History

display_a_location

id title brief sdk
DF2AC5D0-D400-A876-7480-810A76E819C2
Display a Location
This recipe shows how to display a location on a map.

Recipe

To show a location on a map in a MKMapView:

  1. 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):
``` mapView = new MKMapView (View.Bounds); mapView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions; View.AddSubview(mapView); ```
  1. 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;
}
  1. Create a location coordinate (for example, the latitude & longitude of Paris):
CLLocationCoordinate2D coords = new CLLocationCoordinate2D(48.857, 2.351);
  1. Determine the area to display (20 miles in this example):
MKCoordinateSpan span = new MKCoordinateSpan(MilesToLatitudeDegrees(20), MilesToLongitudeDegrees(20, coords.Latitude));
  1. Set the Region property on the map:
mapView.Region = new MKCoordinateRegion(coords, span);
  1. The map will now show, centered on Paris, France with the default map type (which is the street map).

Additional Information

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;
};