APILayer Blog – All About APIs: AI, ML, Finance, & More APIs

How to Build a Geocoding Tool with the positionstack API (and Vibe Code It)

Geocoding hides inside a lot of apps you use every day. When a delivery app turns the address you typed into a pin, that’s forward geocoding. When a ride app shows the street you’re standing on, that’s reverse geocoding. Both are a single API request, which makes a geocoder a good first location project, with a catch that only shows up once you test real places: the data is messy, and a perfect match can still be the wrong place.

We built one called WhatIsMyGeoAddress on the positionstack API. It turns addresses into coordinates and back, and if you allow it, it reads your device’s position and tells you the address you’re at. We’ll go through the API first, with the real requests and responses we got, and then show how to vibe code a geocoder of your own with an AI assistant.

What is the positionstack API?

positionstack is a REST API for forward and reverse geocoding. The forward endpoint takes free text, like a street address or a landmark, and returns matching places with coordinates. The reverse endpoint takes a latitude and longitude and returns the places nearest to it. Both return results in the same shape: the coordinates, the address split into parts (number, street, neighbourhood, locality, county, region, country), a display-ready label, a type saying whether the match is an address, a street, a venue or a whole town, and a confidence score.

According to positionstack’s pricing page, the free plan gives you 100 requests a month for non-commercial use, and the paid plans start at 100,000 a month. Batch geocoding, which takes a list of addresses in one request, starts on the Professional plan.

The plan matrix. Free covers forward and reverse geocoding with HTTPS at 100 requests a month; batch requests start on Professional, and commercial use on Basic.

A “what’s my address” page is the obvious thing to build, but the same two calls power a lot of quieter features. You can geocode a shipping address at checkout to catch ones that don’t exist, store coordinates next to every customer so you can sort them by distance, fill in a city and postcode from the user’s location, or turn the GPS tags in photos into place names. Once the two endpoints work, each of these is mostly interface.

How do you turn an address into coordinates?

You send the address as query to the forward endpoint with your access key. After signing up and copying the key from the dashboard, this is the whole request:

				
					curl "https://api.positionstack.com/v1/forward?access_key=YOUR_KEY&query=1600%20Pennsylvania%20Ave%20NW,%20Washington%20DC"

				
			

Here’s the response it returned:

				
					{
  "data": [
    {
      "latitude": 38.897675,
      "longitude": -77.036547,
      "type": "address",
      "name": "1600 Pennsylvania Avenue NW",
      "number": "1600",
      "postal_code": "20500",
      "street": "Pennsylvania Avenue NW",
      "confidence": 1,
      "region": "District of Columbia",
      "region_code": "DC",
      "county": "District of Columbia",
      "locality": "Washington",
      "neighbourhood": "White House Grounds",
      "country": "United States",
      "country_code": "USA",
      "continent": "North America",
      "label": "1600 Pennsylvania Avenue NW, Washington, DC, USA",
      "map_url": "https://positionstack.com/download/map.html?bbox=-77.036047,38.898175,-77.037047,38.897175&marker=38.897675,-77.036547"
    }
  ]
}

				
			

data is an array even though there’s only one match, and that’s the part to design around. A full street address usually comes back as one clear result, but a vague query returns several, and your interface has to decide whether to show the first or let the person choose. The label is the tidy, formatted version of the address, so it’s the natural headline for a result. map_url links to a map of the result’s bounding box, which means its zoom depends on what matched: a street address opens close in, a city-level match shows the whole city. WhatIsMyGeoAddress rebuilds that URL with a fixed box of about 70 metres around the point, so every map opens at street level.

Errors come back in the same shape for both endpoints. An invalid key returned a 401 with {“error”: {“code”: “invalid_access_key”, “message”: “You have not supplied a valid API Access Key…”}}, so check for that error object before you read data.

The error codes worth handling. The two 429s need different messages: usage_limit_reached means the month is used up, rate_limit_reached means slow down and retry.

Why does the country flag come back empty?

Because country_code is the three-letter ISO code: USA here, and GBR for the United Kingdom. Most services that work with countries expect the two-letter code instead, including the flag image CDNs. We found this the hard way: WhatIsMyGeoAddress builds the flag next to the country from https://flagcdn.com/${country_code.toLowerCase()}.svg, and flagcdn returns a 404 for usa.svg and gbr.svgwhile us.svg and gb.svg work. Because the flag is a CSS background image rather than an <img> with an error handler, nothing complains. The box is just empty, for every country.

There are two fixes. You can keep a small map from three-letter to two-letter codes on your side, or you can add country_module=1 to the request. The country module adds a block with the country’s official name, capital, flag emoji, calling code, currencies and languages, and a global section that includes alpha2, so country_module.global.alpha2gives you US directly. Two other modules are worth knowing about: timezone_module=1 adds the time zone name and UTC offset, and sun_module=1 adds sunrise and sunset times. Each one makes the response bigger, so only turn on the ones the page uses.

