Gmaps4rails - dynamically update markers from a database on a map without refreshing a page

Hi, I am creating a Rails application to track a bus. I showed my markers very well from the database on my Google map in Rails 4 using 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 position of markers on the map without refreshing the page from the database?

+3
source share
1 answer
 <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, which worked for me.

+1
source

Source: https://habr.com/ru/post/1266536/


All Articles