Click here to Skip to main content
15,908,768 members
Articles / Desktop Programming / WPF

WPF Map Control using Data

Rate me:
Please Sign up or sign in to vote.
4.91/5 (54 votes)
28 Jan 2012CPOL4 min read 353.4K   14.9K   141   133
A WPF control that displays data from OpenStreetMap


This article will create a simple WPF control that enables browsing of map data from OpenStreetMap, as well as enabling searching for places and displaying the results on the map.

The attached zip file has both the source code, with documentation, and a sample application.


I needed to allow the user to select various locations in my project but didn't want the user to have to install any other applications (such as Google Earth or Bing Maps 3D). One option was to have a web browser in my application pointing to the online versions, but this didn't feel right. Finally, I looked at OpenStreetMap and was impressed by the maps, but couldn't find any controls to put in my application.

What is OpenStreetMap?

From their Main Wiki page:

OpenStreetMap creates and provides free geographic data such as street maps to anyone who wants them. The project was started because most maps you think of as free actually have legal or technical restrictions on their use, holding back people from using them in creative, productive, or unexpected ways.

Basically, OpenStreetMap is a map made by the community for everybody to use. Also, luckily for me, all the details for the file naming conventions are there for creating our own control. All we have to do is download the relevant 256 x 256 pixel square image tiles for the area we want to look at and stitch them together - simple!


The original version of the code used a method similar to the WinForms DoEvents method to allow queued up messages in the UI to be processed while the images were updating. There was a reason WPF doesn't implement this method because it's not a good idea to do that! This time around, there's a separate class responsible for fetching the images (either from the cache on disk or from the server) and this is called on a background thread (using <a href="">ThreadPool.QueueUserWorkItem</a> to take care of thread creation) and then freezing the BitmapImage. Once frozen, this can be passed back to the UI thread, which updates one tile at a time as needed without blocking.

Using the Code

All the basic functionality for displaying a map and searching is in the MapControl project, however, you will need to create the controls for navigating and for getting the search query from the user. I've made a separate project called SampleApp which does just this, but I must confess my design skills suck.

TileGenerator Class

This class has helper methods to retrieve information from OpenStreetMap and has the following members:

public static class TileGenerator
    // The maximum allowed zoom level.
    public const int MaxZoom = 18;

    // Occurs when the number of downloads changes.
    public static event EventHandler DownloadCountChanged;

    // Occurs when there is an error downloading a Tile.
    public static event EventHandler DownloadError;

    // Gets or sets the folder used to store the downloaded tiles.
    // Note: This should be set before any call to GetTileImage.
    public static string CacheFolder { get; set; }

    // Gets the number of tile images waiting to be downloaded.
    // Note: this is not the same as the number of active downloads.
    public static int DownloadCount { get; }
    // Gets or sets the user agent used to make the tile request.
    // Note: This should be set before any call to GetTileImage.
    public static string UserAgent { get; set; }

    // Returns a valid value for the specified zoom, 
    // in the range of 0 - MaxZoom inclusive.
    public static int GetValidZoom(int zoom);

Before we do anything with any of the map controls, even before trying to call their constructors, we need to set the directory for the tile image cache folder and the user agent we will use to identify ourselves. Here MainWindow is assumed to be the first window loaded but you could instead put this line inside the constructor of the default App class:

public MainWindow()
    // Very important we set the CacheFolder before doing anything so the
    // MapCanvas knows where to save the downloaded files to.
    TileGenerator.CacheFolder = @"ImageCache";
    TileGenerator.UserAgent = "MyDemoApp";

    this.InitializeComponent(); // Because this will create the MapCanvas, it
                                // has to go after the above.

MapCanvas Class

The actual map is displayed inside the MapCanvas, which is inherited from the WPF Canvas control (hence the well thought out name ;) ).

public sealed class MapCanvas : Canvas
    // Identifies the Latitude attached property.
    public static readonly DependencyProperty LatitudeProperty;

    // Identifies the Longitude attached property.
    public static readonly DependencyProperty LongitudeProperty;

    // Identifies the Viewport dependency property. This will be read only.
    public static readonly DependencyProperty ViewportProperty;

    // Identifies the Zoom dependency property.
    public static readonly DependencyProperty ZoomProperty;

    // Gets the visible area of the map in latitude/longitude coordinates.
    public Rect Viewport { get; }

    // Gets or sets the zoom level of the map.
    public int Zoom { get; set; }

    // Gets the value of the Latitude attached property for a given dependency object.
    public static double GetLatitude(DependencyObject obj);

    // Gets the value of the Longitude attached property for a given dependency object.
    public static double GetLongitude(DependencyObject obj);

    // Sets the value of the Latitude attached property for a given dependency object.
    public static void SetLatitude(DependencyObject obj, double value);

    // Sets the value of the Longitude attached property for a given dependency object.
    public static void SetLongitude(DependencyObject obj, double value);

    // Centers the map on the specified coordinates, calculating the required zoom level.
    // The size parameter is the minimum size that must be visible, 
    // centered on the coordinates.
    // i.e. the longitude range that must be visible will be: 
    // longitude +- (size.Width / 2)
    public void Center(double latitude, double longitude, Size size);

    // Creates a static image of the current view.
    public ImageSource CreateImage();

    // Calculates the coordinates of the specified point.
    // The point should be in pixels, relative to the top left corner of the control.
    // The returned Point will be filled with the Latitude in the Y property and
    // the Longitude in the X property.
    public Point GetLocation(Point point);

The main points of interest are the two attached properties that make it a bit easier for positioning child controls (though you can still use the regular Canvas ones such as Canvas.Left, etc.): MapCanvas.Latitude and MapCanvas.Longitude. Using them should be straight forward:

<!-- Make sure you've included a reference to MapControl.dll in your project -->
<!-- and put a reference like the following at the start of the XAML file: -->
<!-- xmlns:map="clr-namespace:MapControl;assembly=MapControl" -->

  <!-- The Top Left corner of the control will be at the specified Latitude + Longitude,
  so set a negative Margin to centralise the control on the coordinates. -->
  <Rectangle Fill="Red" Height="50" Width="50" Margin="-25,-25,0,0"
             map:MapCanvas.Latitude="38.895" map:MapCanvas.Longitude="-77.037" />

Panning and Zooming

The MapCanvas will handle dragging with the mouse and zooming using the scroll wheel, however, you will probably want to add a set of navigation controls as well. To enable this, the MapControl registers itself with the following (self explanatory) standard WPF commands:

  • ComponentCommands.MoveDown
  • ComponentCommands.MoveLeft
  • ComponentCommands.MoveRight
  • ComponentCommands.MoveUp
  • NavigationCommands.DecreaseZoom
  • NavigationCommands.IncreaseZoom

SearchProvider/SearchResult Classes

This SearchProvider class first tries to parse the query for a decimal latitude and longitude (in that order, separated by a comma and/or space) but if that fails will pass the query on to Nominatim to search osm data by name and address. Just to reiterate, it will only try and parse decimal degrees, not degrees minutes seconds.

public sealed class SearchProvider
    // Occurs when the search has completed.
    public event EventHandler SearchCompleted;

    // Occurs if there were errors during the search.
    public event EventHandler<SearchErrorEventArgs> SearchError;

    // Gets the results returned from the most recent search.
    public SearchResult[] Results { get; }

    // Searches for the specified query, localizing the results to the specified
    // area.
    // Note that it only returns true if a search was started. This does not
    // always mean that the method has failed - if a set of valid coordinates
    // were passed as the query then no search will be performed (returning
    // false) but the SearchCompleted event will be raised and the Results will
    // be updated.
    public bool Search(string query, Rect area);

This finally leaves the SearchResult class that, as you would expect, contains information for an individual search result returned from Nominatim.

public sealed class SearchResult
    // Gets the formatted name of the search result.
    public string DisplayName { get; }

    // Gets the index the result was returned from the search.
    public int Index { get; }

    // Gets the latitude coordinate of the center of the search result.
    public double Latitude { get; }

    // Gets the longitude coordinate of the center of the search result.
    public double Longitude { get; }

    // Gets the size of the search's bounding box.
    public System.Windows.Size Size { get; }

