none
U.S. Zip Codes RRS feed

  • General discussion

  • This comes up every once in a while here, so if you're looking for a fairly simple way to get information on U.S. Zip Codes (note that I cannot promise accuracy, but as far as I know, it's correct to date), have a look at what I posted in another thread here.

    I hope it helps someone. :)


    Please call me Frank :)

    Wednesday, December 18, 2013 5:54 PM

All replies

  • Hello Frank,

    Another method (requires Internet access) is to invoke a service. Does not give some data you have, just another idea that might be of use.

    From the following page http://www.webservicex.net/WS/WSDetails.aspx?WSID=42&CATID=7 get the WSDL, add a new service reference to a project.

    I named my service ZipCodeTest, did an import then used the code below to get the data shown below for my zip code.

    Imports ZipCodeTest.ZipService
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim Test = New USZipSoapClient("USZipSoap")
            Dim Result = Test.GetInfoByZIP("97303")
            Console.WriteLine(Result.OuterXml)
        End Sub
    End Class

    Console.WriteLine results

    <NewDataSet xmlns="">
       <Table>
          <CITY>Salem</CITY>
          <STATE>OR</STATE>
          <ZIP>97303</ZIP>
          <AREA_CODE>503</AREA_CODE>
          <TIME_ZONE>P</TIME_ZONE>
       </Table>
    </NewDataSet>


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Wednesday, December 18, 2013 7:12 PM
    Moderator
  • Good work Kevin,

    I'll learn about webservices and the like one of these days I guess, but as it stands, I have no idea how to set one up.

    ***

    As for what I posted though, I'm hopeful that people will use the option to have it saved locally. The drawback is that there's no "updating" if the source data changes, so there's good and bad no matter how you go about it. ;-)


    Please call me Frank :)

    Wednesday, December 18, 2013 7:17 PM
  • Good work Kevin,

    I'll learn about webservices and the like one of these days I guess, but as it stands, I have no idea how to set one up.

    ***

    As for what I posted though, I'm hopeful that people will use the option to have it saved locally. The drawback is that there's no "updating" if the source data changes, so there's good and bad no matter how you go about it. ;-)


    Please call me Frank :)

    Here is a very simple web service on skydrive done in VS2012 as per my first reply. Don't have time to provide instructions right now but it's not difficult. The example as setup is a one time run but would be easy to tweak (remove data bindings) for multiple runs.

    Screenshot


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Wednesday, December 18, 2013 7:43 PM
    Moderator
  • Kev,

    I'm sure it works well but I have no way to open it. ;-)

    *****

    Like I said, one day I'll take it on, but then again -- if it's not updated then it's a moot point anyway; once you have the data locally, you have it and there's then no point in it.


    Please call me Frank :)

    Wednesday, December 18, 2013 7:47 PM
  • Trying this again...

    I’ve modified my class now – the data (the XML) remains as it was, but I thought that I’d embellish it a bit as follows:

    A few things above are noteworthy:

    First, the ‘internal list of ZipCodes’ (“zcList”) is now public so you can access it directly in your code. Do still be sure to initialize it first of course, otherwise it’ll be empty. ;-)

    Secondly, I have an overridden the “.ToString” method to return more meaningful information as will be shown in use in my testing of it which follows.

    Next, I have overloaded the method named “GetZipCodeInfo” and the overloaded version takes a city name and a state name and returns a LIST of ZipCode. Obviously a city/state has [typically] more than one zip code.

    The city and state are not case-sensitive (and will even strip out spaces) and with the name of the state, you can use either the full name or the state’s two-letter abbreviation. As with the original method, be sure to test that the return value isn’t null.

    Lastly then, I’ve added another method which is overloaded:

    GetDistance

    This method, a function, will return a type double indicating the straight-line distance (or geodesic distance, to be technically correct) between the two locations.

    This method is overloaded such that you can send it two zip codes or two city/state pairs. As with the former, the city and state names aren’t case-sensitive and the state can be either the full state name or the state’s two-letter abbreviation.

    I have the revised class’s code on a page of my website here and to save you time, I’ve zipped it up and have that uploaded here.

    Following shows the results of a few tests:

          ZipCode.InitializeZipCodes(True)

     

           TextBox1.Text = "Zip code list count: " & _

               ZipCode.zcList.Count.ToString("n0")

         Dim findZC As ZipCode = ZipCode.GetZipCodeInfo("99950")

     

           If findZC IsNot Nothing Then

               TextBox1.Text = findZC.ToString

           End If

         Dim test As List(Of ZipCode) = _

               ZipCode.GetZipCodeInfo("charleston", "south        CARolina")

     

           If test IsNot Nothing Then

               Dim sb As New System.Text.StringBuilder

     

               For i As Integer = 0 To test.Count - 1

                   If i > 0 Then

                       sb.AppendLine()

                       sb.AppendLine("-----")

                       sb.AppendLine()

                   End If

     

                   sb.AppendLine(test(i).ToString)

               Next

     

               If sb.ToString.Length > 0 Then

                   TextBox1.Text = sb.ToString

               End If

           End If

          Dim dist1 As Double = ZipCode.GetDistance(test(0).ZipCode, _

                                                     findZC.ZipCode, _

                                                     ZipCode.DistanceUnit.Miles)

     

           If dist1 > 0 Then

               Dim sb As New System.Text.StringBuilder

     

               sb.AppendLine("The distance between:")

               sb.AppendLine()

               sb.AppendLine(test(0).ToString)

               sb.AppendLine()

               sb.AppendLine("...and")

               sb.AppendLine()

               sb.AppendLine(findZC.ToString)

               sb.AppendLine()

               sb.AppendLine("... is " & dist1.ToString("n1") & " miles as the crow flies.")

     

               If sb.ToString.Length > 0 Then

                   TextBox1.Text = sb.ToString

               End If

           End If

          Dim dist2 As Double = _

               ZipCode.GetDistance(test(0).CityName, test(0).StateInitials, _

                                   "asheville", "nOrTh     caroLINA", ZipCode.DistanceUnit.Miles)

     

           If dist2 > 0 Then

               Dim sb As New System.Text.StringBuilder

     

               sb.AppendLine("The distance between:")

               sb.AppendLine()

               sb.AppendLine(test(0).ToString)

               sb.AppendLine()

               sb.AppendLine("...and")

               sb.AppendLine()

               sb.AppendLine(ZipCode.GetZipCodeInfo("asheville", "nOrTh     caroLINA")(0).ToString)

               sb.AppendLine()

               sb.AppendLine("... is " & dist2.ToString("n1") & " miles as the crow flies.")

     

               If sb.ToString.Length > 0 Then

                   TextBox1.Text = sb.ToString

               End If

           End If

     

     

    I hope that someone here might find this useful. :)

     


    Please call me Frank :)

    Thursday, December 19, 2013 8:45 PM
  • The Post Office has a set of free API's, I'm going to mess around with them....

    https://www.usps.com/business/web-tools-apis/list-of-apis.htm

    Update : I got a userID, but it is not valid for things like Zip Code lookup or Address Validation. To do that I am supposed to "Request Permission to Access Address Information APIs" at https://www.usps.com/business/webtools-address-information.htm

    When I enter my ID and a URL, I get this:

    Thank you for submitting your questions or comments.

    The US Postal Service appreciates you taking the time to respond and provide us your feedback.

    Back to the USPS.com Home Page

    I have some code but it only returns errors. Project = "USPSInterface" - Main Form:

    Imports USPSInterface.WebTools
    Public Class Form1
    
        Private Sub BTNGo_Click(sender As System.Object, e As System.EventArgs) Handles BTNGo.Click
            Dim wt As WebTools = New WebTools
            TXTResults.Text = wt.CityStateLookupRequest(TXTZipCode.Text)
        End Sub
    
        Private Sub BTNTest_Click(sender As System.Object, e As System.EventArgs) Handles BTNTest.Click
            Dim wt As WebTools = New WebTools
            TXTResults.Text = wt.AddressValidateRequest("MyHomeAddress", "", "MyCity", "MyState(2 chars)", "MyZip5", "MyZip4")
        End Sub
    End Class
    

    Class WebTools (WebTools.vb):

    Imports System.Net
    Class WebTools
        'Base URL for USPS Address and Zip Code validation API.
        Private Const BaseURL As String = "http://testing.shippingapis.com/ShippingAPITest.dll"
        'Web client instance.
        Private wsClient As New WebClient()
        'User ID obtained from USPS.
        Public USPS_UserID As String = "XXXXXXXXXXXX"
        '------------------------------------------------------
        ' Send request to remote site. Return reply data.
        '------------------------------------------------------
        Private Function GetDataFromSite(ByVal USPS_Request As String) As String
            Dim strResponse As String = ""
            Dim ResponseData() As Byte
            'Send the request to USPS.
            ResponseData = wsClient.DownloadData(USPS_Request)
            'Convert byte stream to string data.
            For Each oItem As Byte In ResponseData
                strResponse &= Chr(oItem)
            Next oItem
            Return strResponse
        End Function
    
        '-------------------------------------------------
        ' This function provides an interface to the USPS
        ' WebTools Address Validation API.
        '-------------------------------------------------
        Function AddressValidateRequest(ByVal Address1 As String, _
                                        ByVal Address2 As String, _
                                        ByVal City As String, _
                                        ByVal State As String, _
                                        ByVal Zip5 As String, _
                                        ByVal Zip4 As String) As String
            'http://production.shippingapis.com/ShippingAPITest.dll?API=Verify
            '  &XML=<AddressValidateRequest USERID="xxxxxxx"><Address ID="0"><Address1></Address1>
            '  <Address2>6406 Ivy Lane</Address2><City>Greenbelt</City><State>MD</State>
            '  <Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest>
            Dim strUSPS As String
    
            strUSPS = BaseURL & "?API=Verify&XML=<AddressValidateRequest USERID=""" + USPS_UserID + """> "
            strUSPS = strUSPS & "<Address ID=""0"">"
            strUSPS = strUSPS & "<Address1>" & Address1 & "</Address1>"
            strUSPS = strUSPS & "<Address2>" & Address2 & "</Address2>"
            strUSPS = strUSPS & "<City>" & City & "</City>"
            strUSPS = strUSPS & "<State>" & State & "</State>"
            strUSPS = strUSPS & "<Zip5>" & Zip5 & "</Zip5>"
            strUSPS = strUSPS & "<Zip4>" & Zip4 & "</Zip4>"
            strUSPS = strUSPS & "</Address></AddressValidateRequest>"
    
            Return GetDataFromSite(strUSPS)
        End Function
    
        '-------------------------------------------------
        ' This function provides an interface to the USPS
        ' WebTools City and State Lookup API.
        '-------------------------------------------------
        Public Function CityStateLookupRequest(ByVal Zip5 As String) As String
            'http://production.shippingapis.com/ShippingAPITest.dll?API=CityStateLookup
            '  &XML=<CityStateLookupRequest USERID="xxxxxxx"><ZipCode ID= "0">
            '  <Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>
            Dim strUSPS As String
    
            strUSPS = BaseURL & "?API=CityStateLookup&XML=<CityStateLookupRequest USERID=""" + USPS_UserID + """>"
            strUSPS = strUSPS & "<ZipCode ID=""0"">"
            strUSPS = strUSPS & "<Zip5>" & Zip5 & "</Zip5>"
            strUSPS = strUSPS & "</ZipCode></CityStateLookupRequest>"
    
            Return GetDataFromSite(strUSPS)
    
        End Function
    
    
    End Class
    

    Here is the response I get for All Zip Code requests

    <?xml version="1.0" encoding="UTF-8"?>
    <Error>
    <Number>80040B1A</Number>
    <Description>API Authorization failure. User XXXXXXXXXXXX is not authorized to use API CityStateLookup.</Description>
    <Source>USPSCOM::DoAuth</Source>
    </Error>

    Hopefully I can resolve this......

    Sunday, December 22, 2013 10:44 PM
  • Devon,

    I didn't know they did, but don't they offer return values in standard formats like XML or JSON?


    Please call me Frank :)

    Sunday, December 22, 2013 10:47 PM
  • Devon,

    I didn't know they did, but don't they offer return values in standard formats like XML or JSON?


    Please call me Frank :)


    What I am surprised about is that they don't have web services but instead utilized old technologie as in ActiveX.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Sunday, December 22, 2013 11:23 PM
    Moderator
  • What I am surprised about is that they don't have web services but instead utilized old technologie as in ActiveX.

    The data that I used is actually based on data from the U.S. Census Bureau.

    Even though the USPS is public information, they apparently aren't very forthcoming about sharing it; the USCB, though, got their data from USPS and they have no problem making it available (persuant to U.S. law, I might add).

    My data is about four years old though.


    Please call me Frank :)

    Sunday, December 22, 2013 11:30 PM
  • I got frustrated by the API tomfoolery so:

    Code:

    '******************************************************************
    '* requires a form with 1 button (BTNShow), 1 combobox (CBOState) *
    '* 3 TextBoxes (TXTAddress1, TXTAddress2, TXTCity)                *
    '* one Multiline Textbox (TXTResults) and                         *
    '* a webbrowser control that should                               *
    '* be made invisible with the textbox covering it                 *
    '******************************************************************
    Option Strict On
    Imports System.Text
    Imports System.IO
    Imports System.Net
    
    Public Class Form1
        Dim ZIPData As New Dictionary(Of String, String)
    
        Private Sub BTNShow_Click(sender As System.Object, e As System.EventArgs) Handles BTNShow.Click
            TXTResults.Clear()
            Dim State As String = ""
            For Each statecode As KeyValuePair(Of String, String) In ZIPData
                If statecode.Key = CBOState.Text Then
                    State = statecode.Value
                End If
            Next
            If State = "" Then Exit Sub
    
            Dim TheProperURL As String = "https://tools.usps.com/go/ZipLookupResultsAction!input.action?resultMode=0&companyName=" & _
                "&address1= " & TXTAddress1.Text.Replace(" "c, "+"c) & _
                "&address2=" & TXTAddress2.Text.Replace(" "c, "+"c) & _
                "&city=" & TXTCity.Text.Replace(" "c, "+"c) & _
                "&state=" & State & _
                "&urbanCode=" & _
                "&postalCode=" & _
                "&zip="
            WebBrowser1.Navigate(TheProperURL)
        End Sub
    
        Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
            'this code I found at http://www.vbdotnetforums.com/vb-net-general-discussion/40795-how-extract-text-website-vb2008.html
            'changed it for this particular purpose
            Dim sb As New StringBuilder
            If Me.WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
                For Each cell As HtmlElement In Me.WebBrowser1.Document.GetElementsByTagName("li")
                    Dim cls As String = cell.GetAttribute("className")
                    If cls = "error" Then
                        If cell.InnerText <> Nothing Then sb.Append(cell.InnerText.Trim)
                    End If
                Next
    
                For Each cell As HtmlElement In Me.WebBrowser1.Document.GetElementsByTagName("span")
                    Dim cls As String = cell.GetAttribute("className")
    
                    If cls = "zip" Then
                        If cell.InnerText <> Nothing Then sb.Append(cell.InnerText.Trim)
                    End If
    
                    If cls = "zip4" Then
                        If cell.InnerText <> Nothing Then
                            sb.Append("-" & cell.InnerText.Trim & vbNewLine)
                        Else
                            sb.Append(vbNewLine)
                        End If
                    End If
                Next
                TXTResults.Text = sb.ToString
            End If
        End Sub
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            WebBrowser1.Visible = False
            ZIPData.Add("Alabama", "AL")
            ZIPData.Add("Alaska", "AK")
            ZIPData.Add("Arizona", "AZ")
            ZIPData.Add("Arkansas", "AR")
            ZIPData.Add("California", "CA")
            ZIPData.Add("Colorado", "CO")
            ZIPData.Add("Connecticut", "CT")
            ZIPData.Add("Delaware", "DE")
            ZIPData.Add("Florida", "FL")
            ZIPData.Add("Georgia", "GA")
            ZIPData.Add("Hawaii", "HI")
            ZIPData.Add("Idaho", "ID")
            ZIPData.Add("Illinois", "IL")
            ZIPData.Add("Indiana", "IN")
            ZIPData.Add("Iowa", "IA")
            ZIPData.Add("Kansas", "KS")
            ZIPData.Add("Kentucky", "KY")
            ZIPData.Add("Louisiana", "LA")
            ZIPData.Add("Maine", "ME")
            ZIPData.Add("Maryland", "MD")
            ZIPData.Add("Massachusetts", "MA")
            ZIPData.Add("Michigan", "MI")
            ZIPData.Add("Minnesota", "MN")
            ZIPData.Add("Mississippi", "MS")
            ZIPData.Add("Missouri", "MO")
            ZIPData.Add("Montana", "MT")
            ZIPData.Add("Nebraska", "NE")
            ZIPData.Add("Nevada", "NV")
            ZIPData.Add("New Hampshire", "NH")
            ZIPData.Add("New Jersey", "NJ")
            ZIPData.Add("New Mexico", "NM")
            ZIPData.Add("New York", "NY")
            ZIPData.Add("North Carolina", "NC")
            ZIPData.Add("North Dakota", "ND")
            ZIPData.Add("Ohio", "OH")
            ZIPData.Add("Oklahoma", "OK")
            ZIPData.Add("Oregon", "OR")
            ZIPData.Add("Pennsylvania", "PA")
            ZIPData.Add("Rhode Island", "RI")
            ZIPData.Add("South Carolina", "SC")
            ZIPData.Add("South Dakota", "SD")
            ZIPData.Add("Tennessee", "TN")
            ZIPData.Add("Texas", "TX")
            ZIPData.Add("Utah", "UT")
            ZIPData.Add("Vermont", "VT")
            ZIPData.Add("Virginia", "VA")
            ZIPData.Add("Washington", "WA")
            ZIPData.Add("West Virginia", "WV")
            ZIPData.Add("Wisconsin", "WI")
            ZIPData.Add("Wyoming", "WY")
            ZIPData.Add("American Samoa", "AS")
            ZIPData.Add("District of Columbia", "DC")
            ZIPData.Add("Federated States of Micronesia", "FM")
            ZIPData.Add("Guam", "GU")
            ZIPData.Add("Marshall Islands", "MH")
            ZIPData.Add("Northern Mariana Islands", "MP")
            ZIPData.Add("Palau", "PW")
            ZIPData.Add("Puerto Rico", "PR")
            ZIPData.Add("Virgin Islands", "VI")
            ZIPData.Add("Armed Forces Africa", "AE")
            ZIPData.Add("Armed Forces Americas", "AA")
            ZIPData.Add("Armed Forces Canada", "AE")
            ZIPData.Add("Armed Forces Europe", "AE")
            ZIPData.Add("Armed Forces Middle East", "AE")
            ZIPData.Add("Armed Forces Pacific", "AP")
            For Each statecode As KeyValuePair(Of String, String) In ZIPData
                CBOState.Items.Add(statecode.Key)
            Next
            CBOState.SelectedIndex = 0
        End Sub
    End Class
    

    Monday, December 23, 2013 1:51 AM