I was working on a project last night utilizing Bing embeddable Maps and wanted to generate these maps on the fly for some WordPress post automation I was employing. I took the map embed code and tried to simply swap out the address references for each new location. That was a no go. It seems the address is more or less window dressing in the Maps equation. What the Microsoft developers really key off of is the latitude and longitude coordinates nested in the string. So the question became, how can I easily pull these elements into Visual Studio?

Enter Bing Maps API. You can pass the web services the street address, and they’ll pop out the the latitude and longitude along with plenty of other useful info. If you are entertaining this approach for a large scale project, I’d definitely suggest digging into the documentation to take advantage of all the bells and whistles this API has to offer. Here are a few helpful links over on Microsoft’s site.


For our quick and dirty approach, the method below quickly gets at the heart of the matter. As you can see, we pass in all the address elements and reassemble them as parts of the Uri. We created our XMLDocument object (don’t forget you need to import the System.Xml library) then load up the returned XML data block. From here we define the Namespace then drill down via XPath to target the latitude and longitude values returned. I was returning them as one string with a tilda in between. Really painfully simple.

static string GetLatLongFromAddress(string street, string city, string state, string zip)
string bingMapsUri = string.Format(@"http://dev.virtualearth.net/REST/v1/Locations/US/" + Regex.Replace
(street,"#","") + ", " + city + ", " + state + "?o=xml&key=BingMapsKey");
XmlDocument bingMapsXmlDoc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(bingMapsXmlDoc.NameTable);
nsmgr.AddNamespace("rest", "http://schemas.microsoft.com/search/local/ws/rest/v1");
string sLong = bingMapsXmlDoc.DocumentElement.SelectSingleNode(@".//rest:Longitude", nsmgr).InnerText;
string sLat = bingMapsXmlDoc.DocumentElement.SelectSingleNode(@".//rest:Latitude", nsmgr).InnerText;
return sLat + "~" + sLong;

You will notice “key=BingMapsKey.” You’ll need to generate one of these on your Live ID account. Again not painful at all. Just create a maps account and setup a new application. Here is more on procuring a Bing Maps Key:


Like I say, this isn’t going to win any coding awards, but it gets the values you need while getting you on your way to tackle the next step of your project. Happy coding!

Image: Google Maps