From the Country Module reference: global.alpha2 is the two-letter code flag CDNs expect, next to the alpha3 code that the main country_code field uses.

How do you turn coordinates into an address?

You call the reverse endpoint with the latitude and longitude, separated by a comma, in the same query parameter. Here’s a request for a point in Westminster, London:

				
					curl "https://api.positionstack.com/v1/reverse?access_key=YOUR_KEY&query=51.5007,-0.1246"

				
			

This one came back with ten results, ordered by distance from the point. The first one:

				
					{
  "latitude": 51.500704,
  "longitude": -0.124572,
  "type": "venue",
  "distance": 0.002,
  "name": "Big Ben",
  "street": "Bridge Street",
  "postal_code": "WC2",
  "confidence": 0.9,
  "region": "London",
  "locality": "London",
  "neighbourhood": "Westminster",
  "country": "United Kingdom",
  "country_code": "GBR",
  "label": "Big Ben, London, England, United Kingdom"
}

				
			

Reverse results carry one extra field, distance, which is how far each result is from your coordinates in kilometres. The first match here is 2 metres away. The next two were Elizabeth Tower at 4 metres and a residence about 30 metres away. For a “where am I” feature the first result is usually right, but it’s worth showing the distance, so people understand why the answer is “Big Ben” and not their own doorstep.

To get coordinates in the first place, the browser’s Geolocation API does the work. WhatIsMyGeoAddress calls navigator.geolocation.getCurrentPosition with high accuracy and a 15 second timeout when the page loads, sends the coordinates to reverse, takes the top result’s label, and then runs a forward lookup on that label to fill in the full result card. It works, but it has two costs we’d change. It spends two requests on every visit where someone allows location, which on a 100-request plan is 50 visitors a month, and it asks for location before the visitor has done anything. A “Use my location” button that asks on click is more polite and only spends requests when someone wants the feature. Either way, browsers only allow geolocation on HTTPS pages, always ask permission, and report an accuracy in metres that ranges from a few metres on a phone with GPS to a block or more on a laptop, so show it next to the result.

Why can a result with full confidence still be wrong?

Because confidence measures how well the result matches the text you sent, not whether it’s the place the person meant. Testing with famous places is the fastest way to see this. When we searched for “Eiffel Tower, Paris” with limit=1, positionstack returned Eiffel Tower Lane in Paris, Tennessee, with a confidence of 1. That’s a correct answer to the literal question, since it is a place called Eiffel Tower in a town called Paris, but nobody typing that query wants Tennessee. Adding country=FR brought the results to France, and the top three were Pont Eiffel, the Eiffel Tower car park and Avenue Gustave Eiffel, all with a confidence of 1.

A plain “Springfield” shows the same problem from the other side. It returned Springfield in Missouri, Massachusetts, Illinois, Oregon and Ohio, every one with full confidence, because every one is a perfect match. No score can choose between them for you.

WhatIsMyGeoAddress currently shows only the first result, and these tests are why we’d change that. Ask for a few results with limit, list them when there’s more than one, and pass country whenever your app knows it, for example from a shipping form. Showing the type helps too, because a “street” match for what should have been a landmark is easy to spot once it’s on screen.

The forward geocoding parameters. country and region are the two filters that turn a perfect-but-wrong match into the right one, and country takes either code format.

How do you stay inside the request quota?

You put a small route on your server between the page and positionstack, and make every lookup go through it. The access key travels in the query string, so anything the browser sends to positionstack directly is visible in the network tab. The route adds the key, asks for a few results, and gives up if positionstack doesn’t answer in time:

				
					// app/api/geocode/route.ts
import { NextRequest } from "next/server";

export async function GET(req: NextRequest) {
  const query = req.nextUrl.searchParams.get("query")?.trim();
  const type = req.nextUrl.searchParams.get("type") === "reverse" ? "reverse" : "forward";
  if (!query) return Response.json({ error: "Enter an address or coordinates" }, { status: 400 });

  const url = new URL(`https://api.positionstack.com/v1/${type}`);
  url.searchParams.set("access_key", process.env.POSITIONSTACK_API_KEY!);
  url.searchParams.set("query", query);
  url.searchParams.set("limit", "5");

  try {
    const res = await fetch(url, { cache: "no-store", signal: AbortSignal.timeout(8000) });
    const data = await res.json();
    if (!res.ok || data.error) {
      return Response.json({ error: data.error?.message ?? "Geocoding failed" }, { status: 502 });
    }
    return Response.json(data);
  } catch {
    return Response.json({ error: "positionstack didn't answer in time. Try again in a minute." }, { status: 504 });
  }
}

				
			