Points of Interest

Before using the code or sample application, you should read and make sure you comply with the following:

The way I read it is make sure you put a copyright notice on the map (like the one in the bottom right hand corner of the sample application) and make sure you don't abuse the servers by downloading too much (such as trying to download all the tiles in one go).


  • 27/01/2012 - Allowed the user agent to be specified (complying with the Tile Usage Policy) and removed the DoEvents related code
  • 15/06/2010 - Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

QuestionAnimation on zoom Pin
Julajus21-Mar-24 1:51
Julajus21-Mar-24 1:51 
QuestionAwesome work...question on rotating map Pin
Donovan30-Aug-22 4:08
Donovan30-Aug-22 4:08 
QuestionHow do I get pixel location from Lat/Long? Here is what I tried... Pin
dotnetkurt17-Jan-22 5:55
dotnetkurt17-Jan-22 5:55 
AnswerRe: How do I get pixel location from Lat/Long? Here is what I tried... Pin
dotnetkurt22-Feb-22 6:17
dotnetkurt22-Feb-22 6:17 
SuggestionTile retrieval - need to set User Agent Pin
awgripton20-Jun-20 0:08
awgripton20-Jun-20 0:08 
GeneralRe: Tile retrieval - need to set User Agent Pin
Richard!i!25-Feb-21 5:30
Richard!i!25-Feb-21 5:30 
GeneralRe: Tile retrieval - need to set User Agent Pin
Member 1557631923-Mar-22 5:06
Member 1557631923-Mar-22 5:06 
Questionhow to select boundary using Mapcontrol Dll Pin
Member 1327268228-Jun-17 2:03
Member 1327268228-Jun-17 2:03 
BugBlank grey tile on location selection Pin
Member 103705113-May-17 4:04
Member 103705113-May-17 4:04 
QuestionZooming more than 18 levels Pin
Art7723-Apr-17 8:52
Art7723-Apr-17 8:52 
Questionadding markers Pin
Member 1082874423-Feb-17 12:39
Member 1082874423-Feb-17 12:39 
QuestionHow draw the line on the map Pin
dima__16-Jun-16 2:40
dima__16-Jun-16 2:40 
AnswerRe: How draw the line on the map Pin
Member 129915928-Oct-17 5:18
Member 129915928-Oct-17 5:18 
QuestionWPF Project issue Pin
adeshtalakane6-Jun-16 0:43
adeshtalakane6-Jun-16 0:43 
AnswerRe: WPF Project issue Pin
Member 1557631923-Mar-22 4:35
Member 1557631923-Mar-22 4:35 
QuestionRemove panning functionality Pin
Member 103705118-Jan-16 0:25
Member 103705118-Jan-16 0:25 
QuestionAdding lines Pin
SeattleHeather18-Sep-15 10:57
SeattleHeather18-Sep-15 10:57 
SuggestionUsing other tile providers Pin
Richard V Williams3-Sep-15 23:29
Richard V Williams3-Sep-15 23:29 
Questionaddition Pin
Member 103265141-Jul-15 19:29
professionalMember 103265141-Jul-15 19:29 
QuestionIs possible to add an map overlay? Pin
Simba_945-Feb-15 1:51
Simba_945-Feb-15 1:51 
QuestionGreat Job!!!! Pin
raananv8-Dec-14 17:31
raananv8-Dec-14 17:31 
QuestionWorks a charm - thanks!! Pin
Paul Rahme7-Jul-14 23:45
Paul Rahme7-Jul-14 23:45 
QuestionGet Coordinates on mouse click Pin
boki_thegame19-May-14 10:09
boki_thegame19-May-14 10:09 
AnswerRe: Get Coordinates on mouse click Pin
paulmair20-May-14 9:43
paulmair20-May-14 9:43 
QuestionAdding lines Pin
Ramajayam19899-Feb-14 2:59
Ramajayam19899-Feb-14 2:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.