Real-time Google Maps Update

Asked

Viewed 2,116 times

3

I’m using the Google map to show objects in real time. I did a function in Javascript which is updated every 3 seconds and in this it updates the marked ones in 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 this other site where only the object is moved.

http://traintimes.org.uk/map/tube/

The source of the link above is here.

But I can’t understand the difference his to mine (the code his is much more complex)

My code, follow his example: http://jsbin.com/danequzala/edit?html,js,console

Basically it is: (change the google map key to your own, it won’t work outside of jsbin.com

<script src="https://code.jquery.com/jquery-2.1.4.js"></script> 
<script src="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 that my problem is that I use setPosition

2 answers

4


Keep a reference to Marker created and reuse it by updating the position via method setPosition() of that instance. Example below:

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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>



<div ng-app="myApp">

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

</div>

Source: https://jsfiddle.net/Xeoncross/k5c2ndyL/, with amendments.

  • In the link sent it does not update right? I’m by cell phone.

  • @Dorathoto by the link worked - maybe it would help to form a more complete answer if you made a functional jsfiddle available with your content.

  • show, this focus that the map is giving on the marker is possible to disable?

  • @Dorathoto Yes, that’s the line I identified with the comment // Comente para interromper o panning automático. Panning is the name of the effect.

1

Good afternoon, this difference occurs because the site that Voce sent example does not use Google Maps, uses the tool Open Street Map (demonstration, API wiki). I’ve had this problem with the map being reloaded and I couldn’t find a solution.

Returning to the use of Google Maps, I recommend you not to use it for this purpose, as you can see in the price list of Google Maps (link) Use cases of asset tracking that appears 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 a year (for 500,000 requests/year). I migrated my platform to Openstreetmap and works perfectly, I recommend the same.

  • I would like to use the Open Street Map, but in my city besides being very outdated most streets have no name. Making it impossible to use.

  • This is a big problem even for Openstreetmap, but Voce can use the Google API for the Geocode part and use Openstreet to plot the map. Works perfectly

  • I need the map with the street names... Look at Bing and it’s pretty outdated, it’s all street names, but a street that was created six months ago doesn’t exist yet.

  • 1

    Then use Google yourself, maybe you’re lucky and not notified. And maybe later the maps are updated and you get to use them .

Browser other questions tagged

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