Beispiel #1
0
        public static void RefineAddressWithGeography(IAddressGeography addr)
        {
            UspsLookupResult usps = GeographyServices.LookupUspsAddress(addr);

            if (usps.Result == LookupResult.Success)
            {
                addr.Quality = (addr.Quality & 0xfff0) | 0x01;
                addr.CopyFrom(usps);

                Match  suffixMatch = Regex.Match(addr.Street, "^(.+) (APT|BSMT|#|BLDG|DEPT|FL|FRNT|HNGR|KEY|LBBY|LOT|LOWR|OFC|PH|PIER|REAR|RM|SIDE|SLIP|SPC|STOP|STE|TRLR|UNIT|UPPR)(.*)$");
                string suffix      = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(suffixMatch.Groups[2].Value.ToLowerInvariant())
                                     + suffixMatch.Groups[3].Value;

                MapsLookupResult maps = GeographyServices.GeocodeAddress(usps);
                if (maps.Result == LookupResult.Success)
                {
                    addr.Quality = (addr.Quality & 0xff0f) | (maps.Quality << 4);
                    string mapsStreet = maps.Street + (suffixMatch.Success ? (" " + suffix) : "");
                    if (addr.Street.Equals(mapsStreet, StringComparison.OrdinalIgnoreCase))
                    {
                        addr.CopyFrom(maps);
                        addr.Street = mapsStreet;
                    }
                    addr.Location = maps.Geography;
                }
            }
        }
        public static MapsLookupResult GeocodeAddress(IAddress addr)
        {
            MapsLookupResult result = new MapsLookupResult { Result = LookupResult.Error };
            if (addr.Street.ToLower().StartsWith("po box"))
            {
                result.Result = LookupResult.NotFound;
                return result;
            }

            WebClient client = new WebClient();
            XmlDocument xml = new System.Xml.XmlDocument();
            string url = string.Format("http://maps.google.com/maps/geo?q={0}&key={1}&output=xml",
                System.Web.HttpUtility.UrlEncode(string.Format("{0}, {1} {2} {3}", addr.Street, addr.City, addr.State, addr.Zip)),
                System.Configuration.ConfigurationManager.AppSettings["MapsKey"]
                );

            xml.LoadXml(client.DownloadString(url));

            XmlElement root = xml.DocumentElement;
            XmlNamespaceManager nsmgr = new
            XmlNamespaceManager(xml.NameTable);
            nsmgr.AddNamespace("k", root.NamespaceURI);
            nsmgr.AddNamespace("d", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0");

            string status = xml.SelectSingleNode("//k:Response/k:Status/k:code", nsmgr).InnerText;
            if (status != "200")
            {
                // Error
            }
            else
            {
                XmlNode details = xml.SelectSingleNode("//d:AddressDetails", nsmgr);

                string accuracyString = ((XmlElement)details).GetAttribute("Accuracy");
                result.Quality = int.Parse(accuracyString);

                result.Result = LookupResult.Range;
                if (result.Quality > 5)
                {
                    result.Result = LookupResult.Success;
                    result.Street = details.SelectSingleNode("//d:ThoroughfareName", nsmgr).InnerText;
                }
                if (result.Quality > 4)
                {
                    result.Zip = details.SelectSingleNode("//d:PostalCodeNumber", nsmgr).InnerText;
                }
                result.City = details.SelectSingleNode("//d:LocalityName", nsmgr).InnerText;
                result.State = details.SelectSingleNode("//d:AdministrativeAreaName", nsmgr).InnerText;

                string[] coords = details.SelectSingleNode("//k:Response/k:Placemark/k:Point", nsmgr).InnerText.Split(',');
                double lat = double.Parse(coords[1]);
                double lng = double.Parse(coords[0]);
                double z = GeographyServices.GetElevation(lat, lng);

                string point = (z > 0) ? string.Format("POINT({0} {1} {2} NULL)", lng, lat, z) : string.Format("POINT({0} {1})", lng, lat);

                result.Geography = SqlGeography.STGeomFromText(new SqlChars(point.ToCharArray()), GeographyServices.SRID);
            }
            return result;
        }
Beispiel #3
0
        public static void RefineAddressWithGeography(IAddressGeography addr)
        {
            MapsLookupResult maps = GeographyServices.GeocodeAddress(addr);

            if (maps.Result == LookupResult.Success)
            {
                addr.Quality  = maps.Quality;
                addr.Location = maps.Geography;
            }
        }
Beispiel #4
0
        public static MapsLookupResult GeocodeAddress(IAddress addr)
        {
            MapsLookupResult result = new MapsLookupResult {
                Result = LookupResult.Error
            };

            if (addr.Street.ToLower().StartsWith("po box"))
            {
                result.Result = LookupResult.NotFound;
                return(result);
            }

            WebClient   client = new WebClient();
            XmlDocument xml    = new System.Xml.XmlDocument();
            string      url    = string.Format("http://maps.google.com/maps/geo?q={0}&key={1}&output=xml",
                                               System.Web.HttpUtility.UrlEncode(string.Format("{0}, {1} {2} {3}", addr.Street, addr.City, addr.State, addr.Zip)),
                                               System.Configuration.ConfigurationManager.AppSettings["MapsKey"]
                                               );

            xml.LoadXml(client.DownloadString(url));

            XmlElement          root  = xml.DocumentElement;
            XmlNamespaceManager nsmgr = new
                                        XmlNamespaceManager(xml.NameTable);

            nsmgr.AddNamespace("k", root.NamespaceURI);
            nsmgr.AddNamespace("d", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0");


            string status = xml.SelectSingleNode("//k:Response/k:Status/k:code", nsmgr).InnerText;

            if (status != "200")
            {
                // Error
            }
            else
            {
                XmlNode details = xml.SelectSingleNode("//d:AddressDetails", nsmgr);

                string accuracyString = ((XmlElement)details).GetAttribute("Accuracy");
                result.Quality = int.Parse(accuracyString);

                result.Result = LookupResult.Range;
                if (result.Quality > 5)
                {
                    result.Result = LookupResult.Success;
                    result.Street = details.SelectSingleNode("//d:ThoroughfareName", nsmgr).InnerText;
                }
                if (result.Quality > 4)
                {
                    result.Zip = details.SelectSingleNode("//d:PostalCodeNumber", nsmgr).InnerText;
                }
                result.City  = details.SelectSingleNode("//d:LocalityName", nsmgr).InnerText;
                result.State = details.SelectSingleNode("//d:AdministrativeAreaName", nsmgr).InnerText;

                string[] coords = details.SelectSingleNode("//k:Response/k:Placemark/k:Point", nsmgr).InnerText.Split(',');
                double   lat    = double.Parse(coords[1]);
                double   lng    = double.Parse(coords[0]);
                double   z      = GeographyServices.GetElevation(lat, lng);

                string point = (z > 0) ? string.Format("POINT({0} {1} {2} NULL)", lng, lat, z) : string.Format("POINT({0} {1})", lng, lat);

                result.Geography = SqlGeography.STGeomFromText(new SqlChars(point.ToCharArray()), GeographyServices.SRID);
            }
            return(result);
        }
Beispiel #5
0
        public static MapsLookupResult GeocodeAddress(IAddress addr)
        {
            MapsLookupResult result = new MapsLookupResult {
                Result = LookupResult.Error
            };
            string url = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?address={0}&key={1}",
                                       System.Web.HttpUtility.UrlEncode(string.Format("{0}, {1} {2} {3}", addr.Street, addr.City, addr.State, addr.Zip)),
                                       System.Configuration.ConfigurationManager.AppSettings["Maps3Key"]
                                       );

            try
            {
                if (addr.Street.ToLower().StartsWith("po box"))
                {
                    result.Result = LookupResult.NotFound;
                    return(result);
                }

                WebClient   client = new WebClient();
                XmlDocument xml    = new System.Xml.XmlDocument();

                xml.LoadXml(client.DownloadString(url));

                string status = xml.SelectSingleNode("/GeocodeResponse/status").InnerText;
                if (status != "OK")
                {
                    throw new InvalidOperationException(xml.OuterXml);
                }
                else
                {
                    var results = xml.SelectNodes("/GeocodeResponse/result");
                    if (results.Count == 0)
                    {
                        LogManager.GetLogger("GeographyServices").InfoFormat("No results for {0}", url);
                        result.Result = LookupResult.NotFound;
                    }
                    else if (results.Count > 1)
                    {
                        result.Result = LookupResult.Range;
                        LogManager.GetLogger("GeographyServices").InfoFormat("Multiple results for {0}", url);
                    }
                    else
                    {
                        result.Result = LookupResult.Success;
                        var coordType = results[0].SelectSingleNode("geometry/location_type").InnerText;
                        if (coordType == "ROOFTOP")
                        {
                            result.Quality = (int)GeocodeQuality.High;
                        }
                        else if (coordType == "RANGE_INTERPOLATED")
                        {
                            result.Quality = (int)GeocodeQuality.Medium;
                        }
                        else
                        {
                            result.Quality = (int)GeocodeQuality.Poor;
                            LogManager.GetLogger("GeographyServices").WarnFormat("Poor quality geocode: {0}", url);
                        }

                        if (result.Quality > (int)GeocodeQuality.Poor)
                        {
                            LogManager.GetLogger("GeographyServices").InfoFormat("Got location: {0},{1}", results[0].SelectSingleNode("geometry/location/lat").InnerText, results[0].SelectSingleNode("geometry/location/lat").InnerText);
                            double lat = double.Parse(results[0].SelectSingleNode("geometry/location/lat").InnerText);
                            double lng = double.Parse(results[0].SelectSingleNode("geometry/location/lng").InnerText);

                            // This call is slow. Might be good to move to background task.
                            // double z = GeographyServices.GetElevation(lat, lng);
                            double z = -100;


                            string point = (z > 0) ? string.Format("POINT({0} {1} {2} NULL)", lng, lat, z) : string.Format("POINT({0} {1})", lng, lat);

                            result.Geography = SqlGeography.STGeomFromText(new SqlChars(point.ToCharArray()), GeographyServices.SRID);
                        }
                    }
                }
            }
            catch (Exception)
            {
                LogManager.GetLogger("GeographyServices").InfoFormat("Error geocoding address: {0}", url);
                throw;
            }
            return(result);
        }
        public static MapsLookupResult GeocodeAddress(IAddress addr)
        {
            MapsLookupResult result = new MapsLookupResult { Result = LookupResult.Error };
              string url = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?address={0}&key={1}",
            System.Web.HttpUtility.UrlEncode(string.Format("{0}, {1} {2} {3}", addr.Street, addr.City, addr.State, addr.Zip)),
            System.Configuration.ConfigurationManager.AppSettings["Maps3Key"]
              );

              try
              {
            if (addr.Street.ToLower().StartsWith("po box"))
            {
              result.Result = LookupResult.NotFound;
              return result;
            }

            WebClient client = new WebClient();
            XmlDocument xml = new System.Xml.XmlDocument();

            xml.LoadXml(client.DownloadString(url));

            string status = xml.SelectSingleNode("/GeocodeResponse/status").InnerText;
            if (status != "OK")
            {
              throw new InvalidOperationException(xml.OuterXml);
            }
            else
            {
              var results = xml.SelectNodes("/GeocodeResponse/result");
              if (results.Count == 0)
              {
            LogManager.GetLogger("GeographyServices").InfoFormat("No results for {0}", url);
            result.Result = LookupResult.NotFound;
              }
              else if (results.Count > 1)
              {
            result.Result = LookupResult.Range;
            LogManager.GetLogger("GeographyServices").InfoFormat("Multiple results for {0}", url);
              }
              else
              {
            result.Result = LookupResult.Success;
            var coordType = results[0].SelectSingleNode("geometry/location_type").InnerText;
            if (coordType == "ROOFTOP")
            {
              result.Quality = (int)GeocodeQuality.High;
            }
            else if (coordType == "RANGE_INTERPOLATED")
            {
              result.Quality = (int)GeocodeQuality.Medium;
            }
            else
            {
              result.Quality = (int)GeocodeQuality.Poor;
              LogManager.GetLogger("GeographyServices").WarnFormat("Poor quality geocode: {0}", url);
            }

            if (result.Quality > (int)GeocodeQuality.Poor)
            {
              LogManager.GetLogger("GeographyServices").InfoFormat("Got location: {0},{1}", results[0].SelectSingleNode("geometry/location/lat").InnerText, results[0].SelectSingleNode("geometry/location/lat").InnerText);
              double lat = double.Parse(results[0].SelectSingleNode("geometry/location/lat").InnerText);
              double lng = double.Parse(results[0].SelectSingleNode("geometry/location/lng").InnerText);

              // This call is slow. Might be good to move to background task.
              // double z = GeographyServices.GetElevation(lat, lng);
              double z = -100;

              string point = (z > 0) ? string.Format("POINT({0} {1} {2} NULL)", lng, lat, z) : string.Format("POINT({0} {1})", lng, lat);

              result.Geography = SqlGeography.STGeomFromText(new SqlChars(point.ToCharArray()), GeographyServices.SRID);
            }
              }
            }
              }
              catch (Exception)
              {
            LogManager.GetLogger("GeographyServices").InfoFormat("Error geocoding address: {0}", url);
            throw;
              }
              return result;
        }