Using the Bing Maps API in your WP7 App
A while ago I wrote a post detailing how easy it was to use the Bing Maps API to GeoCode an address, which enables you to get the geographical position (Latitude and Longitude) of a location when only given the street address.
This has been invaluable in a number of applications since then including the TrafficMATE app which used street addresses to help create Routes to check for traffic incidents. So how exactly can we get the Lat/Long for a location when only given the street address? Well thankfully it's easy.
As in the previous post, we need to start by adding a Service Reference to our project. The Bing Maps API service that deals with Geocoding is located at http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc
I called the reference Bing.Geocode, but feel free to call it whatever you like.
You will also need to get a developer key to use with the API, but don't worry that's easy too. Chances are that if you have already been using Bing Maps with the Map control in Windows Phone 7 then you already have one of these. If not, go get one at http://www.bingmapsportal.com/
The code that calls the Bing Maps Geocode service is fairly easy. In your XAML all you really need is a TextBox where the user can enter an address and then a Button they click to call the function.
//get lat/long for this address
GeocodeRequest request = new GeocodeRequest();
request.Credentials = new Credentials();
request.Credentials.ApplicationId = YourKey;
request.Query = this.TextBoxOrigin.Text;
GeocodeServiceClient client = new GeocodeServiceClient();
client.GeocodeCompleted += new EventHandler<GeocodeCompletedEventArgs>(client_GeocodeCompleted);
Then all you need to do is interrogate the results sent back from Bing in your GeocodeCompleted event handler.
void client_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
GeocodeResponse response = e.Result;
if (response.Results.Count > 0)
As you can see from the code above, I am simply selecting the first record in the Results array and displaying the Address.FormattedAddress property. Other properties that may be useful are Address.Locality (AKA:Suburb) Address.AdminDistrict (AKA:State).
The other important fields that you will want to process are the Lat and Long. These are contained within the Location array in fields aptly named Latitude and Longitude. These could be easily returned using the syntax response.ResultsLocationLatitude and response.ResultsLocationLongitude.