How to Make Icone Ride in the Google Maps api

Asked

Viewed 2,168 times

21

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

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

inserir a descrição da imagem aqui

As I don’t understand javascript I’m asking for this little 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>

3 answers

11

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 you have difficulty let me know that I make an example with your code.

  • 1

    André Very Cool this was just... only I’m not knowing how to deploy in this my script giving error. could make an example?

  • Fabio, could post the error?

  • Ola André is no mistake just doesn’t work

5

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

Google maps com marcador animado

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 as zoom, the center with the above coordinate and the map type.
  3. The map is created: new google.maps.Map
  4. I create a new marker(Marker) with a coordinate equal to the center.
  5. I create a variable(position) where the marker will move
  6. I call the animation method Marker.Animate informing the displacement speed in milliseconds(Duration) and a function that will be called when arriving at coordinate -34.197, 150.644.

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

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

If you prefer to 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 your XML because the logic would get complicated for me to create php and load the information, the concept is the same blz? I made it simple to load data, you’ll have to break your head a little bit and learn a little Javascript hehehe. Anyway, here’s what’s 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 every Update to move them around the screen correctly.
  2. The loading of new coordinates are being simulated through an array I created in hand. At each Update I get the next coordinate.

inserir a descrição da imagem aqui

  1. Note that I’ve set the animation time to last 5 seconds between each position and the GPS update time for every 10 seconds.
  2. It works for a bookmark and will work for the 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 in the beginning because it doesn’t influence the animation part in my tests.
  4. In your case you won’t even need to control the nextPos and nextPosGPS because when you pull the 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 not having in-depth knowledge in JS I strongly recommend that you take time to break your head and adapt the code, with very little change it will be working with XML. Remember you can’t call clearOverlay otherwise the problem of "blinking" the screen will keep happening. The flow is:

GPS coordinate handle > create marker > GPS coordinate handle > move to new position > GPS coordinate handle > move to new position. And so on and so on..

  • Ola Rodrigo... I tried to implant in my code more gave error... the map disappears, I do not have much notion of javascript.

  • And this script works with multiple vehicles, it works fine, but it keeps the vehicles flashing with each update. if you can help me to implant in this my script above will help me a lot....

  • I’ll try your script and see what I can

  • meu xml---> <gps>&#xA;<gps lat="" longi="" id_motorista="0" p_nome="" img="" speed="" frase="" id_saida="0" data="" placa="" fotom=""/>&#xA;<gps lat="-22.7097683333" longi="-42.6261733333" id_motorista="0" p_nome="" img="" speed="001.7" frase="" id_saida="0" data="" placa="" fotom=""/>&#xA;<gps lat="-22.9849211" longi="-43.1914952" id_motorista="124" p_nome="" img="" speed="0" frase="" id_saida="352" data="" placa="" fotom=""/>&#xA;<gps lat="-22.9172516667" longi="-43.0946033333" id_motorista="138" p_nome="" img="" speed="045.1" frase="A caminho" id_saida="349" data="" plate="" fotom=""/> </gps>

1

Very simple:

The updateMaps() routine is calling clearOverlays() that cleans all markers. So every 30 seconds they disappear and reappear.

Just exclude markers that have not had change at a certain 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 Marketer using the board before creating. If there is a card just update the position.

Let me know if you need more details.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.