Skip to content
the poor coder

google distance value to km convert

Poor Man
Published
Reading time
1 min read
On this page

Converting Google Distance Value to Kilometers#

If you have ever used the Google Maps Distance Matrix API, you may have noticed that the distance is returned in meters. However, often times we need to convert this value to kilometers for better readability. Here are a few ways you can do this conversion:

Method 1: Manual Conversion#

The simplest way to convert the distance value from meters to kilometers is to divide it by 1000:

Text
const distanceInMeters = 5000;
const distanceInKilometers = distanceInMeters / 1000; // Output: 5

Method 2: Using a Conversion Function#

You can also create a function that takes in the distance in meters and returns the value in kilometers:

Text
function convertMetersToKilometers(meters) {
  const kilometers = meters / 1000;
  return kilometers;
}

// Usage
const distanceInMeters = 5000;
const distanceInKilometers = convertMetersToKilometers(distanceInMeters); // Output: 5

Method 3: Using a Library#

Another way to convert the distance value to kilometers is by using a library such as convert-units. This library allows you to easily convert between different units of measurement including length, mass, temperature, etc.

Text
const convert = require('convert-units');

// Usage
const distanceInMeters = 5000;
const distanceInKilometers = convert(distanceInMeters).from('m').to('km'); // Output: 5

Method 4: Using Google Maps API Utility Library#

If you are already using the Google Maps JavaScript API, you can also use the Google Maps API Utility Library to convert the distance value to kilometers:

Text
// Load the library


// Usage
const distanceInMeters = 5000;
const distanceInKilometers = google.maps.geometry.spherical.computeLength([LatLng1, LatLng2]) / 1000; // Output: 5

Using any of these methods, you can easily convert the distance value returned by the Google Maps Distance Matrix API to kilometers for better readability.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC