0

I have Trucks table in SQL.My Trucks send Lat and Lng to SQL every 10 seconds like this table

 dbo.Trucks

ID    readTime                      TruckID          Lat             Lng

1     2014-01-24  18:02:47.983        78             36,785          35,4672

2     2014-01-24  18:03:11.983        78             34,785          37,341

3     2014-01-24  18:03:45.541        78             31,785          34,242

.  

.

780   2014-01-24  22:42:45.541         .                .               .

I created markers on google map by get data from SQL using JSON.Parse.But I want to refresh markers and move them on maps.(not like press F5.With a timer or time out).I dont know how can I use timer or timeout in these codes.

Source codes : http://www.aspdotnet-suresh.com/2013/05/aspnet-show-multiple-markers-on-google.html

 <script type="text/javascript">

 function initialize() 

{

 var markers = JSON.parse('<%=OnlineTrucks() %>');

 var mapOptions = 

 {

    center: new google.maps.LatLng(markers[0].lat, markers[0].lng),

    zoom: 5,

    mapTypeId: google.maps.MapTypeId.ROADMAP


   };

var infoWindow = new google.maps.InfoWindow();

var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);


image = '/Images/truck.png';


     for (i = 0; i < markers.length; i++) {


    var data = markers[i]

    var myLatlng = new google.maps.LatLng(data.lat, data.lng);

    var marker = new google.maps.Marker({

    position: myLatlng,

    map: map,

   title: data.title,

   icon: image,

    });


  (function(marker, data) {


      google.maps.event.addListener(marker, "click", function(e) {

      infoWindow.setContent(data.description);

      infoWindow.open(map, marker);


         });

        })(marker, data);

          }


}


</script>
</head>

<body onload="initialize()">

 <form id="form1" runat="server">

 <div id="map_canvas" style="width: 500px; height: 400px"></div>

C#

public string OnlineTrucks() {

DataTable dt = new DataTable();

    using (SqlConnection con = new SqlConnection("Data 
Source=localhost;Initial Catalog=MyDB;Integrated Security=true"))
{   
    using (SqlCommand cmd = new SqlCommand("select 
title=TruckID,lat=Lat,lng=Lat from Trucks", con))
{

con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);

    System.Web.Script.Serialization.JavaScriptSerializer serializer = new 
System.Web.Script.Serialization.JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row;

    foreach (DataRow dr in dt.Rows)
    {

    row = new Dictionary<string, object>();

    foreach (DataColumn col in dt.Columns)

    {

    row.Add(col.ColumnName, dr[col]);

    }

    rows.Add(row);

    }

    return serializer.Serialize(rows);

    }

    }

    }
user3107343
  • 2,159
  • 6
  • 26
  • 37

1 Answers1

0

The typical approach here would be to have your JavaScript periodically poll some JSON API on your server every N seconds for updated locations. The simple way would be to download the complete set of markers on every poll. From here, you could optimize to only send the new locations of trucks that have moved. You could also send the northeast/southwest corners (bounds) of the map to filter the query down to the trucks that are visible in the current map viewport.

JavaScript polling is normally done via XHR (XMLHttpRequest) aka AJAX.

The JavaScript code could loosely resemble:

var delay = 10 * 1000 /* milliseconds per second */;
var markers = [];  // an array of google.maps.Marker instances

function poll() {
  var req = new XMLHttpRequest();
  req.open('GET', 'http://www.mozilla.org/', true);
  req.onreadystatechange = function (aEvt) {
  if (req.readyState == 4) {
    if(req.status == 200)
      redraw(req.responseText);
    else
      alert("Error loading data\n");
    }
    // queue the next polling request
    window.setTimeout(poll, delay);
  };
  req.send(null);
}

// start the polling queue
poll();

// handles updating any changed markers in the global markers array
function redraw(response) {
   var data = JSON.parse(response); 

   // assume data looks something like `[ {id: 1, latitude: 10, longitude: 20 } ]`
   data.forEach(function(item) {
     markers.some(function(marker) {
       if (marker.id === item.id) {
          marker.setPosition(new google.maps.LatLng(item.latitude, item.longitude));
          return true;
       }
     });
   });
 }

This code is nowhere near what a complete solution would look like, but, hopefully hits the major concepts. Note that the Google Maps API v3 doesn't have a way to query the markers on the map canvas. You have to maintain the collection of markers yourself via some variable (preferably not a global variable like above). You use window.setTimeout to call a function every N milliseconds. Similar to recursion, the function called by setTimeout queues a new timeout back to itself when complete.

A more sophisticated method would be to push change events in location to the browser using WebSockets, although this requires more advanced skills. And you need Windows Server 2012 to support WebSockets.

Steve Jansen
  • 9,398
  • 2
  • 29
  • 34