gmaps4rails - update dynamically the markers from

2019-05-08 05:54发布

问题:

Hello I building Live bus tracking Rails app. I displayed very well my markers from the database on my Google Map in Rails 4 with the gmaps4rails gem.

Controller:

@hash = Gmaps4rails.build_markers(@vehicle_trackings) do |track, marker|
      marker.lat track.latitude
      marker.lng track.longitude
      marker.picture({
        url: "/images/Bus Filled-30.png",
        width:  50,
        height: 50
     })
    end 

View:

<div id='map' style='width: 100%; height: 500px;'></div>
    <script>
        handler = Gmaps.build('Google');

            handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
                markers = handler.addMarkers(<%=raw @hash.to_json %>);
                handler.bounds.extendWith(markers);
                handler.fitMapToBounds();
            });
    </script>

Now how to update dynamically every 15 seconds the markers's position on the map without refresh the page from the database?

回答1:

<script>
    handler = Gmaps.build('Google');
        handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
           markers = handler.addMarkers(<%=raw @hash.to_json %>);
           handler.bounds.extendWith(markers);
           $( document ).ready(function() {         
            setInterval(function(){
                $(function () {
                    $.ajax({
                      type:"GET",
                      url:"/path_to_controller_action",
                      dataType:"json",
                      data: {some_id:1},
                      success:function(result){                     
                        for (var i = 0; i < markers.length; i++) {
                          markers[i].setMap(null);
                          handler.removeMarkers(markers);
                        }
                        markers = [];
                        markers = handler.addMarkers(result);
                        handler.bounds.extendWith(markers);                         
                      }
                    })
                });
               }, 10000);
            handler.fitMapToBounds();
            handler.getMap().setZoom(17);     
            });             
        });
</script>

replace the markers with x intervel using ajax thats worked for me.