Get Zip Code from GPS data

I am currently working on a Windows Phone 7 (WP7) app and I essentially needed to get two pieces of information for the idea to get off the ground. First I need a way to get the the current GPS coordinates from the phone and secondarily I needed to be able to translate that GPS coordinate into a zip code.

As of this writing there are very few physical WP7 devices available to test with, and while Microsoft have done a great job in sending these phones to the press and the big players in the smart phone industry that does not help people like me. I am aware that the Visual Studio Express tool contains a good Emulator, however, it does not provide you access to the GPS backbone, as a result I will wait to offer suggestions on the code.

Get Zip Code (Postal Code) information from the longitude and latitude

Once we have the GPS data from the phone we can pull the zip code information from GPS (reverse geocode) using the Bing Maps API, specifically the Geocode Service. In order to access this service you will need to sign up at the Bing Maps Account Center (requires a Live ID), and subsequently get a Bing Maps key for authentication (review the terms of use carefully).

private void MakeReverseGeocodeRequest(double latitude, double longitude)
	string Results = "";

		// Set up you Bing Maps key here...
	        string key = "....."; 

                GeocodeService.ReverseGeocodeRequest reverseGeocodeRequest = 
                                new GeocodeService.ReverseGeocodeRequest();
                reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
                reverseGeocodeRequest.Credentials.ApplicationId = key; //apply the key

                // Set the long and lat
                GeocodeService.Location point = new GeocodeService.Location();
       	        point.Latitude = latitude;
                point.Longitude = longitude;

                reverseGeocodeRequest.Location = point;

                // Make the reverse geocode request
                GeocodeService.GeocodeServiceClient geocodeService =
                	new GeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
                GeocodeService.GeocodeResponse geocodeResponse = 
		//Postal Code is one of the properties of the Address
		Results = geocodeResponse.Results[0].Address.PostalCode;
      	catch (Exception ex)
		Results = "An exception occurred: " + ex.Message;

UPDATE: This is not the code I would use in a Windows Phone environment, I would probably perform some form of callback. My next post will explain further.

Comment Section

Comments are closed.