Real-time Google Maps update

3

I'm using Google map to show objects in real time. I made a function in Javascript which is refreshed every 3 seconds and in that it updates those marked on the Google map.

Something like:

  vmarcador[value.Id] = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: "text " + value.Lon
            });
vmarcador[value.Id].setPosition(localidade_viatura_atualizado);

Okay, everything works, the problem is that my map seems to be reloaded every 3 seconds is different from that other site where only the object is moved.

link

The source of the link above is here .

But I can not understand the difference in it from my (the dele is much more complex)

My code, follows his example: link

Basically it is: (change the google map key to one of yours, this one will not work outside of jsbin.com

<script src="https://code.jquery.com/jquery-2.1.4.js"></script><scriptsrc="https://maps.googleapis.com/maps/api/js?key=AIzaSyBFL7XB2lwmJ-albxQgXFoGi4N7xwTO-sU" type="text/javascript"></script>

<div id="map_canvas" style="width:100%; height: 900px"></div>
<script>
 $(document).ready(function () {
            inicia_tempo_real("");
});

var total_viaturas_exibidas;
var map;
var vmarcador = [];
var janela_detalhes = [];
var vconta_vtrs_inicio = 0;
var vconta_vtrs_real_time = 0;
var ViaturaId;
var UrlRestPontos = "http://coi.wmb.com.br/monitoramento/JsonViaturasOnline";
var tempoRefresh = 5; //Seg

var triangleCoords;
var x = new google.maps.LatLng(-23.120520, -46.546923);

function inicia_tempo_real(VTRId) {
    ViaturaId = VTRId;

    var mapProp = {
        center: x,
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var infoWindow = new google.maps.InfoWindow();
    map = new google.maps.Map($('#map_canvas')[0], mapProp);

    clearInterval(vintervalo);
    vconta_vtrs_inicio = 0;

    // Recupera origem dos pontos..
    $.getJSON(UrlRestPontos + "?viaturaValor=" + ViaturaId, function (valores_recebidos) {
        $.each(valores_recebidos.pontos_recebidos, function (i, value) {
            var localidade_viatura_atualizado = new google.maps.LatLng(value.Lat, value.Log);

            vconta_vtrs_inicio++;
            var myLatlng = new google.maps.LatLng(value.Lat, value.Lon);
            janela_detalhes[value.Id] = new google.maps.InfoWindow({
                content:  "VTR:" + value.VTR,
            });
            vmarcador[value.Id] = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: "text " + value.Lon
            });
            vmarcador[value.Id].setPosition(localidade_viatura_atualizado);

            janela_detalhes[value.Id].open(map, vmarcador[value.Id]);

            google.maps.event.addListener
            (
            vmarcador[value.Id], 'click', function () {
                document.getElementById('IFRAMEMonitoramento').src = '/monitoramento/DetalhesVTRIframe?viaturaValor=' + value.ViaturaId;
                $('#myModal').modal();
            }
            );
        });
    });

   var vintervalo = setInterval(function () {
        atualiza()
    }, tempoRefresh * 1000);

 CarregaAtibaia();
}

function CarregaAtibaia() {
    var AreaAtibaia = [];
    $.ajax({
        type: "GET",
        url: "/scripts/coi/bordaAtibaia.json",
        dataType: "json",
        success: function (data) {
            AreaAtibaia = data;
            DesenhaAtibaia(AreaAtibaia);
        }
    });
}

