Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
Need to loop through Google Distance Matrix JSON Object Response

Okay, so i have a list of businesses each with it's own div created via DOM (document.create(div)) blah blah blah

div business 1. 12 miles (only shows on first div)
div business 2
div business 3 etc.

I'm using Google's Distance Matrix to calculate the users location to the business they choose. I've been able to get the calculations with my code see below. But the distance only shows up for the first div. I've tried every loop possible and still can't get it to post for each business listing

if you're familiar with this api, use the api link below with your own api Key

and plug in your own coordinates to test code

var latitude = localStorage.getItem("userLocationLat");
var longitude = localStorage.getItem("userLocationLong");

  var service = new google.maps.DistanceMatrixService();
  // build request
  var origin1 = new google.maps.LatLng(latitude, longitude);
  var destinationA = new google.maps.LatLng(bizlatitude, bizlongitude);
          var request = {
            origins: [origin1],
            destinations: [destinationA],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.IMPERIAL,
            avoidHighways: false,
            avoidTolls: false
          }

         
      service.getDistanceMatrix(request).then((response) => {
          for(var i in response.rows){
             document.getElementById('distance').innerHTML = response.rows[0].elements[0].distance.text;

              //test in console
              console.log(response.rows[0].elements[0].distance.text);
          }

in the console.log I would get all calculations listed but when i look at the actual website it only displays the calculation for the first business listing

div business 1. 12 miles (only shows on the first div)
div business 2
div business 3 etc.

Link to Google Distance Matrix Documentation https://developers.google.com/maps/documentation/javascript/distancematrix

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!