简体   繁体   中英

Updating google map markers without reloading map and blinking

I am doing a project where I should create a web page that shows Google map with the markers at the specified GPS coordinates. The project is organized in the following way. At the server side, I have the php script that accepts HTTP request from a GPS device, receives and stores GPS coordinates in the corresponding .txt file. The php file also includes javascript/jquery code that reads the .txt file with the GPS coordinates, create new instance of Google map and put the markers on map for the user that make request in a web browser. As I am electronic hardware engineer, this is pretty new for me. The code I found reloads the map on every 5 second, but that makes the map flashing/blinking for a while on each reload. Also, if I change the zooming manually in the browser, it resets to default on each map reload. Is there any way to avoid map blinking, and update markers smoothly. In the following is the snippet of the javascript/jquery code I have.

function initialize()
    {
        mapProp = {
          center:myCenter,
          zoom:17,
          mapTypeId:google.maps.MapTypeId.ROADMAP
          };
        setInterval('mark()',5000);
    }

    function mark()
    {
            map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
        var file = "gps.txt";
        $.ajaxSetup({cache: false});
                $.get(file, function(txt) { 
            var lines = txt.split("\n");

            for (var i=0;i<lines.length;i++){
                console.log(lines[i]);
                var words=lines[i].split(",");
                if ((words[0]!="")&&(words[1]!=""))
                {
                    marker=new google.maps.Marker({
                          position:new google.maps.LatLng(words[0],words[1]),
                          });
                    marker.setMap(map);
                    map.setCenter(new google.maps.LatLng(words[0],words[1]));
                    map.addMarker(new MarkerOptions().position(entry.getValue()).title(entry.getKey()));
                }
            }
            lastLength = lines.length;
            marker.setAnimation(google.maps.Animation.BOUNCE);
        });

    }

    google.maps.event.addDomListener(window, 'load', initialize);

What is going on

You keep recreating the map on every update rather than creating it once and add new markers to it.

Fixed code, with comments:

function initialize() {

   // map starting point
   var myCenter = new google.maps.LatLng(0, 0);

   // coordinates file
   var file = "gps.txt";

   // init and keep a reference to last line of coordinates
   var lastLength = 0;

   // init and keep reference to last set marker
   var marker;

   // map options
   var mapProp = {
      center:myCenter,
      zoom:17,
      mapTypeId:google.maps.MapTypeId.ROADMAP
   };

   // create map
   var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

   // execute once
   mark();

   // set update
   setInterval(mark, 5000);

   // this runs on schedule to add new markers
   function mark() {

      $.ajaxSetup({cache:false});

      $.get(file, function(txt) {

         var lines = txt.split("\n");

         // disable animation on last marker from previous update
         if(marker) {
            marker.setAnimation(null);
         }

         // start from last line + 1 from previous update
         for(var i=lastLength; i<lines.length; ++i) {

            // some debug
            //console.log(lastLength);
            //console.log(lines[i]);

            var words=lines[i].split(",");

            if(words[0] != "" && words[1] != "") {

               // new marker
               marker = new google.maps.Marker({
                  position:new google.maps.LatLng(words[0],words[1]),
               });

               // put marker on map
               marker.setMap(map);

               // center on marker
               map.setCenter(new google.maps.LatLng(words[0],words[1]));

               // I don't know the api enough to fix this part although it seems to work without it
               //map.addMarker(new MarkerOptions().position(entry.getValue()).title(entry.getKey()));
            }
         }

         // update list starting position
         lastLength = lines.length;

         //set animation on current last marker
         marker.setAnimation(google.maps.Animation.BOUNCE);
      }, 'text'); // added datatype:text
   }
}

// init
google.maps.event.addDomListener(window, 'load', initialize);

remove this line to get rid of bouncing issue.

marker.setAnimation(google.maps.Animation.BOUNCE);

While you are plotting the markers hold them in an array

marker[j]=new google.maps.Marker({position:new google.maps.LatLng(words[0],words[1])});

and later only add new ones to the map or remove all old one by

marker[j].setMap(null);

and then plot all markers afresh.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM