views:

268

answers:

1

Hi All,

Quick question regarding Google Maps, AJAX and some back end data.

How would I go about creating google map that updates in "real time" with information I have stored in the database?

The way I see it working in my head is.

Database collects geo tagged entries from users. A script (probably php) retrieves the latest record. Javascript + AJAX takes the response and plots it onto Google Maps.

How do I get it to refresh and update as records are being entered?

+2  A: 

You need a script on the server that given a timestamp will check if new records have been inserted in the database after that timestamp. If yes, it should return a response with the latest entry.

On the client side, you should initiate an AJAX request to the server-side script, either using normal or long polling, with the timestamp parameter of the last update.

When your AJAX request receives new information, you should simply move your markers on the map. Then initiate a new AJAX request with the updated timestamp paramater.

Pseudo-example using jQuery:

var lastUpdate = '2000/01/01 00:00:00';

function autoUpdate()
{
    $.ajax({
       type: "GET",
       url: "check_updates.php?last_update=" + lastUpdate,
       dataType: 'json',
       success: function(jsonData) {

          // 1. Check if jsonData is empty. If not we received some fresh data.
          // 2. Update lastUpdate from the jsonData with the timestamp from 
          //    the server. Don't use JavaScript to update the timestamp, 
          //    because the time on the client and on the server will 
          //    never be exactly in sync.
          // 3. Move the markers on Google Map.

          // Relaunch the autoUpdate() function in 5 seconds.
          setTimeout(autoUpdate, 5000);
       }
    });
}
Daniel Vassallo
that makes sense, thanks dan! i'll probably tweak the following code with your approach: http://mapki.com/wiki/AJAX_with_PHP_and_MySQL
st4ck0v3rfl0w