Calculate Distance Api Google Maps v3 Automatically in a Loop

2

I would like to calculate the distance between two points using the api Google Maps V3 automatically without the use of interface, and send them to java for future processing. The coordinates are in a MySQL database.

I'm even getting more than one by one. I have to keep updating the page and give submits so the result goes to java, all this manually. I would like to put everything in a loop, but the google function is asynchronous and already has a callback.

//Realiza o calculo das distancias e a detecção da localidade
//start,middle e end são coordenadas no formato do google    
function calculateDistances(start,middle,end) {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [start,middle],
      destinations: [middle,end],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
}

//analiza o resultado retornado pela funcao service.getDistanceMatrix da api do google
function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var values = "";
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      values += origins[i] + "$" + destinations[i]+ "$" + results[i].distance.text + "$" + results[i].duration.text + "#";
    }
    //evnia o valor para o o formulario
    document.getElementById('distance').value = values;
  }
}

The api is in javascript and I have to send the coordinates (lat, lon), wait for the response from the google server and send it to the servlet.

Is there any chance that this works?

    
asked by anonymous 09.09.2014 / 01:47

2 answers

1

The Google Maps V3 API spherical computes this for you, when you pass an array of LatLng.

var polyLengthInMeters = google.maps.geometry.spherical.computeArea(polygon.getPath().getArray());
    
20.05.2015 / 21:21
1

Look, here is a simple idea: Work with an array of locales. Make the call that returns the distance by controlling a variable for this array. At the end of your callback function you increment the variable and compare it with the limit of the array. If you have not yet reached the last index, program a timer to call the distance calculation routine one more time, doing this until you reach the last position. It works. Hugs.

    
07.08.2016 / 03:17