Wednesday 11 October 2023

Can we just autofill city and state? Please!

Coming from a country that is not the US where zip/postal codes are hyper specific, it always drives me nuts when you are filling in a form in the US that is like:

City

State

Zip

It's patently obvious and massively infuriating that anyone from a country such as the UK that this could be trivially autopopulated if you asked for the zip first. In the UK you usually are asked to enter the postcode and then the first line is the only one you have to complete.

As with many things in the US, why is this so hard?

Like literally, mash in the 10011 -> New York City, New York. Done. It would also improve the quality of the data that the forms collect.

So in an idle 10 minutes I decided to have a go at fixing the problem with ChatGpt.



Looks pretty sensible to me. Does it work? Sure does.

One small snag is that there are zip codes that cross state lines. That's a minor annoyance and one of the justifications used to excuse this lack of functionality in form filling websites. OK so I tested it with a zip that is ambiguous:

[nix-shell:~]$ node ~/state/state.js
State: Arizona
City: Teec Nos Pos

This seems reasonable. If you are one of the poor suckers who lives in an ambiguous zip then I am sorry, that is the price you have to pay. At the moment everyone is paying the price to fill in City and State!



Ok so let's ship it.


// Define a function to resolve ZIP code to state and city
function resolveZipCode(zipCode, callback) {
  // Define the API endpoint for Zippopotam
  const apiUrl = `https://api.zippopotam.us/us/${zipCode}`;

  // Make an HTTP request to the API
  fetch(apiUrl)
    .then(response => {
      if (response.status === 200) {
        return response.json();
      } else {
        throw new Error('ZIP code not found');
      }
    })
    .then(data => {
      const state = data.places[0].state;
      const city = data.places[0]['place name'];
      callback(null, { state, city });
    })
    .catch(error => {
      callback(error, null);
    });
}

// Example usage
const zipCode = '86514'; // Replace with the ZIP code you want to resolve
resolveZipCode(zipCode, (error, result) => {
  if (error) {
    console.error('Error:', error);
  } else {
    console.log('State:', result.state);
    console.log('City:', result.city);
  }
});



No comments:

Post a Comment

Leave a comment!

Can we just autofill city and state? Please!

Coming from a country that is not the US where zip/postal codes are hyper specific, it always drives me nuts when you are filling in a form ...