Using a
DataSet
to read XML is not very flexible. Try using
System.Xml.Linq[
^] to parse the XML instead.
DataTable dtCoordinates = new DataTable();
dtCoordinates.Columns.AddRange(new[] {
new DataColumn("Id", typeof(string)),
new DataColumn("Address", typeof(string)),
new DataColumn("Latitude", typeof(double)),
new DataColumn("Longitude", typeof(double)),
new DataColumn("City", typeof(string)),
new DataColumn("ZipCode", typeof(string))
});
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + Uri.EscapeDataString(completeAdd) + "&sensor=false";
XDocument document = XDocument.Load(url);
XElement result = document.Root == null ? null : document.Root.Element("result");
if (result != null)
{
string placeId = (string)result.Element("place_id");
string formattedAddress = (string)result.Element("formatted_address");
string city = (string)result
.Elements("address_component")
.Where(ac => ac.Elements("type").Any(t => t.Value == "locality"))
.Elements("long_name")
.FirstOrDefault()
;
string zipCode = (string)result
.Elements("address_component")
.Where(ac => ac.Elements("type").Any(t => t.Value == "postal_code"))
.Elements("long_name")
.FirstOrDefault()
;
var location = result.Elements("geometry").Elements("location").FirstOrDefault();
double? latitude = location == null ? default(double?) : (double?)location.Element("lat");
double? longitude = location == null ? default(double?) : (double?)location.Element("lng");
dtCoordinates.Rows.Add(placeId, formattedAddress, latitude, longitude, city, zipCode);
}
return dtCoordinates;