简体   繁体   English

如何刷新谷歌标记的经度和纬度?

[英]How to refresh latitude and longitude of google markers?

I have Trucks table in SQL.My Trucks send Lat and Lng to SQL every 10 seconds like this table 我在SQL中有Trucks表。我的Trucks每隔10秒向SQL发送Lat和Lng到此表

 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. 我通过使用JSON.Parse从SQL获取数据在Google地图上创建了标记,但是我想刷新标记并将其在地图上移动(不像按F5那样带有计时器或超时)。我不知道如何使用计时器或这些代码中的超时。

Source codes : http://www.aspdotnet-suresh.com/2013/05/aspnet-show-multiple-markers-on-google.html 源代码: 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# 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);

    }

    }

    }

The typical approach here would be to have your JavaScript periodically poll some JSON API on your server every N seconds for updated locations. 这里的典型方法是让JavaScript每N秒定期轮询服务器上的一些JSON API以获取更新的位置。 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. JavaScript轮询通常通过XHR(XMLHttpRequest)或AJAX完成。

The JavaScript code could loosely resemble: JavaScript代码可能大致类似于:

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. 请注意,Google Maps API v3无法查询地图画布上的标记。 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. 您使用window.setTimeout每N毫秒调用一次函数。 Similar to recursion, the function called by setTimeout queues a new timeout back to itself when complete. 与递归类似,由setTimeout调用的函数在完成时会将新的超时排队回到自身。

A more sophisticated method would be to push change events in location to the browser using WebSockets, although this requires more advanced skills. 一种更复杂的方法是使用WebSocket将更改事件的位置推送到浏览器,尽管这需要更高级的技能。 And you need Windows Server 2012 to support WebSockets. 并且您需要Windows Server 2012支持WebSockets。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过经度和纬度以编程方式显示Google地图 - How to display Google map programatically by Longitude and Latitude 在Google地图上显示多个标记,这些标记具有从C#中的SQL Server数据库检索到的纬度和经度值 - Displaying multiple markers on google maps with latitude and longitude values retrieved from a SQL Server database in C# 如何在C#中将经度/纬度和缩放级别转换为Google坐标? - How to convert Longitude/ Latitude and zoom level to Google coordinates in C#? 如何对经纬度坐标进行插值 - How to interpolate latitude and longitude coordinates 如何在Android Google Map V2上放置标记/绘制经度和​​纬度 - How to place marker/ plot Longitude and latitude on android google map v2 零缩放比例的像素在Google地图中代表多少经度和纬度? - How much longitude and latitude does a pixel represent in Google Maps with zero zoom? 如何使用经度和纬度坐标发送电子邮件,或者使用C#发送Google静态地图 - How to send an Email with longitude and latitude coordinates or maybe send a Google static map using c# 如何在c#中使用webBrowser控件来获取用户谷歌的经纬度? - How to use webBrowser control in c# to get user google latitude and longitude? 如何在 c# 中动态地将多个纬度和经度传递给谷歌距离矩阵 api? - how to dynamically pass multiple latitude and longitude to google distance matrix api in c#? 如何使用sql数据库中的经度和纬度在Google地图上显示图像? - how to display image on google map using latitude and longitude from sql database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM