How to make icon walk in Google Maps api

In my script below it every 30 seconds causes the icon to change position, so that the Icon some and appears at the next point.

  • more what I wanted was for him to walk up to the next point as shown in the image below

insert the description of the image here

As I don't understand javascript I'm asking for this help

//Icons
	var customIcons = {
       airport: {
        icon: 'images/AirPort.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
       hotelothon: {
        icon: 'images/othon.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      
        
    };

	//Popup dos markers
	var infoWindow = null;	

	//A visibilidade do mapa precisa estar global
	var map = null;
	
	//Este é um array global dos marcadores presentes na tela
	var markersArray = [];

	/*
	 * Inicialização da API de Mapas do Google 
	 */
	function initialize() {

		//Não vou explicar o óbvio!!!
		var myLatlng = new google.maps.LatLng(-22.91729049, -43.18914413);
		var myOptions = {
			zoom : 12,
			center : myLatlng,
			mapTypeId : google.maps.MapTypeId.ROADMAP


		}

		map = new google.maps.Map(document.getElementById("map_canvas"),
				myOptions);
          var trafficLayer = new google.maps.TrafficLayer();
          trafficLayer.setMap(map);
          //  Inicio do Jonson para altera a cor do Mapa
        var pink_parks = [
];
    map.setOptions({styles: pink_parks});
    
    directionsDisplay = new google.maps.DirectionsRenderer();    
    directionsDisplay.setMap(map);        
                
           // Fim do jonson     
				
		infoWindow = new google.maps.InfoWindow;				
		
		//Esse método eu criei para realizar o load dos markers no mapa
		//Execução imediata!!!
		updateMaps();

		//Definimos tambem execução com intervalo de tempo
        // 5000 = 5 segundos
        // 10000= 10 segundos
		window.setInterval(updateMaps, 10000);

	}
	
	/*
	 * Método que remove os overlays dos markers
	 */
    function clearOverlays() {
	  for (var i = 0; i < markersArray.length; i++ ) {
	   markersArray[i].setMap(null);
	  }
	}
	
	/*
	 * Método que realiza chama o caminho do xml de dados
	 * e atualiza o mapa
	 */	
	function updateMaps() {

		// Vamos remover o que já havia de overlay
		// É possível implementar a remoção e inclusão seletiva
		clearOverlays();

		//Aqui é o pulo do gato, que muita gente perde noites de sono
		//e quando você para para ver a solução, percebe que é tão óbvia
		
		//Quando chamamos um arquivo, o browser pode tomar a decisão
		//de armazenar em cache. Se o browser utilizar cache, as próximas 
		//requisições do mesmo recurso não batem no servidor.
		
		//Definindo um modificador único para o arquivo de dados conseguimos "FORÇAR" 
		//o browser a baixar novamente o arquivo.
		
		//Em java eu utilizo o header do http para dizer NO-CACHE!!
		
		var timestamp = new Date().getTime();
		var data = 'gps/data.php?t=' + timestamp;
		
		//Me guardo o direito a não explicar o óbvio, novamente
		$.get(data, {}, function(data) {
			$(data).find("gps").each(
			
					function() {
						var gps = $(this);
						var nome = gps.attr("nome");
                        var alti = gps.attr("alti");
                        var bateria = gps.attr("bateria");
						var speed = gps.attr("speed");
                        var data = gps.attr("data");
                        var hora = gps.attr("hora");
						var p_nome = gps.attr("p_nome");
                        var status1 = gps.attr("status1");
                        var destino = gps.attr("destino");
                        var from_to = gps.attr("from_to");
                        var in_out = gps.attr("in_out");
                        var id_saida = gps.attr("id_saida");
                        var start = gps.attr("start");
                        var p_tipo_serv = gps.attr("p_tipo_serv");
                        var hora_start = gps.attr("hora_start");
                        var modelo = gps.attr("veo");
                        var placa = gps.attr("placa");
                        var origem = gps.attr("origem");
                        var destino = gps.attr("destino");
                        var cor = gps.attr("cor");
                        var forn = gps.attr("fornecedor");
                        var foto1 = gps.attr("foto1");
                        var fotom = gps.attr("fotom");
                        var frase = gps.attr("frase");
                        
                        var id_pax = gps.attr("id_pax");
                        
                        var id_motorista = gps.attr("id_motorista");
                        var img = gps.attr("img");
						var statusgps = gps.attr("statusgps");
                        var p_tipo_veiculo = gps.attr("vei");
                    var icon = customIcons[p_tipo_veiculo] || {};
         				var latlng = new google.maps.LatLng(parseFloat(gps
								.attr("lat")), parseFloat(gps.attr("longi")));
						var html = "<b>Codigo do Servi&ccedil;o:&nbsp;" + id_saida + "</b> " + id_motorista + 


"<table border='0' width='400'>"+
"<tbody>"+
"<tr>"+
"<td style='text-align: center; color: #fff; font-family: Segoe,;' colspan='4' bgcolor='#663366'>Detalhes do Transporte</td>"+
"</tr>"+
"<tr>"+
"<td colspan='2' height='40'><br /><strong>Produto:&nbsp;&nbsp;</strong>"+p_nome+"  "+frase+"</td>"+
"<td style='text-align: center;' rowspan='6' width='132'><span style='font-size: xx-small;'>Mororista</span><br /><img src='img/fotos/"+fotom+"' alt='' width='100' /><br />"+nome+"</td>"+
"</tr>"+
"<tr>"+
"<td colspan='2' width='172'><strong>Indo Para:&nbsp;&nbsp;</strong>"+destino+"&nbsp;</td>"+
"</tr>"+
"<tr>"+
"<td><strong>Data:&nbsp;&nbsp;</strong>"+start+"</td>"+
"<td><strong>&nbsp;in/out:</strong> "+in_out+"</td>"+
"</tr>"+
"<tr>"+
"<td><strong>Hora:&nbsp;&nbsp;</strong>"+hora_start+"</td>"+
"<td>&nbsp;<strong>to:</strong> "+from_to+"</td>"+
"</tr>"+
"<tr>"+
"<td><strong>Placa:&nbsp;</strong>"+placa+"</td>"+
"<td>&nbsp;</td>"+
"</tr>"+
"<tr>"+
"<td style='text-align: center;' colspan='2' height='26'><hr /><a href='gps/pax2.php?id_saida="+id_saida+"' target='_blank'><strong>Listar Passageiros</strong></a></td>"+
"</tr>"+
"<tr>"+
"<td>&nbsp;</td>"+
"</tr>"+
"<tr>"+
"<td bgcolor='#330066'><span style='color: #ffffff;'><strong>Speeed:&nbsp;</strong>"+speed+"Km</span></td>"+
"<td colspan='2' bgcolor='#330066'><span style='color: #ffffff;'><strong>Bateria:&nbsp;</strong>"+bateria+"</span></td>"+
"</tr>"+
"</tbody>"+
"</table>"



     
                  
                        "";
       var marker = new google.maps.Marker({
       position : latlng,
   	   map : map,
       title: id_saida,
       icon: icon.icon,
       labelContent: "$425K",
      // labelAnchor: new google.maps.Point(22, 0),
       labelClass: "labels", // the CSS class for the label
       labelStyle: {opacity: 0.75} ,                           

          
                            
							//shadow: icon.shadow,
						});
		
        

        				
						google.maps.event.addListener(marker, 'click', function() {
						        infoWindow.setContent(html);
						        infoWindow.open(map, marker);
						      });						
						
					//Opa... bora guardar as referências dos markers??
					markersArray.push(marker);
						
					google.maps.event.addListener(marker, "click", function() {});
					});
			});
0
		}

		google.setOnLoadCallback(initialize);
	
<script src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Main Container Fluid -->
	<div class="">
	<div id="" style="height: 460px;">



<div id="map_canvas" style="position: absolute; top: 10%;  left: 0%; width: 100%; height: 765px"></div>
<div id="log"></div>			
				
			</div>
Author: Fabio Henrique, 2016-04-26

3 answers

I use the marker animate

Https://github.com/combatwombat/marker-animate

var marker = new google.maps.Marker({position: new google.maps.LatLng(0,0), map: myMap, title: 'Hello World!'});
var newPosition = new google.maps.LatLng(13,42);
marker.animateTo(newPosition, {  duration: 1000 });

If you put the markerAnimate.js in your html and use the code. If it has difficulty it warns me that I make an example with your code.

 11
Author: André Vicente, 2016-04-26 12:41:58

Fábio follows an example that will help you, I created a marker and put it to move to a certain coordinate:

Google maps with animated marker

HTML

<div id="map_canvas" ></div>

JAVASCRIPT

initialize();

function initialize() {
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
    zoom: 10,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
    position: new google.maps.LatLng(-34.397, 150.644),
    map: map
});

var posicaDestino = new google.maps.LatLng(-34.197, 150.644);

marker.animateTo(posicaDestino, {
    duration: 13000,
    complete: function() {
        alert("Chegou ao destino!");
    }
});

}

  1. creates a variable with a coordinate that will be the center.
  2. the options are set to zoom, the center with the coordinate above, and the type of the map.
  3. map is created: new google.maps.Map
  4. create a new marker (marker ) with a coordinate equal to the center.
  5. I create a variable ( destination position ) where the marker will move
  6. I call the marker animation method.animate indicating the displacement speed in milliseconds ( duration ) and a function that will be called upon reaching the -34,197, 150,644 coordinate.

The following resources need to be referenced in the project (Jquery, GoogleMaps and MarkerAnimate):

Note: in your case as it will be capturing new coordinates all the time, let's say every 20s, the above process will run multiple times and the animation method called each time a new position is capture.

If you prefer access my JSFiddle at: http://jsfiddle.net/rodrigorf/gxge3b5c /


Part 2

Editing the answer to add what was done with the existing script, I did not use its XML because the logic was going to be complicated for me to create php and load the information, the concept is the same blz? I simplified just loading data, you'll have to break your head a little bit and learn a little javascript hehehehe. Anyway, it follows what it was done:

  1. the clearOverlays() function should no longer be used, it does not work with it because it removes the created marker from the screen, and we need them with each Update to move them around the screen correctly.
  2. loading new coordinates are being simulated through an array i created in hand. Every Update I pick up the next coordinate.

insert the description of the image here

  1. see that I set the animation time to last 5 seconds between each position and the GPS update time for every 10 seconds.
  2. works for a bookmark and will work for others you have. The difference is that the new positions will not come from an array but from your XML.
  3. I removed the giant list of icons at the beginning because it does not influence the animation part in my tests.
  4. In your case you will not even need to control the nextPos and nextPosGPS because when you pull the data from the XML they are already new data from New coordinated.

    var infoWindow = null;
    var map = null;
    var markersArray = [];
    var nextPosGPS = 0;
    var data = gerarArrayPosicoesGPS();
    
    initialize();
    
    function initialize()
    {
        var myLatlng = new google.maps.LatLng(-22.91829049, -43.18914413);
        var myOptions = {
            zoom: 16,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
    
        map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(map);
    
        var pink_parks = [];
        map.setOptions({
            styles: pink_parks
        });
    
        directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setMap(map);
    
        infoWindow = new google.maps.InfoWindow;
        updateMaps();
        window.setInterval(updateMaps, 10000);
    }
    
    function updateMaps()
    {
        nextPos = nextPosGPS + 1;
        var marker = [];
        var latlng = new google.maps.LatLng(data[nextPos].x, data[nextPos].y);
        if (markersArray.length > 0)
        {
            console.log("pega do array");
            marker = markersArray[0];
            console.log("dados do marker");
        } else
        {
            console.log("cria novo marker");
            marker = new google.maps.Marker({
                position: latlng,
                map: map,
            });
        }
        google.maps.event.addListener(marker, 'click', function () {
            infoWindow.setContent("");
            infoWindow.open(map, marker);
        });
    
        marker.animateTo(latlng, { duration: 5000 });
    
        markersArray.push(marker);
        nextPosGPS++;
    }
    
    function gerarArrayPosicoesGPS()
    {
        var arr = new Array();
        arr.push({ x: -22.91729049, y: -43.18914413 });
        arr.push({ x: -22.91629049, y: -43.18914413 });
        arr.push({ x: -22.91529049, y: -43.18914413 });
        arr.push({ x: -22.91429049, y: -43.18914413 });
        arr.push({ x: -22.91329049, y: -43.18914413 });
        arr.push({ x: -22.91229049, y: -43.18914413 });
        arr.push({ x: -22.91129049, y: -43.18914413 });
        arr.push({ x: -22.91029049, y: -43.18914413 });
        arr.push({ x: -22.90929049, y: -43.18914413 });
        arr.push({ x: -22.90829049, y: -43.18914413 });
    
        return arr;
    }
    

Fabio, even if I do not have in-depth knowledge in JS strongly recommend that you take a little time to break your head and adapt the code, with very little change it will be working with XML. Remember that you cannot call the clearOverlay otherwise the problem of "flashing" the screen will continue to happen. The flow is:

GPS coordinate handle > create marker > GPS coordinate handle > move to new position > coordinate handle GPS > move to new position. And so it goes..

 5
Author: rodrigorf, 2016-05-05 02:38:27

Very simple:

The updateMaps() routine is calling clearOverlays() which clears all markers. So from 30s to 30s they add up and reappear.

Just delete the markers that have not changed in a given time, for example 30mins.

For this add two fields with: last update and the board. So you can identify the markers.

In the updateMaps () routine, locate an existing marker using the board before creating. If the plate exists just update the position.

Let us know if you need more details.

 1
Author: Luiz Vaz, 2016-04-28 03:46:52