简体   繁体   中英

Issue getting latitude and longitude of a given address using google api

My problem is that running the below function on my local webserver all the addresses passed are resolved by latitude and longitude. When I publish on the host, most of these addresses returns an empty string. The address argument is so formatted: "Main Street 550, London"

    public string GetLongitudeAndLatitude(string address, string sensor)
    {
        string urlAddress = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + HttpUtility.UrlEncode(address) + "&sensor=" + sensor;
        string returnValue = "";
        try
        {
            XmlDocument objXmlDocument = new XmlDocument();
            objXmlDocument.Load(urlAddress);
            XmlNodeList objXmlNodeList = objXmlDocument.SelectNodes("/GeocodeResponse/result/geometry/location");
            foreach (XmlNode objXmlNode in objXmlNodeList)
            {
                // GET LONGITUDE 
                returnValue = objXmlNode.ChildNodes.Item(0).InnerText;

                // GET LATITUDE 
                returnValue += "," + objXmlNode.ChildNodes.Item(1).InnerText;
            }
        }
        catch
        {
            // Process an error action here if needed  
        }
        return returnValue;
    }

You are resetting the returnValue for each iteration. Change the code to return all the returned latitudes and longitudes to get the complete collection and compare.

foreach (XmlNode objXmlNode in objXmlNodeList)
{
    // GET LONGITUDE 
    returnValue += "\r\n" + objXmlNode.ChildNodes.Item(0).InnerText;

    // GET LATITUDE 
    returnValue += "," + objXmlNode.ChildNodes.Item(1).InnerText;
}

Also browse to the GoogleMaps url from both your local machine and the server and check if the same XML content is returned? The server may not have internet connection as well.

http://maps.googleapis.com/maps/api/geocode/xml?address=Main%20Street%20550,%20London&sensor=false

I tried this other method, but the problem on the server persist triyng to deserialize properties. The error catched is: "Index was outside the bounds of the array." On local every is ok...

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM