How to make animated moving marker on Google map using javascript | Geek On Java - Hub for Java and Android

728x90 AdSpace

Latest News
Monday, 13 October 2014

How to make animated moving marker on Google map using javascript

Hello friends today i am telling you how you can be make animated marker on Google map using javascript.
How to make animated moving marker on Google map using javascript,make animated moving marker on Google map using javascript,animated moving marker on Google map using javascript,moving marker on Google map using javascript,marker on Google map using javascript,Google map using javascript,

Working Demo click here : Updated

Source Code :

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>GeekOnJava: Directions Complex</title>
  

<style>
html{height:100%;}
body{height:100%;margin:0px;font-family: Helvetica,Arial;}
</style>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script>
<script type="text/javascript">
  
  var map;
  var directionDisplay;
  var directionsService;
  var stepDisplay;
 
  var position;
  var marker = [];
  var polyline = [];
  var poly2 = [];
  var poly = null;
  var startLocation = [];
  var endLocation = [];
  var timerHandle = [];
    
  
  var speed = 0.000005, wait = 1;
  var infowindow = null;
  
  var myPano;   
  var panoClient;
  var nextPanoId;
  
  var startLoc = new Array();
  startLoc[0] = 'rio claro, trinidad';
  startLoc[1] = 'preysal, trinidad';
  startLoc[2] = 'san fernando, trinidad';
  startLoc[3] = 'couva, trinidad';

  var endLoc = new Array();
  endLoc[0] = 'princes town, trinidad';
  endLoc[1] = 'tabaquite, trinidad';
  endLoc[2] = 'mayaro, trinidad';
  endLoc[3] = 'arima, trinidad';


  var Colors = ["#FF0000", "#00FF00", "#0000FF"];


function initialize() {  

  infowindow = new google.maps.InfoWindow(
    { 
      size: new google.maps.Size(150,50)
    });

    var myOptions = {
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    address = 'Trinidad and Tobago'
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
     map.fitBounds(results[0].geometry.viewport);

    }); 
  // setRoutes();
  } 


function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
    var contentString = '<b>'+label+'</b><br>'+html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: label,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });
        marker.myname = label;


    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,marker);
        });
    return marker;
}  

function setRoutes(){   

    var directionsDisplay = new Array();

    for (var i=0; i< startLoc.length; i++){

    var rendererOptions = {
        map: map,
        suppressMarkers : true,
        preserveViewport: true
    }
    directionsService = new google.maps.DirectionsService();

    var travelMode = google.maps.DirectionsTravelMode.DRIVING;  

    var request = {
        origin: startLoc[i],
        destination: endLoc[i],
        travelMode: travelMode
    };  

        directionsService.route(request,makeRouteCallback(i,directionsDisplay[i]));

    }   


    function makeRouteCallback(routeNum,disp){
        if (polyline[routeNum] && (polyline[routeNum].getMap() != null)) {
         startAnimation(routeNum);
         return;
        }
        return function(response, status){
          
          if (status == google.maps.DirectionsStatus.OK){

            var bounds = new google.maps.LatLngBounds();
            var route = response.routes[0];
            startLocation[routeNum] = new Object();
            endLocation[routeNum] = new Object();


            polyline[routeNum] = new google.maps.Polyline({
            path: [],
            strokeColor: '#FFFF00',
            strokeWeight: 3
            });

            poly2[routeNum] = new google.maps.Polyline({
            path: [],
            strokeColor: '#FFFF00',
            strokeWeight: 3
            });     


            // For each route, display summary information.
            var path = response.routes[0].overview_path;
            var legs = response.routes[0].legs;


            disp = new google.maps.DirectionsRenderer(rendererOptions);     
            disp.setMap(map);
            disp.setDirections(response);


            //Markers               
            for (i=0;i<legs.length;i++) {
              if (i == 0) { 
                startLocation[routeNum].latlng = legs[i].start_location;
                startLocation[routeNum].address = legs[i].start_address;
                // marker = google.maps.Marker({map:map,position: startLocation.latlng});
                marker[routeNum] = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
              }
              endLocation[routeNum].latlng = legs[i].end_location;
              endLocation[routeNum].address = legs[i].end_address;
              var steps = legs[i].steps;

              for (j=0;j<steps.length;j++) {
                var nextSegment = steps[j].path;                
                var nextSegment = steps[j].path;

                for (k=0;k<nextSegment.length;k++) {
                    polyline[routeNum].getPath().push(nextSegment[k]);
                    //bounds.extend(nextSegment[k]);
                }

              }
            }

         }       

         polyline[routeNum].setMap(map);
         //map.fitBounds(bounds);
         startAnimation(routeNum);  

    } // else alert("Directions request failed: "+status);

  }

}

    var lastVertex = 1;
    var stepnum=0;
    var step = 50; // 5; // metres
    var tick = 100; // milliseconds
    var eol= [];
