<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.