Calculate Distances Api Google Maps v3 Automatically in a Loop

Asked

Viewed 3,719 times

2

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

I’m getting one by one. I have to keep updating the page and give submits so that the result goes to java, all this manually. I would like to put everything in a loop, except google’s 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 google server and send to Servlet.

Is there any chance that this could work?

  • If you have Latitude and Longitude, it is easy to calculate: In PHP (but it is easy to transform) this is done like this: http://www.phpsources.org/scripts459-PHP.htm

2 answers

1

The Spherical Google maps V3 API calculates this for you, when you pass a Latlng array.

var polyLengthInMeters = google.maps.geometry.spherical.computeArea(polygon.getPath().getArray());

1

Look, here’s a simple idea : Work with an array of locations. 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 to the limit of the array. If you have not yet reached the last index, set a timer to call the distance calculation routine once more, doing this until you reach the last position. It works. Hugs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.