简体   繁体   中英

How to remove Google Map Markers without blinking?

I am trying to populate multiple markers via ajax request on 5 sec interval. Every thing is working fine, but markers blinks on each interval call.

I am clearing all markers & regenerating again on each interval call. I just want to re-generate markers without blinking.

Also, it's possible that ajax request can return different result set on each interval call.

Following is the code:

  var map;
  var places;
  var markers = [];
  var iw_map;
  var markers_map = new Array();

  function initialize() {
      geocoder = new google.maps.Geocoder();

      var latlngCenter = new google.maps.LatLng(25.1999721, 66.8354386);
      iw_map = new google.maps.InfoWindow();
      var mapOptions = {
          center: latlngCenter,
          zoom: 7,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
      fetchPlaces();
      fitMapToBounds_map();
  }

  function fetchPlaces(cityId = null, hubId = null, riderId = null) {
    clearMarkers(); 
    $.ajax({
      url: '{{ route('get-markers') }}',
      method:'POST',
      data: {'city_id': cityId, hub_id: hubId, rider_id: riderId},
      dataType: 'json',
      cache: false,
      success: function(data) {

          // console.log(markers);

          var markerz = data.markers;

          // clearMarkers();

          $.each(markerz, function (i, dt) {

            var marker_icon = {url: dt.icon};
            var position = new google.maps.LatLng(dt.lat,dt.lng);
            var marker = new google.maps.Marker({
              map: map,
              position: position,
              icon: marker_icon
            });

            // newcoordinate = new google.maps.LatLng(dt.lat,dt.lng);

            google.maps.event.addListener(marker, "click", function(event) { 
              $.ajax({  
                  url: '{{ route('get-marker-info') }}',
                  method:'POST',
                  data: JSON.parse(dt.params),
                  success: function(data) {  
                      iw_map.setContent(data.infoBox);  
                      iw_map.open(map, marker);  
                  }  
              });
            });
            markers.push(marker.getPosition());
            markers_map.push(marker);
          });

          // fitMapToBounds_map();
      }  
    });

  }

  function fitMapToBounds_map() {
      var bounds = new google.maps.LatLngBounds();
      if (markers.length>0) {
          for (var i=0; i<markers.length; i++) {
              console.log(markers[i]);
              bounds.extend(markers[i]);
          }
          map.fitBounds(bounds);
      }
  } 

  function clearMarkers() {

    for (var i = 0; i < markers_map.length; i++) {
      markers_map[i].setMap(null);
    }

    markers_map = [];
  }

  function loadScript_map() {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "http://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false&v=3&libraries=places&callback=initialize";
      document.body.appendChild(script);
  }
  window.onload = loadScript_map;

  setInterval(fetchPlaces, 5000);

This is untested code so it might need a few adjustments.

I renamed your variables with meaningful names and changed the logic to first add the new markers, then remove the old markers.

When you get your markers with AJAX, first empty the new_markers array, then plot the markers on the map, and add them to the new_markers array. Then clear the old markers from the map ( markers array). The first time, this array will be empty so nothing will happen. Copy new_markers array to markers array. Repeat.

Here is the code:

var map;
var places;
var markers_positions = [];
var markers = [];
var new_markers = [];
var iw_map;


function initialize() {
  geocoder = new google.maps.Geocoder();

  var latlngCenter = new google.maps.LatLng(25.1999721, 66.8354386);
  iw_map = new google.maps.InfoWindow();
  var mapOptions = {
    center: latlngCenter,
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  fetchPlaces();
  fitMapToBounds_map();
}

function fetchPlaces(cityId = null, hubId = null, riderId = null) {

  new_markers = [];

  $.ajax({
    url: '{{ route('get-markers') }}',
    method: 'POST',
    data: {
      city_id: cityId,
      hub_id: hubId,
      rider_id: riderId
    },
    dataType: 'json',
    cache: false,
    success: function(data) {

      $.each(data.markers, function(i, dt) {

        var marker_icon = {
          url: dt.icon
        };
        var position = new google.maps.LatLng(dt.lat, dt.lng);
        var marker = new google.maps.Marker({
          map: map,
          position: position,
          icon: marker_icon
        });

        google.maps.event.addListener(marker, "click", function(event) {
          $.ajax({
            url: '{{ route('get-marker-info') }}',
            method: 'POST',
            data: JSON.parse(dt.params),
            success: function(data) {
              iw_map.setContent(data.infoBox);
              iw_map.open(map, marker);
            }
          });
        });
        markers_positions.push(marker.getPosition());
        new_markers.push(marker);
        clearMarkers();
      });
    }
  });

}

function fitMapToBounds_map() {
  var bounds = new google.maps.LatLngBounds();

  for (var i = 0; i < markers_positions.length; i++) {
    console.log(markers_positions[i]);
    bounds.extend(markers_positions[i]);
  }
  map.fitBounds(bounds);
}

function clearMarkers() {

  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }

  markers = new_markers;
}

function loadScript_map() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false&v=3&libraries=places&callback=initialize";
  document.body.appendChild(script);
}
window.onload = loadScript_map;

setInterval(fetchPlaces, 5000);

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