这是我不久前从 MSDN 改编的一些代码。添加地址文本框和查找按钮以搜索地图。
<TextBox Height="23" Name="txt_address" Width="84" />
<Button Content="Find" Height="23" Margin="0 0 5 0" Name="btn_Find" Width="64" Click="btn_Find_Click" />
按钮点击事件;
private void btn_Find_Click(object sender, RoutedEventArgs e)
{
FindAndDisplayNearbyPOI(Geocode(txt_address.Text));
}
public XmlDocument Geocode(string addressQuery)
{
string BingMapsKey = "You bing key";
string geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + addressQuery + "?o=xml&key=" + BingMapsKey;
XmlDocument geocodeResponse = GetXmlResponse(geocodeRequest);
return geocodeResponse;
}
private XmlDocument GetXmlResponse(string requestURL)
{
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format("Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
return xmlDoc;
}
}
private Microsoft.Maps.MapControl.WPF.Location FindAndDisplayNearbyPOI(XmlDocument xmlDoc)
{
Microsoft.Maps.MapControl.WPF.Location pushpin = new Microsoft.Maps.MapControl.WPF.Location();
// Create namespace manager
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("rest", "http://schemas.microsoft.com/search/local/ws/rest/v1");
// Get all locations in the response and then extract the coordinates for the top location
XmlNodeList locationElements = xmlDoc.SelectNodes("//rest:Location", nsmgr);
if (locationElements.Count == 0)
{
//ErrorMessage.Visibility = Visibility.Visible;
//ErrorMessage.Content = "The location you entered could not be geocoded.";
}
else
{
// Get the geocode points that are used for display (UsageType=Display)
XmlNodeList displayGeocodePoints = locationElements[0].SelectNodes(".//rest:GeocodePoint/rest:UsageType[.='Display']/parent::node()", nsmgr);
string latitude = displayGeocodePoints[0].SelectSingleNode(".//rest:Latitude", nsmgr).InnerText;
string longitude = displayGeocodePoints[0].SelectSingleNode(".//rest:Longitude", nsmgr).InnerText;
pushpin = AddPushpinToMap(Convert.ToDouble(latitude), Convert.ToDouble(longitude), "Cust");
map1.Center = new Microsoft.Maps.MapControl.WPF.Location(Convert.ToDouble(latitude), Convert.ToDouble(longitude));
map1.ZoomLevel = 12;
}
return pushpin;
}
private Microsoft.Maps.MapControl.WPF.Location AddPushpinToMap(double latitude, double longitude, string pinLabel)
{
Microsoft.Maps.MapControl.WPF.Location location = new Microsoft.Maps.MapControl.WPF.Location(latitude, longitude);
Microsoft.Maps.MapControl.WPF.Pushpin pushpin = new Microsoft.Maps.MapControl.WPF.Pushpin();
pushpin.Content = pinLabel;
pushpin.Location = location;
map1.Children.Add(pushpin);
return pushpin.Location;
}