How to do Icone walk in api Google Maps

20

In My script below it every 30 seconds causes the icon to change position, only the icon disappears and appears at the next point.

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

AsIdonotunderstandjavascriptI'maskingforthishelp

//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><scripttype="text/javascript" src="http://www.google.com/jsapi"></script><scriptsrc="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>
    
asked by anonymous 26.04.2016 / 02:28

3 answers

11

I use the Marker animate

  

link

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 markerAnimate.js in your html and use the code. If you have difficulty let me know that I'll give you an example with your code.

    
26.04.2016 / 14:41
5

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

HTML

<divid="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!");
    }
});

}

  • Creates a variable with a coordinate that will be the center.
  • The options are set to zoom, the center with the above coordinate and the map type.
  • Map is created: new google.maps.Map
  • I create a new marker ( marker ) with a coordinate equal to that of the center.
  • I create a variable ( TargetDate ) where the marker will move
  • I call the marker.animate animation method by telling the velocity of the displacement in milliseconds ( duration ) and a function that will be called upon reaching the coordinate -34.197, 150.644.
  • The following resources need to be referenced in the project (Jquery, GoogleMaps and MarkerAnimate):

    Note: In your case you will be capturing new coordinates all the time, let's say that every 20s, the above process will be executed several times and the animation method called each time a new position is captured.

    If you prefer to access my JSFiddle at: link

    PART 2

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

  • 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 at each Update to move them around the screen correctly.
  • Loading new coordinates are being simulated through an array I created in my hand. At every Update I get the next coordinate.
  • See that I set the animation time to last 5 seconds between each position and the GPS refresh time for every 10 seconds.
  • It works for one 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.
  • Removed the giant list of icons at the beginning because it does not influence the animation part in my tests.
  • In your case you will not even need to control nextPos and nextPosGPS because when you pull XML data they are already new data of new coordinates.

    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 without deep knowledge in JS strongly recommend that you take some time to break the head and adapt the code, with very little change it will be working with XML. Remember that you can not call the clearOverlay otherwise the problem of "blinking" the screen will continue to happen. The stream is:

    GPS coordinate handle > create bookmark > GPS coordinate handle > moves to new position > GPS coordinate handle > moves to a new position. And so it goes ..

        
    03.05.2016 / 21:18
    1

    Very simple:

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

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

    To do this, add two fields with: last update and the card. So you can identify the markers.

    In the updateMaps () routine, locate an existing marker using the board before you create it. If the board exists, simply update the position.

    Please let me know if you need more details.

        
    28.04.2016 / 05:46