Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Google Maps API: How to Calculate Distance from Text?

Learn how to use Google Maps API to calculate miles between cities from user input like ‘City A to City B’ with a simple text field.
Thumbnail showing Google Maps with a route from New York to Boston beside a text input field with 'New York to Boston' typed in, demonstrating how to calculate distance from raw text using Google Maps API Thumbnail showing Google Maps with a route from New York to Boston beside a text input field with 'New York to Boston' typed in, demonstrating how to calculate distance from raw text using Google Maps API
  • 📏 Google Maps Distance Matrix API can determine exact miles between cities from user text.
  • 🧠 Nielsen data shows typed destination inputs improve user satisfaction over dropdowns.
  • 💲 Google Maps API offers 500 free elements monthly; overages incur usage-based charges.
  • 🗺️ Map routes look better and improve user experience when shown with distance data.
  • 🧠 Regex parsing helps pull out start and end cities from what users type.

When users type phrases like “Chicago to Detroit,” instead of picking from lists, your app feels smarter and more natural. In this guide, you will learn how to use the Google Maps API to figure out miles between cities from text users type. This gives your users an easy, easy-to-use experience. And it also gives you a strong system you can add to web or mobile apps.


Understanding the Google Maps Distance Matrix API

The Google Maps Distance Matrix API is key for figuring out distances in your app. This API calculates travel distance and time between two or more places. For example, if you are finding two specific cities, neighborhoods, or landmarks, this API gives quick, correct results for your users.

The Distance Matrix API works for different ways to travel, including:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 🚗 Driving
  • 🚶 Walking
  • 🚲 Bicycling
  • 🚍 Transit (bus, subway, trains)

It works well and lets you ask for information in both metric and imperial units. For most apps in the U.S., users usually want results in miles. So, adding units=imperial is important.

Here’s a sample request URL:

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Chicago&destinations=Detroit&key=YOUR_API_KEY

The response contains:

  • The travel distance (like "282 mi")
  • How long it will take (based on traffic now or traffic you set)
  • Codes that help check for errors or explain things

Tip: The API is made to figure out results for many start and end places. But this example only looks at one city calculation to keep it simple and on point.


Parsing Freeform Text Input Like “City A to City B”

One helpful user interface improvement is letting users just type where they are going, like “New York to Miami.” This is better than making them pick from lists or maps. But, this needs smart text reading to happen in the background.

A simple regex (regular expression) can pull out the two cities from a phrase that is written correctly:

const input = "San Francisco to Las Vegas";
const regex = /([A-Za-z\s]+)\s+to\s+([A-Za-z\s]+)/i;
const match = input.match(regex);

if (match) {
  const origin = match[1].trim();
  const destination = match[2].trim();
}

This regular expression looks for:

  • City names that have spaces or letters
  • The word “to” to show a trip
  • It works no matter if letters are big or small

This solution works for most common things users type. But it might not be enough for different types of questions, like:

  • “Headed from Atlanta to Nashville”
  • “How far is it from Dallas to Austin?”

To handle harder or more conversational text, add light Natural Language Processing (NLP) tools. A service like Google’s Dialogflow or spaCy (for Python) can help figure out how sentences are built and pull out place names.

🧠 A 2022 study by Nielsen Norman Group found that letting users type destinations was faster and made users happier than dropdowns and map choices. So, choosing to read text like this is not just a tech choice, but also a win for how easy the app is to use.


Setting Up Google Maps API and Getting Your API Key

Before you start development, you'll need to set up your project in the Google Cloud environment. Here’s a step-by-step guide:

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Go to APIs & Services > Library.
  4. Enable the following APIs:
    • 💡 Maps JavaScript API
    • 📏 Distance Matrix API
  5. Go to APIs & Services > Credentials to make a new API key.
  6. To keep things secure, set up HTTP referrer restrictions (for web apps) or IP address restrictions (for backend apps).

🔐 Important: Always keep your API key safe. Never upload it to a public place or show it in frontend code unless a referrer protects it.

Pricing Notes:

  • Free tier: The Distance Matrix API lets you make 500 requests per month for free.
  • Billing: After that, Google charges for each request. For example, one request with 1 start and 1 end point counts as 1 element.

💲 Fun Fact: MarketsandMarkets (2023) says the global routing API business—this includes tools like Distance Matrix—is worth over $15 billion.


Making the API Call from Parsed Cities

Once you have pulled out city names and kept your API key safe, you are ready to figure out distance using a simple JavaScript function.

async function getDistance(origin, destination) {
  const key = 'YOUR_API_KEY';
  const url = `https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=${encodeURIComponent(origin)}&destinations=${encodeURIComponent(destination)}&key=${key}`;

  const response = await fetch(url);
  const data = await response.json();
  return data;
}

This function sends a GET request to the Distance Matrix API. The encodeURIComponent makes sure that spaces or special characters in city names do not mess up the URL.

The result will include:

  • distance: A string a person can read (like "320 mi")
  • duration: How long it takes to travel (like "4 hours 50 mins")
  • status fields: Helpful for finding input errors, wrong addresses, or problems with your usage limit

Converting Distance into Miles

If you set units=imperial, the API will give distances in miles on its own. Most users in the U.S. want to see distances in miles, as it makes sense and is easy to read.

From the API response:

const distanceText = data.rows[0].elements[0].distance.text; // e.g., "381 mi"
const distanceValue = data.rows[0].elements[0].distance.value; // in meters

If you need to convert the raw meters to miles:

const miles = (distanceValue / 1609.344).toFixed(2);

This gives you an exact number to keep, follow, or show in your app.


Simple Web App: Live Distance from Text Input

Let’s build a basic HTML tool that lets users enter something like “Seattle to Portland” and quickly get the distance.

<input type="text" id="cityInput" placeholder="e.g., Seattle to Portland">
<button onclick="calculate()">Calculate Distance</button>
<p id="result"></p>

<script>
async function calculate() {
  const input = document.getElementById('cityInput').value;
  const regex = /([A-Za-z\s]+)\s+to\s+([A-Za-z\s]+)/i;
  const match = input.match(regex);
  if (!match) return alert("Invalid format! Please use city-to-city phrasing.");

  const origin = match[1].trim();
  const destination = match[2].trim();

  const url = `https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=${encodeURIComponent(origin)}&destinations=${encodeURIComponent(destination)}&key=YOUR_API_KEY`;

  const res = await fetch(url);
  const data = await res.json();

  if (data.rows[0].elements[0].status !== "OK") {
    document.getElementById('result').textContent = "Couldn't find a valid route.";
    return;
  }

  const distance = data.rows[0].elements[0].distance.text;
  document.getElementById('result').textContent = `Distance: ${distance}`;
}
</script>

This app looks at the format, makes the API call, and displays results—all in under 50 lines of code.


Error Handling and User Input Validation

When you work with user input and APIs, you are likely to run into unusual situations. Here are some situations and good ways to do things:

Common Errors:

  • ❌ Misspellings in city names can lead to ZERO_RESULTS.
  • ⚠️ Cities with the same name (like “Springfield”) make it unclear which one.
  • 🔒 Wrong API settings can lead to REQUEST_DENIED.

Validation Tips:

  • Give hints or use auto-suggestions.
  • Check how long and what format the input is before sending the request.
  • Use Google’s Places API for better autocomplete and to tell similar places apart.

And in your call, always check:

if (data.status !== "OK" || data.rows[0].elements[0].status !== "OK") {
  // Handle the error or notify users
}

Adding a Visual Map or Route

Text distances are useful, but showing a route on a map makes it more believable and clear. You can use the Google Maps JavaScript API to display a map route.

const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();

directionsRenderer.setMap(map);
directionsService.route({
  origin: origin,
  destination: destination,
  travelMode: 'DRIVING',
}, (result, status) => {
  if (status === 'OK') {
    directionsRenderer.setDirections(result);
  }
});

This changes your app from a simple calculator to something that helps with directions. You can also let users pick how they want to travel or change stops on the fly.


Securing and Optimizing the App

To protect your app and make it work for more users:

Security

  • 🔐 Limit your API key by domain or IP address.
  • 🔑 Use environment variables for secret information (especially on the server).
  • ⛔ Never show your API key in client-side code.

Optimization

  • ⚡ Use caching (like Cloudflare, Redis) for requests that happen often.
  • 📉 Reduce extra calls by using debounced input.
  • 💬 Set limits on how many calls can be made (rate-limiting) if you add user accounts.

⚠️ Google Cloud Docs (2023) says users get 500 elements per month for free. Keep an eye on usage so you do not get unexpected bills.


Bringing This to Mobile Apps

No matter if you are building in native code or using mobile frameworks, the way to calculate distance can fit in easily:

  • React Native: Use fetch() like on the web; use with React hooks.
  • Flutter: Use the http package or Dio, with JSON decoding.
  • iOS (Swift): Use URLSession to make API calls.
  • Android (Kotlin): Use Retrofit or OkHttp.

Tip: On mobile, think about having the start point fill in by itself from GPS location, using navigator.geolocation or APIs built for the platform.


Going Beyond: Multi-City and Estimated Times

To handle more complex uses:

  • 🧭 Read inputs like “NY to Chicago to LA” and figure out each part of the trip.
  • 🛣️ Use the Directions API for full route planning, including turn-by-turn directions.
  • ⌚ Add departure_time=now to get estimates that are updated for live traffic.

You can also use:

...&traffic_model=best_guess

Putting this data together helps plan trips with time predictions, not just distances.


Things Developers Should Avoid

  • Do not hardcode distances; routes change because of traffic and closed roads.
  • Be careful with city names that are in different places (like “Paris” in Texas versus France).
  • Always check how many API calls you can make and any error messages.

A strong app that can handle more users tests these unusual cases before it goes live. And it includes helpful messages if something goes wrong.


Alternatives to Google Maps API

Google Maps is good, but it is not your only choice. Other options might work better, depending on your budget or region:

Provider Free Tier Notes
OpenRouteService Good free limits Open source; good for researchers or apps in the EU
HERE Technologies 250k transactions/month (free) Strong and easy-to-use platform for developers
Mapbox 100k directions/month (free) Good looking maps and vector maps

Think about these if you are making your app work worldwide, have a limited budget, or want open-source control.


Turning Input into Location Intelligence

When a user types “Miami to Tampa,” you now know how to read what was typed. You can figure out exact distance and time with the Google Maps API. And you can show it with good-looking user interfaces and maps. No matter if you are building delivery software, travel apps, or learning tools, this skill changes simple text into useful location information.

When you add traffic data, predict arrival times, or show full trip plans, your app does not just give facts, it gives understanding.


Citations

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading