Google Maps For Rails - updating markers via ajax only when search result changes

烈酒焚心 提交于 2019-12-08 02:28:25

Your problem lies in comparing both lists of markers to decide whether you should update or not.

The thing is, although _.isEqual(__oldmarkers, __markers) does perform a deep comparison, there might be things in Marker instances within your list that change even for identical points (an id, timestamps, ...).
Or perhaps it's simply because at the start, both __markers and __oldMarkers are null, thus equal, meaning you never get inside the ifblock.

Anyway, I think deep comparison here could become too costly. What I'd do instead, is compare things that are comparable easily, like the flat list of coordinates for each set of markers.

Something like this:

var __markers, __coordinates = [];
function resetMarkers(handler, json_array) 
{
  var coordinates = _.map(json_array, function(marker) {
    return String(marker.lat) + ',' + String(marker.lng);
  });

  if(_.isEqual(__coordinates.sort(), coordinates.sort()))
  {
    handler.removeMarkers(__markers);
    clearSidebar();
    clearZipcode();
    if (json_array.length > 0) 
    {
      __markers = handler.addMarkers(json_array);
      _.each(json_array, function(json, index){
        json.marker = __markers[index];
      });
      createSidebar(json_array);
    }
    __coordinates = coordinates;
  }
};

Here __coordinates and coordinates are just flat arrays of String, which should be compared quickly and give you the expected results.
In ordered to be compared using _.isEqual, both arrays are sorted beforehand.

NB: Old code used _.difference but that wasn't correct (see discussion in comments)
(Note that I'm using _.difference though, probably more costly than _.isEqual but with the bonus of being independent of the returned markers order.)

edit: Oh and of course you can stop sending that "oldHash" in the search query params now ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!