function DesenhaAtibaia(varea_atibaia) {
    var AreaAtibaia = new google.maps.Polygon({
        paths: varea_atibaia,
        strokeColor: '#FF0000',
        strokeOpacity: 0.9,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.04
    });
    AreaAtibaia.setMap(map);
}
function atualiza() {
    if (vconta_vtrs_real_time != vconta_vtrs_inicio && vconta_vtrs_real_time > 0) {
        vconta_vtrs_real_time = vconta_vtrs_inicio;
      //  inicia_tempo_real();
    }

    vconta_vtrs_real_time = 0
    $("#viaturas_selecionadas").empty();
    $("#viaturas_selecionadas").append('<option value="0">Todas</option>');

    $.getJSON(UrlRestPontos + "?viaturaValor=" + ViaturaId, function (valores_recebidos) {
        $.each(valores_recebidos.pontos_recebidos, function (i, value) {
            var localidade_viatura_atualizado = new google.maps.LatLng(value.Lat, value.Log);
            var vvtrs;
            var vocorrencias;
            var vvalores_mostrar = "";

            vconta_vtrs_real_time++;


            $("#viaturas_selecionadas").append('<option value="' + value.ViaturaId + '">' + value.VTR + '</option>');

            vmarcador[value.Id].setPosition(localidade_viatura_atualizado);

            if (value.Situacao == 1) {
                vmarcador[value.Id].setIcon('http://coi.wmb.com.br/Content/img/viatura_busy.png')
            }
            else {
                vmarcador[value.Id].setIcon('http://coi.wmb.com.br/Content/img/viatura_free.png')
            }

            if ($("#exibir_vtr").is(":checked")) {
                vvalores_mostrar = "VTR:" + value.VTR;
            }

            if ($("#exibir_oco").is(":checked")) {
                if (vvalores_mostrar != "") {
                    vvalores_mostrar = vvalores_mostrar + "<br>OCO:" + value.CodigoOcorrencia;
                }
                else {
                    vvalores_mostrar = "OCO:" + value.CodigoOcorrencia;
                }
            }

            if ($("#exibir_vtr").is(":checked") || $("#exibir_oco").is(":checked")) {
                janela_detalhes[value.Id].open(map, vmarcador[value.Id]);
                janela_detalhes[value.Id].setContent(vvalores_mostrar);
            }
            else {
                janela_detalhes[value.Id].close();
            }
        });
    });
}
</script>

Is it my problem that I use setPosition

    
asked by anonymous 12.08.2016 / 20:22

2 answers

4

Save a reference to the created Marker and reuse it by updating the position via setPosition() method of that instance. Following example:

angular.module('myApp', []).
directive('myMap', function($timeout) {
  var link = function(scope, element, attrs) {

    var map, infoWindow;
    var markers = [];

    var currPos = { x: 50, y: 2 }; // <- Posição inicial
    var mapOptions = { center: new google.maps.LatLng(50, 2), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false };

    function initMap() { if (map === void 0) { map = new google.maps.Map(element[0], mapOptions); } }

    function setMarker(map, position, title, content) {
      var marker;
      var markerOptions = { position: position, map: map, title: title, icon: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png' };

      marker = new google.maps.Marker(markerOptions);
      scope.marker = marker;
      markers.push(marker);
    }

    initMap();

    setMarker(map, new google.maps.LatLng(51.508515, -0.125487), 'Londres', 'xxxxxxxxx');
    map.panTo(new google.maps.LatLng(51.508515, -0.125487));

    floatABit = function() {

      currPos.x = currPos.x + ((Math.random() * 50) - 25) / 50;
      currPos.y = currPos.y + ((Math.random() * 50) - 25) / 50;

      var ll = new google.maps.LatLng(currPos.x, currPos.y);

      scope.marker.setPosition(ll);
      map.panTo(ll); // Comente para interromper o panning automático.
      $timeout(floatABit, 500);
    };

    floatABit();

  };

  return {
    restrict: 'A',
    template: '<div id="gmaps"></div>',
    replace: true,
    link: link
  };
});
#gmaps {
  width: 100%;
  height: 400px;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>



<div ng-app="myApp">

  <div my-map=""></div>

</div>

Source: link , with changes.

    
01.09.2016 / 21:19
1

Good afternoon, this difference occurs because the site you submitted as an example does not use Google Maps, it uses the Open Street Map tool ( demo , API Wiki ). I already had this map problem reloading and I could not find a solution.

Returning to the use of Google Maps, I recommend that you do not use it for this purpose, as you can see in the Google Maps price list ( Asset Tracking Use Cases that seems to be your case, falls into the Premium plan. Last month I was notified by Google that I would have to pay for a Premium license, the price is around $ 15,000 per year (for 500,000 requests / year). I migrated my platform to OpenStreetMap and it works perfectly, I recommend the same.

    
12.08.2016 / 21:36