I want to be able to retrieve the geographical coordinates (latitude and longitude) for a given address. I'm hoping I can do that if I have the full address (street address + city + state + zip).
If it matters, I am using Bing Maps. The skeleton code I've got is this (fullAddress, AddPushpin(), and getGeoCordsForAddress() are the most pertinent parts):
private void btnSave_Click(object sender, EventArgs e)
{
string fullAddress = string.Empty;
if (MissingValues()) return;
mapName = cmbxMapName.SelectedItem.ToString();
locationName = txtbxLocation.Text;
address = txtbxAddress.Text;
city = txtbxCity.Text;
st8 = txtbxSt8.Text;
zip = txtbxZip.Text;
mapDetailNotes = richtxtbxMapNotes.Text;
fullAddress = string.Format("{0} {1} {2} {3}", address, city, st8, zip);
if (InsertIntoCartographerDetail())
{
MessageBox.Show("insert succeeded");
AddPushpin(fullAddress);
ClearControls();
}
else
{
MessageBox.Show("insert failed");
}
}
private void AddPushpin(string fullAddress)
{
GeoCoordinate geoCoord = getGeoCordsForAddress(fullAddress);
Pushpin pin = new Pushpin();
pin.Location = new Location(geoCoord.Latitude, geoCoord.Longitude);
. . .
}
private GeoCoordinate getGeoCordsForAddress(string fullAddress)
{
GeoCoordinate gc = new GeoCoordinate();
. . . // What goes here?
return gc;
}
Microsoft has an official BingMapsRESTToolkit which helps you to work with Bing Maps REST Services easily. To do so, you need to install BingMapsRESTToolkit NuGet Package.
Here, you are interested in GeocodeRequest to get location by address.
Example - Get latitude and longitude by address and create a pushpin on map
Install BingMapsRESTToolkit NuGet Package and run the following code:
private async void button1_Click(object sender, EventArgs e)
{
var request = new GeocodeRequest();
request.BingMapsKey = "YOUR MAP KEY";
request.Query = "172 Jalan Pinang, 50088 Kuala Lumpur, " +
"Federal Territory of Kuala Lumpur, Malaysia";
//OR
//request.Address = new SimpleAddress()
//{
// CountryRegion = "Malaysia",
// AddressLine = "172 Jalan Pinang",
// AdminDistrict = "Kuala Lumpur, Federal Territory of Kuala Lumpur",
// PostalCode = "50088",
//};
var result = await request.Execute();
if (result.StatusCode == 200)
{
var toolkitLocation = (result?.ResourceSets?.FirstOrDefault())
?.Resources?.FirstOrDefault()
as BingMapsRESTToolkit.Location;
var latitude = toolkitLocation.Point.Coordinates[0];
var longitude = toolkitLocation.Point.Coordinates[1];
var mapLocation = new Microsoft.Maps.MapControl.WPF.Location(latitude, longitude);
this.userControl11.myMap.SetView(mapLocation, 15);
var p = new Pushpin() { Location = mapLocation, ToolTip = "KLCC Park" };
this.userControl11.myMap.Children.Add(p);
}
}
How to use WPF Bing Maps in Windows Forms:
Bing Maps REST Toolkit related resources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With