Display a Location

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

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

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.