I have a form that calculates mileage from 4 destinations to one single origin. When submitted, I can display the text that shows the origin and the distance to each destination on a new line, for example:
Margate, UK to Coventry, UK: 177 mi in 3 hours 13 mins Brighton, UK to Coventry, UK: 158 mi in 2 hours 41 mins Bristol, UK to Coventry, UK: 108 mi in 1 hour 49 mins Birmingham, UK to Coventry, UK: 21.8 mi in 31 mins
I want to create an array of this information so I can call it in other functions. For example, I just want the Destination and the miles, so something like this:
{"Margate, UK" => 177, "Brighton, UK" => 158, "Bristol, UK" => 108, "Birmingham, UK" => 21.8}
Here is the code I use to make the for loop:
function calcDistance(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
You can try making an array const distances = [] and then push into it the desired information in the inner for loop
...
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
distances.push([origins[i], results[j].distance.text])
...
}
or you could extract the information from the submitted form text using regex
const distinations =
'Margate, UK to Coventry, UK: 177 mi in 3 hours 13 mins Brighton, UK to Coventry, UK: 158 mi in 2 hours 41 mins Bristol, UK to Coventry, UK: 108 mi in 1 hour 49 mins Birmingham, UK to Coventry, UK: 21.8 mi in 31 mins'
const cities = distinations.match(/\b(?:(?!Coventry)\w)\w+, \w+/g)
const distances = distinations.match(/(?<=: )\d+/g)
const result = []
for (let index in cities) {
const city = cities[index]
const distance = distances[index]
result.push({
city,
distance
})
}
console.log(result)