I am trying to develop a site that simulates a moving bus on Google Maps according to a set of predefined coordinates. I am working on PHP, HTML and Javascript (Google Maps Api). The database holding the coordinates is on localhost. My question has to do with the actual simulation of the bus moving towards all the coordinates in the database.
To explain: The database looks like this:
id latt lon
1. 53.4877 -2.27519
2. 53.4859 -2.27489
etc. There are 14 entries.
The PHP script that connects to the database:
<?php
$host = "localhost";
$user = "hidden";
$pass = "";
$databaseName = "database";
$tableName = "locations";
$con = mysql_connect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ($row = mysql_fetch_row($result)) {
$data[] = $row;
}
echo json_encode($data);
?>
The javascript function:
function moveBus(map, marker)
{
$.ajax({
url: 'api2.php',
data: "",
dataType: 'json',
async: false,
success: function(data)
{
for (var i in data)
{
var row = data[i];
var latt = row[1];
var lon = row[2];
moveMarker(map, marker, latt, lon);
}
}
})
};
The moveMarker function:
function moveMarker( map, marker, latt, lon) {
setTimeout( function(){ marker.setPosition( new google.maps.LatLng( latt , lon ) ); }, 3500 );
};
As you can understand what I have now just sends the bus marker on the last set of coordinates after the loop is finished instead of showing the whole route it makes to get there. I have tried lots of different approaches to make this happen without success.
Any ideas?
Thank you in advance.
Your setTimeouts finish at the same time 3500 ms. You should increase time outs for points based on their order... something like position_on_route *3500.
for (var i in data)
{
var row = data[i];
var latt = row[1];
var lon = row[2];
timeout=i*3500;
moveMarker(map, marker, latt, lon, timeout);
}
function moveMarker( map, marker, latt, lon, timeout) {
setTimeout( function(){ marker.setPosition( new google.maps.LatLng( latt , lon ) ); }, timeout );
};