Getting address from postal code

by Chandu Thota

Related link: http://www.csthota.com




So, how to get an address from any given postal code using MapPoint Web Service? There is no direct one-method call that can accomplish this; you have to combine two methods, FindPlace and GetLocationInfo from the FindServiceSoap class, to get the address of a zip code/postal code.

Here is a sample that shows how to do accomplish it:


private Address GetAddressFromZipCode(string zipCode)
{
Address address = null;
FindServiceSoap findService = new FindServiceSoap();
FindSpecification spec = new FindSpecification();
spec.DataSourceName = "MapPoint.NA";
spec.InputPlace = zipCode;

string[] entityNames = new string[4];
entityNames[0] = "Postcode1";
entityNames[1] = "Postcode2";
entityNames[2] = "Postcode3";
entityNames[3] = "Postcode4";

spec.EntityTypeNames = entityNames;

spec.Options = new FindOptions();
findService.Credentials = new System.Net.NetworkCredential(myUserId, mySecurePassword);
FindResults findRes = findService.Find(spec);
if(findRes.NumberFound > 0)
{
LatLong ll = findRes.Results[0].FoundLocation.LatLong;
GetInfoOptions options = new GetInfoOptions();
options.IncludeAddresses = true;
options.IncludeAllEntityTypes = false;
Location[] locations = findService.GetLocationInfo(ll, "MapPoint.NA", options);
foreach(Location location in locations)
{
if(location != null && location.Address != null)
{
address = location.Address;
break;
}
}
}
return address;
}


The GetInfoOptions here is important since that's where we are requesting the addresses for returned locations and also limiting the SOAP response packet size. The IncludeAllEntityTypes is set to true by default and this causes too many location results to be returned. So, setting it to false is a good idea if you just want the city, state and country details from a zip code. For example, searching for address for zip code 98052 returned 15 locations when IncludeAllEntityTypes set to true and returned only 4 locations when set to false!


Now, do you have a better way of finding an address for any given postal code? Discuss it here!