In the past two years, I have written a few blog posts that explored how to figure out where the user physically is. Most of these experiments involved navigator.geolocation but last week's iOS 15, Private Relay, and Geolocation post brought in the concept of figuring out the person's location based upon their IP address. After finishing that post, I started to wonder what it would take to simplify things. Can I reduce the number of API calls to things and make the result more reliable? In the process, I decided that I would also wrap things up into a central Cloudflare worker.
So, let's see what the guts of the worker look like.
As you can see above, a lot of the returned data is just things that cloudflare knows about you, out of the gate but in order to get your likely street address, an API call to Mapquest is still needed. I also set it up so that you can pass latitude and longitude values in as get variables. If the user is on an LTE or 5g connection, their location is likely to show up as being in a completely different place.
So, how do we implement this new API?
Using the "Use GPS to update position" and "Use IP to update position" buttons, you can toggle between the two modes of detection. Basically, one passes lat/long coordinates into the API and the other leaves it up to the node script to figure it out.
In a real-world setting, I would execute the IP-based detection by default and give the user the option to use the more accurate option if they wished to do so. This is definitely getting integrated into my Wisconsin State Parks project.
Have any questions, comments, etc? Feel free to drop a comment, below.
Top comments (0)