Ride-Hailing App Clones · Course book
Chapter 2: Search, Geocoding and the Trip Map
With a home screen and a map in place, the ride app needs its core flow: the rider says where they are and where they want to go, and the app shows both places on a map before offering rides. This chapter covers that flow. It explains how to build the search page, how to pass the chosen places from page to page in Next.js, how geocoding turns a typed address into coordinates, how to place markers and frame both points on the map, and how to compute the straight-line distance between them by hand. These pieces turn a static map into something that responds to what the rider wants.
The search page
The search page asks two questions: where to pick up and where to drop off. Its layout is simple and familiar from real ride apps: a back button at the top, two stacked input boxes beside a small graphic of a circle, a line and a square that shows the start and end of the journey, a button to add a stop, a row for saved places and a large confirm button at the bottom.
Each input is a controlled component in React: its value is held in state with useState and updated by an onChange handler, so the component always knows exactly what has been typed. That makes it easy to validate before moving on, for example disabling the confirm button until both boxes contain something, and to clear or prefill the boxes, such as filling the pickup with "Current location".
A saved places row, holding a home or work address, saves typing for frequent trips. In a first version it can be a fixed example; later it can come from the user's account in the database. Small touches like these are much of what makes a ride app feel quick to use.
Accessibility matters here as well. Each input needs a label, even if it is visually hidden, so that screen readers announce "Pickup location" and "Where to?" rather than an anonymous text box. Setting the input's autocomplete attribute appropriately, and giving the back button a real <button> or <a> element with an accessible name such as "Back", lets the page work with a keyboard and assistive technology, not only with taps.
Passing data between pages
When the rider confirms, the app moves to a confirmation page and must take the two places with it. In Next.js the simplest way is the query string: the confirm button links to /confirm?pickup=Ferry%20Building&dropoff=SFO, and the confirmation page reads the values with the router.
import { useRouter } from "next/router";
export default function Confirm() {
const router = useRouter();
const { pickup, dropoff } = router.query;
// pickup and dropoff are undefined on the very first render,
// so wait for router.isReady before using them.
}
Next.js's Link component can build the address from an object, { pathname: "/confirm", query: { pickup, dropoff } }, and encodes spaces and special characters automatically. Query strings have useful properties: the page can be refreshed or shared and still knows the trip, and the browser's back button works naturally. The weakness is that they hold only text, and anyone can edit them, so the confirmation page must treat them as untrusted input and handle values that cannot be found.
| Method | Survives refresh | Good for | Watch out for |
|---|---|---|---|
| Query string | Yes | Small values such as place names | Users can edit it; text only |
| Global state (context or a store) | No, unless saved | Larger objects shared by many pages | Lost on reload |
| Browser storage | Yes | Remembering recent searches | Per device; must be read safely |
| Database | Yes, everywhere | Saved places and trip history | Needs an account and a request |
Geocoding: from words to coordinates
A map cannot place "Ferry Building"; it needs longitude and latitude. Forward geocoding converts a place name or address into coordinates; reverse geocoding does the opposite, turning a position into an address, which is how an app shows "Current location: 1 Market Street". Mapbox offers a Geocoding API: the app sends the text and its access token, and receives a list of matching places, each with a name, a type such as address or point of interest, and a center of [longitude, latitude].
async function geocode(place) {
// GEOCODING_BASE holds the Mapbox geocoding address from its documentation
const url = `${GEOCODING_BASE}/${encodeURIComponent(place)}.json` +
`?limit=1&access_token=${TOKEN}`;
const res = await fetch(url);
if (!res.ok) throw new Error("Geocoding failed");
const data = await res.json();
return data.features[0]?.center; // [longitude, latitude] or undefined
}
The function returns undefined when nothing matches, which the page checks before drawing. Writing it as a small helper, separate from the component, makes it easy to test and to swap for a different geocoding provider later.
The confirmation page calls the geocoding API twice, once for each place, and stores the coordinates in state. Because both requests are independent, running them together with Promise.all halves the waiting time compared with one after the other. Results can be improved with options: limiting to one country, biasing towards the user's current area with a proximity parameter so that "Main Street" finds the nearby one, and asking only for the best match. If no result comes back, the page should say so and offer to return to search rather than showing an empty map.
Typing addresses accurately is hard on a phone, so mature apps offer autocomplete: as the rider types, the app requests suggestions and shows them in a list, and choosing one fills the box with an exact place and its coordinates. To avoid a request for every keystroke, the app waits until typing pauses for a few hundred milliseconds, a technique called debouncing.
Markers and framing the trip
With both coordinates known, the map component, reused from the home page, adds two markers: one at the pickup and one at the drop-off, ideally in different colours or shapes to match the circle-and-square graphic on the search page. The component receives the coordinates as props, and an effect adds the markers whenever they change, removing old ones first so markers do not pile up.
Keeping references to the markers makes clean-up simple: the effect stores each marker it creates, and its clean-up function calls marker.remove() on each before the next run. The same applies to the map itself if the component can unmount. Another subtle point is timing. The map style loads asynchronously, so adding layers too early fails; markers can be added at once, but anything drawn as a map layer, such as the route line in the next chapter, should wait for the map's load event. Writing the map component so that it accepts optional pickup and drop-off props, and draws nothing extra when they are missing, lets the same component serve both the home page and the confirmation page.
To show both points, the map is framed with map.fitBounds, given the south-west and north-east corners of a box around them: the smallest longitude and latitude, and the largest. With padding of around 60 pixels, the markers do not sit right at the edge of the screen. For a pickup at [−122.3937, 37.7955], the Ferry Building, and a drop-off at [−122.3790, 37.6213], the airport, the corners are [−122.3937, 37.6213] and [−122.3790, 37.7955].
Straight-line distance by hand
Before routing along roads, it is useful to know the straight-line, or great-circle, distance between two points, for example to reject trips that are implausibly long. The haversine formula computes it on a sphere of radius 6,371 km. For short distances, a flat approximation is close enough: one degree of latitude is about 111.32 km, and one degree of longitude is 111.32 km times the cosine of the latitude.
Distances like this also feed later features: showing a rough fare before the route arrives, sorting nearby drivers or deciding which map zoom level suits the trip. Whatever the method, remember that coordinates are in degrees and trigonometric functions in JavaScript expect radians, so multiply by π / 180 first.
Practice tasks
- Write the
Linkobject that sends the pickup "Union Square" and the drop-off "Golden Gate Park" to the confirm page. - Explain why the confirmation page must check
router.isReadybefore using the query values. - Give the bounding box corners for points at [2.2945, 48.8584] and [2.3522, 48.8566].
- Using the flat approximation, estimate the distance between those two points in Paris. The cosine of 48.86° is about 0.658.
- Why does running the two geocoding requests with
Promise.allmake the page faster? - Describe what the page should show if geocoding finds no match for the drop-off.
This course book is available to read online only at tech-academy.chrysolites.org.