DEV Community

Luo Atlas
Luo Atlas

Posted on

How to Convert an Address to Latitude and Longitude with JavaScript

If you have a street address and need to place it on a map, calculate distances, find nearby places, or store its location in a database, you first need to convert that address into geographic coordinates.

This process is called geocoding.

For example:

1600 Amphitheatre Parkway, Mountain View, CA
Enter fullscreen mode Exit fullscreen mode

might be converted into something like:

Latitude: 37.422
Longitude: -122.084
Enter fullscreen mode Exit fullscreen mode

In this guide, we'll look at how address-to-coordinate conversion works and how to implement it with JavaScript.

What Is Geocoding?

Geocoding converts a human-readable location into latitude and longitude coordinates.

The input could be:

  • A complete street address
  • A city name
  • A postal code
  • A landmark
  • A place name

For example:

Times Square, New York
Enter fullscreen mode Exit fullscreen mode

can be converted into coordinates that can then be displayed on a map.

The reverse process is called reverse geocoding:

Latitude + Longitude → Address
Enter fullscreen mode Exit fullscreen mode

So the two operations are:

Address → Coordinates     = Geocoding
Coordinates → Address     = Reverse Geocoding
Enter fullscreen mode Exit fullscreen mode

Basic JavaScript Example

Most geocoding services expose an HTTP API.

A simplified JavaScript request looks like this:

async function geocodeAddress(address) {
  const url =
    `https://nominatim.openstreetmap.org/search` +
    `?format=json&q=${encodeURIComponent(address)}`;

  const response = await fetch(url);
  const results = await response.json();

  if (!results.length) {
    throw new Error("Location not found");
  }

  return {
    latitude: parseFloat(results[0].lat),
    longitude: parseFloat(results[0].lon)
  };
}
Enter fullscreen mode Exit fullscreen mode

Then call it like this:

geocodeAddress("Times Square, New York")
  .then(location => {
    console.log(location.latitude);
    console.log(location.longitude);
  })
  .catch(error => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

The result will look similar to:

{
  latitude: 40.758,
  longitude: -73.9855
}
Enter fullscreen mode Exit fullscreen mode

The exact coordinates may vary depending on the geocoding provider and which geographic feature it considers the best match.

Why encodeURIComponent() Matters

Addresses often contain spaces, commas, apartment numbers, accented characters, and other symbols.

For example:

10 Downing Street, London
Enter fullscreen mode Exit fullscreen mode

should not simply be inserted into a URL without encoding.

Use:

encodeURIComponent(address)
Enter fullscreen mode Exit fullscreen mode

which produces a URL-safe version of the input.

const address = "10 Downing Street, London";

const encoded = encodeURIComponent(address);

console.log(encoded);
Enter fullscreen mode Exit fullscreen mode

Without proper encoding, some addresses may produce invalid requests or unexpected search results.

Building a Simple Address Search

You can connect the geocoding function to an HTML input.

<input
  id="address"
  type="text"
  placeholder="Enter an address"
/>

<button id="search">
  Find Coordinates
</button>

<div id="result"></div>
Enter fullscreen mode Exit fullscreen mode

Then add JavaScript:

const input = document.getElementById("address");
const button = document.getElementById("search");
const result = document.getElementById("result");

button.addEventListener("click", async () => {
  const address = input.value.trim();

  if (!address) {
    result.textContent = "Please enter an address.";
    return;
  }

  try {
    const location = await geocodeAddress(address);

    result.innerHTML = `
      Latitude: ${location.latitude}<br>
      Longitude: ${location.longitude}
    `;
  } catch (error) {
    result.textContent = "Location not found.";
  }
});
Enter fullscreen mode Exit fullscreen mode

Now a user can enter an address and receive its latitude and longitude directly in the browser.

Geocoding Results Are Often Ambiguous

One important detail is that an address does not always correspond to exactly one location.

Consider a search like:

Springfield
Enter fullscreen mode Exit fullscreen mode

There are many places with that name.

A geocoding service may return several possible results.

Instead of always selecting the first result, you can display a list.

async function searchLocations(address) {
  const url =
    `https://nominatim.openstreetmap.org/search` +
    `?format=json&limit=5&q=${encodeURIComponent(address)}`;

  const response = await fetch(url);

  return response.json();
}
Enter fullscreen mode Exit fullscreen mode

Then:

const locations = await searchLocations("Springfield");

locations.forEach(location => {
  console.log(
    location.display_name,
    location.lat,
    location.lon
  );
});
Enter fullscreen mode Exit fullscreen mode

For a real search interface, letting users choose from several matching locations is often better than assuming the first result is correct.

Latitude and Longitude Order Can Be Confusing

This is one of the most common coordinate mistakes.

Many JavaScript mapping libraries use:

latitude, longitude
Enter fullscreen mode Exit fullscreen mode

or:

lat, lng
Enter fullscreen mode Exit fullscreen mode

But GeoJSON uses:

[longitude, latitude]
Enter fullscreen mode Exit fullscreen mode

For example:

const latitude = 40.758;
const longitude = -73.9855;
Enter fullscreen mode Exit fullscreen mode

A normal object might look like:

{
  lat: 40.758,
  lng: -73.9855
}
Enter fullscreen mode Exit fullscreen mode

But a GeoJSON point is:

{
  type: "Point",
  coordinates: [-73.9855, 40.758]
}
Enter fullscreen mode Exit fullscreen mode

Notice that the order is reversed.

Mixing these formats can place your marker thousands of kilometers away from where you expected.

Displaying the Result on a Map

If you're using MapLibre GL JS, the result can be used directly to position a marker.

For example:

const location = {
  latitude: 40.758,
  longitude: -73.9855
};

new maplibregl.Marker()
  .setLngLat([
    location.longitude,
    location.latitude
  ])
  .addTo(map);
Enter fullscreen mode Exit fullscreen mode

You can also center the map on the location:

map.flyTo({
  center: [
    location.longitude,
    location.latitude
  ],
  zoom: 14
});
Enter fullscreen mode Exit fullscreen mode

Again, notice that MapLibre expects:

[longitude, latitude]
Enter fullscreen mode Exit fullscreen mode

rather than:

[latitude, longitude]
Enter fullscreen mode Exit fullscreen mode

What If an Address Cannot Be Found?

Geocoding is not exact.

A request might fail because:

  • The address is misspelled
  • The building is new
  • The address database is incomplete
  • The user entered only part of the address
  • The place has several possible names
  • The postal address format is unusual
  • The location is in a poorly mapped region

Instead of treating an empty response as a fatal error, a better interface might ask the user to modify the search.

if (!results.length) {
  console.log(
    "No exact result found. Try adding a city, region, or country."
  );
}
Enter fullscreen mode Exit fullscreen mode

For example, instead of:

Main Street 25
Enter fullscreen mode Exit fullscreen mode

try:

25 Main Street, Boston, MA, USA
Enter fullscreen mode Exit fullscreen mode

More geographic context usually produces better results.

Avoid Geocoding the Same Address Repeatedly

If your application frequently looks up the same addresses, you may not want to send a new API request every time.

A simple application could store previously resolved addresses:

const cache = new Map();

async function getCoordinates(address) {
  const key = address.trim().toLowerCase();

  if (cache.has(key)) {
    return cache.get(key);
  }

  const coordinates = await geocodeAddress(address);

  cache.set(key, coordinates);

  return coordinates;
}
Enter fullscreen mode Exit fullscreen mode

For larger applications, results can be stored in a database instead.

Before caching geocoding data in production, check the terms of the geocoding provider you're using.

Browser or Server?

For a small experiment, calling a geocoding API directly from the browser is convenient.

For production applications, a backend endpoint is often better.

Instead of:

Browser → Geocoding Provider
Enter fullscreen mode Exit fullscreen mode

you can use:

Browser
   ↓
Your Server
   ↓
Geocoding Provider
Enter fullscreen mode Exit fullscreen mode

This gives you more control over:

  • API keys
  • Rate limiting
  • Caching
  • Logging
  • Error handling
  • Provider changes

It also prevents private API credentials from being exposed in client-side JavaScript.

Common Address-to-Coordinate Mistakes

When implementing geocoding, these problems appear frequently.

1. Assuming the first result is always correct

Generic place names can return multiple matches.

2. Swapping latitude and longitude

Some APIs and mapping formats use different coordinate orders.

3. Not encoding the address

Always encode user input before adding it to a query URL.

4. Expecting every address to exist

Geocoding databases are incomplete and constantly changing.

5. Exposing private API keys

If your provider requires a secret API key, geocoding requests may need to go through your backend.

6. Sending a request on every keystroke

If you're building address autocomplete, debounce requests instead of calling the API for every character.

For example:

let timer;

input.addEventListener("input", () => {
  clearTimeout(timer);

  timer = setTimeout(() => {
    console.log("Search:", input.value);
  }, 400);
});
Enter fullscreen mode Exit fullscreen mode

This greatly reduces unnecessary requests.

Testing Coordinates Manually

When debugging geocoding, it is useful to inspect the result outside your application.

You can search for an address and verify its coordinates with an online coordinate lookup tool such as CoordMap:

https://www.coordmap.com/longitude-latitude-finder

This is especially helpful when you're trying to determine whether a problem comes from:

  • The address
  • The geocoding service
  • Coordinate order
  • Your map code
  • Marker placement

Final Thoughts

Converting an address to latitude and longitude is conceptually simple:

Address
   ↓
Geocoding API
   ↓
Latitude + Longitude
   ↓
Map / Database / Distance Calculation
Enter fullscreen mode Exit fullscreen mode

But reliable geocoding requires more than sending an address to an API.

You also need to consider ambiguous locations, missing addresses, coordinate order, request limits, caching, and error handling.

Once you have valid coordinates, they become the starting point for many other geographic tasks: displaying markers, calculating distances, finding nearby places, reverse geocoding, or performing spatial searches.

And that is why, in most mapping applications, coordinates are usually the beginning rather than the final answer.

Top comments (0)