Search code examples
javascriptsqlgoogle-mapsgoogle-maps-api-2

Getting the Distance between Two Points More than Once


I had to repair an old project regarding google maps so this is in V2. In my database, I already had the latlng of all the user in my database. Then there are certain events that the system can create (e.g. a fire event). Now, the system should be able to compute the distance of all the users from the fire event and list down all the people based on their distance from the area. How can I do that? fromAddress should be an array of the people's latlng and toaddress is the latlng of the event. The logic must be similar to the code below

for(i=0;i<fromAddress.length;i++){
    gdir.load("from: " + fromAddress[i] + " to: " + toAddress,  { "locale": "en" });
    distance = Math.round((gdir.getDistance().meters / 1000)*10)/10;
    duration = Math.round(gdir.getDuration().seconds/60);
    //store distance and duration for output
}

Thanks!


Solution

  • There are different options:

    1. When the distance doesn't have to be based on a route, you don't need any requests, you may calculate the distance using google.maps.geometry.spherical.computeDistanceBetween()
      In v2 use distanceFrom
    2. request a directionResult for every origin/destination-pair
      (V2: getDistance())
    3. request a DistanceMatrixResult , it allows you to retrieve up to 25 results with 1 request
      (This is not available in V2, but you may request the web-service: http://code.google.com/intl/en/apis/maps/documentation/distancematrix/ )