Tuesday, February 14, 2012

Simulating moving targets in Google Maps

Recently i made a project in which I had to simulate real targets/GPS Clients moving gently in Google Maps. I want to share the logic for people who want similar codes.

DEMO: http://hobbycoders.com/demos/gpssimulation

Google API provides a method of directly rendering the entire path between a source and destination. But if you want the same thing to be done but simulating a moving target in the same path, a bit of code has to be written. So here is the logic:

1. Google API can give the path coordinates (Latitude, Longitude) in JSON or XML. An example of JSON direction lookup from Srirangam to Trichy (They both are places in India), google direct URI which gives direct JSON output will look like:

2. Now from AJAX get the output of file and make a Javascript object from it easily (thats why JSON used). I was facing problem of cross domain ajax referencing with this, so i created a Java code in my domain which can proxy the web page for me in same domain

3. Once done, for each step of direction (like first turn left, then turn left etc.,), you get a variable called points in converted Javascript object from JSON. To extract it use:

4. If you notice, the points data will be encoded. Decode it, google has already given the code to decode it

5. And now for each step in direction, you will get many coordinates of latitude-longitude pair

6. Create a Polyline (Google Map object) for each pair of lat-long (if you need the entire trail of path) or a Marker (only current position)

7. Call some delay function in javascript like setInterval will be a good choice, iterate through the coordinates slowly and render polylines. This will give a feeling that some target is actually moving on map

8. Use a loop and do the same for many targets, so that many GPS targets will be on your Google Map (Multithreading experience)

Code Demo: http://hobbycoders.com/demos/gpssimulation   (view the source code of the demo)

If you face any problem with the logic/code i shared or if you need any code helps with this please email me or leave a comment here. If you have an alternate method also, please share.