Distance betweens one point and multiple points

419 views
Skip to first unread message

Dam28800

unread,
Jul 12, 2011, 5:38:25 AM7/12/11
to google-map...@googlegroups.com
Hi,

I am looking to calculate the distance between an address and other addresses.
In searching the forum I found this code and I have adapted as best I could :

var tab_ville = array("toronto, ont", "chicago, il");  
var arrayCount = 0;  

function makeRequest(requestVar) { 
directionsService.route(requestVar, function (response,status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
arrayCount ++;
if (arrayCount < tab_ville.length) { 
var nextEnd = new google.maps.LatLng(tab_ville[arrayCount][0], tab_ville[arrayCount][1]);
nextRequest = { 
                      origin: start, 
                      destination: nextEnd 
                  }; 
                //  recursive call to the request function 
                 makeRequest(nextRequest); 
}
}
});
}

I have a function that calculates the distance between two fixed points, I would like tomerge these two codes but I do not see how

  function calcRoute() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
   /* var waypts = [];
    var checkboxArray = document.getElementById("waypoints");
    for (var i = 0; i < checkboxArray.length; i++) {
      if (checkboxArray.options[i].selected == true) {
        waypts.push({
            location:checkboxArray[i].value,
            stopover:true});
      }
 
    }
 */
    var request = {
        origin: start, 
        destination: end,
       /* waypoints: waypts,
        optimizeWaypoints: true,*/
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        var route = response.routes[0];
        var summaryPanel = document.getElementById("directions_panel");
        summaryPanel.innerHTML = "";
        // For each route, display summary information.
        for (var i = 0; i < route.legs.length; i++) {
          var routeSegment = i + 1;
          summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
          summaryPanel.innerHTML += route.legs[i].start_address + " to ";
          summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
          summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
        }
      }
    });
  }

Thank you in advance for your help and sorry for my english I'm french.

Esa

unread,
Jul 12, 2011, 6:54:59 AM7/12/11
to Google Maps JavaScript API v3
You should study Google Distance Matrix service
http://code.google.com/apis/maps/documentation/distancematrix/

Dam28800

unread,
Jul 13, 2011, 4:12:46 AM7/13/11
to google-map...@googlegroups.com
Thank you for your answers.
It's ok, but I do not know how to feed the destinations in my data from my mysql database.

My Code :
<html> 
  <head> 
    <title>Google Maps API v3 Example: Distance Matrix</title> 
   
   <script type='text/javascript'>
function getXhr(){
                                var xhr = null; 
if(window.XMLHttpRequest) // Firefox et autres
  xhr = new XMLHttpRequest(); 
else if(window.ActiveXObject){ // Internet Explorer 
  try {
               xhr = new ActiveXObject("Msxml2.XMLHTTP");
           } catch (e) {
               xhr = new ActiveXObject("Microsoft.XMLHTTP");
           }
}
else { // XMLHttpRequest non supporté par le navigateur 
  alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
  xhr = false; 
                                return xhr;
}
// Quand je sélectionne une ville
function go(){
var xhr = getXhr();
// On défini ce qu'on va faire quand on aura la réponse
xhr.onreadystatechange = function(){
// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
if(xhr.readyState == 4 && xhr.status == 200){
leselect = xhr.responseText;
// On se sert de innerHTML pour rajouter les options a la liste
document.getElementById('resultat').innerHTML = leselect;
}
}

// Ici on va voir comment faire du post
xhr.open("POST","ajax.php",true);
// ne pas oublier ça pour le post
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// ne pas oublier de poster les arguments
sel = document.getElementById('start');
client = sel.options[sel.selectedIndex].value;
xhr.send("client="+client);

}

</script>
    </script> 
    
 
    <style type="text/css"> 
      body {
        margin: 20px;
        font-size: 12px;
      }
      #map {
        height: 480px;
        width: 640px;
        border: solid thin #333;
        margin-top: 20px;
      }
    </style> 
 
<?php
include('connexion_base.php');
//Reqête pour alimenter le menu déoulant
$retour_sel = mysql_query(" SELECT CONCAT(c.nom, ' ', c.ville) AS Client,
c.id_client,
CONCAT(cc.lat, ',', cc.lon) AS coord
FROM client c
JOIN client_coord cc
ON c.id_client=cc.client_co
GROUP BY c.id_client
ORDER BY c.nom");


//Requête pour alimenter l'array destination en fixe
$retour = mysql_query(" SELECT c.nom,
CONCAT(cc.lat, ',', cc.lon) AS coord
FROM client c
JOIN client_coord cc
ON c.id_client=cc.client_co
ORDER BY c.nom
LIMIT 0,10");
$i=1;
while ($donnees = mysql_fetch_array($retour))
{
$destination[$i] = $donnees['coord'];
$i++;
}
?>
    <script> 
 
      var map;
      var geocoder;
      var bounds = new google.maps.LatLngBounds();
      var markersArray = [];
      
// Array en fixe qui devra être alimenter par la requête ajax
      var destinationA = "<?php echo $destination['1']; ?>";
      var destinationB = "<?php echo $destination['2']; ?>";
 var destinationC = "<?php echo $destination['3']; ?>";
 var destinationD = "<?php echo $destination['4']; ?>";
 var destinationE = "<?php echo $destination['5']; ?>";
 //var desti = array["Marseille, France", "Nice, France"];
 
      function initialize() {
        var opts = {
          center: new google.maps.LatLng(55.53, 9.4),
          zoom: 10,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map'), opts);
        geocoder = new google.maps.Geocoder();
      }
    
      function calculateDistances() {
var origin1 = document.getElementById("start").value;
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
          {
            origins: [origin1],
            destinations: [destinationA, destinationB, destinationC, destinationD, destinationE],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
          }, callback);
      }
 
      function callback(response, status) {
        if (status != google.maps.DistanceMatrixStatus.OK) {
          alert('Error was: ' + status);
        } else {
          var origins = response.originAddresses;
          var destinations = response.destinationAddresses;
          var outputDiv = document.getElementById('outputDiv');
          outputDiv.innerHTML = "";
          deleteOverlays();
 
          for (var i = 0; i < origins.length; i++) {
            var results = response.rows[i].elements;
            addMarker(origins[i], false);
            for (var j = 0; j < results.length; j++) {
              addMarker(destinations[j], true);
              outputDiv.innerHTML += "<table border='1'><tr><td><b>" + origins[i] + "</b></td><td>" + destinations[j]
                  + "</td><td>" + results[j].distance.text + "</td><td>"
                  + results[j].duration.text + "</td></tr></table>";
            }
outputDiv.innerHTML += "";
          }
        }
      }
 
      function addMarker(location, isDestination) {
        var icon;
        if (isDestination) {
          icon = destinationIcon;
        } else {
          icon = originIcon;
        }
        geocoder.geocode({'address': location}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            bounds.extend(results[0].geometry.location);
            map.fitBounds(bounds);
            var marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location,
              icon: icon
            });
            markersArray.push(marker);
          } else {
            alert("Geocode was not successful for the following reason: "
              + status);
          }
        });
      }
      
      function deleteOverlays() {
        if (markersArray) {
          for (i in markersArray) {
            markersArray[i].setMap(null);
          }
          markersArray.length = 0;
        }
      }
 
    </script> 
  </head> 
  <body onLoad="initialize()"> 
    
    <div id="resultat"></div>
    <div id="inputs"> 
      <pre class="prettyprint"> 

      </pre> 
      <p>
      <select id="start" onChange="go()"> 
<?php
while ($donnees_sel = mysql_fetch_array($retour_sel))
{
echo '<option value="'.$donnees_sel['coord'].'">'.$donnees_sel['Client'].'</option>';
}
?>
</select> 
      
      <button type="button" onClick="calculateDistances();">Calculate
        distances</button></p> 
    </div> 
    <div id="outputDiv"></div> 
    <div id="map"></div> 
  </body> 
</html> 

Ajax Code : 

if(isset($_POST["client"]))
{
include ('connexion_base.php');
$tab = explode(',', $_POST['client']);
$radius = 2000;
$lat_gps = $tab[0];
$lon_gps = $tab[1];

$query = sprintf(" SELECT CONCAT(c.nom, ' ', c.ville) AS Client,
CONCAT(cc.lat, ',', cc.lon) AS coord,
( 6371 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lon ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance 
FROM client c  
JOIN client_coord cc
ON c.id_client=cc.client_co
HAVING distance < '%s' 
ORDER BY distance ASC  
LIMIT 0, 10",
mysql_real_escape_string($lat_gps),
mysql_real_escape_string($lon_gps),
mysql_real_escape_string($lat_gps),
mysql_real_escape_string($radius));
$result = mysql_query($query);
$i=1;
while ($row = mysql_fetch_array($result))
{  
$destination[$i] = $row['coord'];
echo $row['Client'].'<br>';
$i++;
}
}

Thank you in advance for your help.

Reply all
Reply to author
Forward
0 new messages