Google Maps for Rails - update markers with AJAX

我怕爱的太早我们不能终老 提交于 2019-11-29 12:42:43

Why don't you just update the map with the new markers? Meaning, instead of re-rendering the whole map after each search, just update the markers on the existing map by removing all markers and adding the new ones.

I haven't verified the method, but I guess it should work and be more efficient:

Create a app/assets/javascript/map.js file. You can store your map-related functions there. Create a function to update your map's markers in this file:

map.js

(function() {
  /* __markers will hold a reference to all markers currently shown
     on the map, as GMaps4Rails won't do it for you.
     This won't pollute the global window object because we're nested
     in a "self-executed" anonymous function */
  var __markers;

  function updateMarkers(map, markersData) 
  {
    // Remove current markers
    map.removeMarkers(__markers);

    // Add each marker to the map according to received data
    __markers = _.map(markersData, function(markerJSON) {
      marker = map.addMarker(markerJSON);
      map.getMap().setZoom(4); // Not sure this should be in this iterator!

      _.extend(marker, markerJSON);

      marker.infowindow = new google.maps.InfoWindow({
        content: marker.infowindow
      });

      return marker;
    });

    map.bounds.extendWith(__markers);
    map.fitMapToBounds();
  };

  // "Publish" our method on window. You should probably have your own namespace
  window.updateMarkers = updateMarkers;
})();

This function can be used to initialize your map and to update it. As you will not (if my answer satisfies you) render the map twice, you can delete _google_map.erb and put its content back into search.html.erb, but using the function we've just created:

search.html.erb

    <div id="map" style='width: 100%; height: 700px;'>
</div>
  <!-- Beginning Google maps -->

<script type="text/javascript" id="map_script">
   $(document).ready(function() {
       mapHandler = Gmaps.build('Google');
       mapHandler.buildMap({ provider: {
           disableDefaultUI: true,
           mapTypeId: google.maps.MapTypeId.TERRAIN
         }, internal: {id: 'map'}
       }, function(){
         var markersData = <%= raw @hash.to_json %>;
         updateMarkers(mapHandler, markersData);
       });
   }); // Document ready
</script>

Please don't forget the var keyword when declaring variables, otherwise they will end up being globals, and that's bad ^^
Note that I have deliberately left mapHandler as a global variable: you will need access to your handler to update markers later when someone uses the search. This is probably not an ideal thing to do, but this question is not about refactoring your code so let's keep it this way.

So now my solution brings you a map that initializes with the given markers on page load. In other words, nothing has changed!

However you're now allowed to reuse this updateMarkers function to change the markers displayed on your map. That's what you search.js.erb script should do:

search.js.erb

(function() {
  var markersData = <%= raw @hash.to_json %>;
  updateMarkers(mapHandler, markersData);
})();

That's it! Hopefully it'll take you to the next step of your project :)

I tried the same thing but instead of updating the marker you should include the map in the partial/placeholder and then update it ...

for example, this is the view which is displaying the map...i will update this view/placeholder with latest map and markers

<div id="map_users_index">
<div id="map" class="map" style="height:relative;">
</div>

in users_controller.rb

   ##take index action or any other action 
    def index
    ##do your stuff and get more users
         respond_to do |format|
           format.html 
           format.js
         end
    end

in index.js.erb

##update the placeholder/partial with new map with new markers

$("#map_users_index").html("<%= escape_javascript(render(:partial => 'index')) %>");

I HAVE MY OWN WORKING CODE...HERE

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