//----------------------------------------------------------------------                
 function updatePoly(i,d) {
 // Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
    if (poly2[i].getPath().getLength() > 20) {
          poly2[i]=new google.maps.Polyline([polyline[i].getPath().getAt(lastVertex-1)]);
          // map.addOverlay(poly2)
        }

    if (polyline[i].GetIndexAtDistance(d) < lastVertex+2) {
        if (poly2[i].getPath().getLength()>1) {
            poly2[i].getPath().removeAt(poly2[i].getPath().getLength()-1)
        }
            poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),polyline[i].GetPointAtDistance(d));
    } else {
        poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),endLocation[i].latlng);
    }
 }
//----------------------------------------------------------------------------

function animate(index,d) {
   if (d>eol[index]) {

      marker[index].setPosition(endLocation[index].latlng);
      return;
   }
    var p = polyline[index].GetPointAtDistance(d);

    //map.panTo(p);
    marker[index].setPosition(p);
    updatePoly(index,d);
    timerHandle[index] = setTimeout("animate("+index+","+(d+step)+")", tick);
}

//-------------------------------------------------------------------------

function startAnimation(index) {
        if (timerHandle[index]) clearTimeout(timerHandle[index]);
        eol[index]=polyline[index].Distance();
        map.setCenter(polyline[index].getPath().getAt(0));

        poly2[index] = new google.maps.Polyline({path: [polyline[index].getPath().getAt(0)], strokeColor:"#FFFF00", strokeWeight:3});

        timerHandle[index] = setTimeout("animate("+index+",50)",2000);  // Allow time for the initial map display
}

//----------------------------------------------------------------------------    



</script>
</head>
<body onload="initialize()">

<div id="tools">

    <button onclick="setRoutes();">Start</button>

</div>

<div id="map_canvas" style="width:100%;height:100%;"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>

Output of above code :
  • Blogger Comments
  • Facebook Comments

21 comments:

  1. Hello. I want to fixed the speed for each marker. You can help me?

    ReplyDelete
    Replies
    1. Yes you can fixed (increase or decrease) the speed of marker. Just find :-
      var speed = 0.000005, wait = 1; line and change it as you want

      Delete
  2. hlw i want to change the locations of the mark. hw can i do?

    ReplyDelete
    Replies
    1. You can change the location of mark by change the address of startLoc and endLoc.

      Delete
  3. Hello, is it possible to remove the route when it is complete?

    ReplyDelete
    Replies
    1. Yes you can remove the route by call updatePoly(0, 0) method after complete

      Delete
  4. Can you have your own path (a sequence of lat/lon pair)? I'm not getting anything from directionService.route to see how these values are stored.

    ReplyDelete
    Replies
    1. Yes you can set your own path by using startLoc and endLoc array. You can check the live demo here.

      Delete
  5. Thanks for this. One question:

    I'm editing the speed var but it's not having an effect on the application. I do not see the speed var being used anywhere after is initialised, what am I missing?

    ReplyDelete
    Replies
    1. Can you please share your code for better understanding ?

      Delete
  6. Re: changing the speed at which the marker moves. I have tried changing the speed variable but it has had no effect. I cannot see the speed var being used anywhere after it is initialised. Could you explain a bit more please

    ReplyDelete
  7. Thanks for this, I see the map but can't see any markers. How can I fix that?

    ReplyDelete
    Replies
    1. Did you add library proper ? Please check it again and which browser you used ?

      Delete
  8. Hello

    Quick question - If I have all coordinates stored in database as MySQL, could you help me with code to show animated markers on map with those coordinates? Thank you

    ReplyDelete
    Replies
    1. you can jquery and javascript to fetch coordinate from MySql and set in startLoc and endLoc array

      Delete
    2. Could you please show me some kind of simple code example, just to feel what you talking about. Thank you

      Delete
  9. hi how do i change startLoc and endLoc
    will i put coordinates or will i put just the name ? thanks for helping :))

    ReplyDelete
  10. how can i put the startLoc and EndLoc from server side,like using markers[]

    ReplyDelete
  11. Hey,
    One important issue i faced during running the code.Where startLoc[i] & endLoc[i]

    The array length i value it takes from 0 to 9 only.
    It implements the diaplay upto 0 to 9. And later the values we assigned it doesn't take those values to display.
    Can you help me out please

    ReplyDelete
  12. Sir, may I know how to display the current latitude and longitude of the marker from time to time? As I just can display the initial place latitude and longitude of marker, may I know how to display the latest coordinates of marker when click on the marker?

    ReplyDelete
  13. Sir, is it possible to get the update coordinates when marker move? For example, The coordinates of marker per every second of 10 seconds. Thank you

    ReplyDelete

Item Reviewed: How to make animated moving marker on Google map using javascript Rating: 5 Reviewed By: Sawan Kumar