简体   繁体   中英

gmaps4rails - update dynamically the markers from the database on the map without refresh the page

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?

<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.

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