The timeout is there because of something we ran into while taking screenshots for this article. positionstack stopped answering for a while: HTTPS requests returned a 504 after about 11 seconds, and HTTP requests returned a 500 with the internal_error code and the message “Request timed out after 15 seconds” after about 15. Our route had no timeout of its own, so a lookup through it waited the full 15 seconds before failing. Eight seconds and a clear message is a better experience than waiting for the upstream to give up.

The rest of the quota work is about not spending requests you don’t need. Don’t geocode on every keystroke: wait for the submit, or debounce autocomplete by a few hundred milliseconds and require a minimum length. Cache results by query on the server, because addresses don’t move and a popular search can be answered without calling the API at all. For reverse lookups, validate the coordinates before you spend a request: latitude has to be between -90 and 90 and longitude between -180 and 180, and people paste them with spaces, degree symbols or the wrong way round. A regex, a range check and swapping the pair when the first number can’t be a latitude catch most of it.

How to vibe code the geocoding tool

With the API’s quirks understood, an AI coding assistant can build most of this. We’d use one that edits a real project, like Claude Code or Cursor, and go one step at a time. Put the details from the sections above into your prompts. Left alone, an assistant will call positionstack from the browser, trust the first result and build flag URLs from the three-letter code, because nothing in the response tells it otherwise.

Start with the server route, since everything else depends on it:

				
					Create a Next.js App Router project with TypeScript and Tailwind. Add a GET
route /api/geocode that takes ?type=forward|reverse&query=... and calls
https://api.positionstack.com/v1/{type} with access_key from the
POSITIONSTACK_API_KEY environment variable, limit=5 and country_module=1.
Never expose the key to the browser. Abort the upstream call after 8 seconds
and return a clear 504 message. positionstack errors come back as an
"error" object with code and message: return those as a clear JSON error.
For reverse, validate that latitude is -90..90 and longitude -180..180, and
accept "lat, lng" with or without spaces.

				
			

When it’s done, hit the route with a real address and with something broken, like 200,200, and read both responses. Then search the page source and the network tab for your key. It shouldn’t appear anywhere.

Next, the page. Be specific about the multiple-results case and the flag, the two things our own first version got wrong:

				
					Build the home page: a toggle between "Address to coordinates" and
"Coordinates to address", one input and a convert button. Show the best
result as a card: the label in large type, a copy button, the type,
confidence, locality, region, postcode, and the country with its flag from
flagcdn.com using country_module.global.alpha2 in lowercase. If there's more
than one result, list the others under the card and let the user pick. The
app runs under a basePath: build every client fetch URL with one helper.

				
			

Check the flag for two or three countries, including the United Kingdom, since GB and GBR are the classic mismatch. Then search for “Springfield” and make sure you get a list rather than a single confident answer.

Then the feature that gives the tool its name, with the location request moved to a click:

				
					Add a "Use my location" button. Call navigator.geolocation.getCurrentPosition
with enableHighAccuracy and a 15 second timeout, send the coordinates to
/api/geocode?type=reverse, and show the first result with "accurate to about
N m" from the browser's accuracy value. If permission is denied or it times
out, show a short message and keep the form usable. Never request location
on page load.

				
			

Test this on your phone as well as your laptop, indoors and outside. The accuracy changes a lot between them, which is exactly why the page should show it.

Things to sort out before you launch

Test the deployed URL, not just localhost. WhatIsMyGeoAddress is served from a sub-path, /devtools/what-is-my-geo-address, and the page originally called /api/geocode. Locally that worked, because there’s no sub-path. Deployed, it pointed at the root of the domain and returned a 404, so every lookup showed “Failed to fetch geocoding data”. Next.js applies basePath to routing and links, not to the URLs you pass to fetch(), so prefix them from one shared constant, and make sure the branch you deploy actually has that change.

Be careful with what you store. A precise location from someone’s phone is personal data, and so is their home address. If you keep a history of lookups, say so on the page, keep it on the device or tie it to an anonymous session, and give people a way to clear it.

Be honest about the data and the licence. A short FAQ under the tool can explain why a location is slightly off, what the confidence score means and how to write coordinates. And the free plan is for non-commercial use, so move to a paid plan before the geocoder goes in front of customers.

Wrapping up

A geocoding tool is two API calls with a lot of care around them. Keep the key on the server and give positionstack a deadline, read the error object, convert the three-letter country code before you use it, ask for several results instead of one, and treat confidence as a match score rather than proof. positionstack does the hard part of matching messy text and raw coordinates against a worldwide address database, and an AI assistant can build the interface in an afternoon once you give it those details.

You can try WhatIsMyGeoAddress and get a free key at positionstack.com.

Exit mobile version