且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从谷歌地图api响应中读取城市和邮政编码

更新时间:2023-02-26 09:32:40

使用数据集读取XML不是很灵活。尝试使用 System.Xml.Linq [ ^ ]来解析XML。



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))
});

// Make sure the address parameter is properly encoded:
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + Uri.EscapeDataString(completeAdd) + "&sensor=false";

// Load the document, and find the "result" node:
XDocument document = XDocument.Load(url);
XElement result = document.Root == null ? null : document.Root.Element("result");

if (result != null)
{
    // TODO: There doesn't seem to be a "result_id" node anywhere in the XML.
    // Assuming you meant the "place_id", which is a string.
    string placeId = (string)result.Element("place_id");
    
    string formattedAddress = (string)result.Element("formatted_address");

    // TODO: I've assumed that "Noida" is the city in your example.
    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;