I have been poking at the Milwaukee County Trasit System (MCTS) APIs over the past few weeks. A few years ago, I tried to write a bus app using Angular and it just didn’t work out well. I figured that I would try it again, using what I have learned since then. The first step was to build out a data infrastructure using Cloudflare Workers and Cloudflare KV. The end-result of that is what drives the MCTS mastodon bot. The workers JSON api returns every bus stop in the system, along with the route, direction, and location. The next step is to figure out where the user is and where they are going. That is the subject of today’s post.
We have covered binding and how to get a user’s street address based upon navigator.geolocation before but I don’t think that we have done this, yet. I want to start with an address prompt and end up with a latitude and longitude coordinate set. We came close when I covered how to convert cities / postal codes to latitude / longitude coordinates but in this version, you are going to able to enter a house number and street.
In the above example, we have an address prompt and the form fields are bound to variables in the app. The values assigned to those variables dictate the values of the form fields and vice versa.
At this point, we are going to default those address values to null and bring in the use of the Mapbox Address Autofill API.
In the above example, we have the same basic webform (except for the addition of an autocomplete attribute on each of the form inputs) but the javascript now contains a call to mapboxsearch.autofill() and the mapbox web library is now included via a CDN. As you start entering the address, it auto-suggests addresses to you and if you click one, it fills the form out.
If you open the network tab in Developer Tools, you can see the value for the latitude and longitude associated with the selected address but for the life of me, I can’t figure out how to get to those values. You also have the question of how to get the values in the case where the user didn’t accept the address suggestion. So, how do you handle getting the coordinates?
In the above example, I added a watcher that looks for changes to the postal code, makes sure that the address has values that aren’t null, and then triggers an alert if that’s the case.
In the next post, we will look at how to actually get the corresponding latitude / longitude coordinates.
[ Cover photo by Brian Patrick Tagalog on Unsplash ]