用谷歌地图和c# .net创建动态折线

本文关键字:创建 动态 折线 net 谷歌地图 | 更新日期: 2023-09-27 18:13:11

我想把VIEWBAG中的值作为c#模型中的LatLons数组传递。我不知道如何动态循环Viewbag数组和添加这些坐标到我的javascript数组传递到:

    // Create an instance of Google map
var map = new GMap2(document.getElementById("map"));
// Tell the map where to start
map.setCenter(new GLatLng(59.3324, 17.8857), 9);
// Create an array with points
var points = [
   new GLatLng(59.6919, 17.8582),
   new GLatLng(59.3030, 18.0395),
   new GLatLng(58.9789, 17.5341)
];
// Create a new polyline
var polyline = new GPolyline(points, '#ff0000', 5, 0.7);
// Add the polyline to the map using map.addOverlay()
map.addOverlay(polyline);

我想做类似于上面的事情,但是没有静态数组。

提前感谢!

编辑:

目前我有:

       var points = [];

   @foreach (var item in ViewBag.LatLons)
   {
     <text>
     points.push(new GLatLng(@item.Latitude, @item.Longitude);
     </text>
   }

但谷歌地图将不显示当这是添加,但是点是正确的迭代通过viewbag数据

用谷歌地图和c# .net创建动态折线

如果您要使用视图模型,则可以使用以下内容代替ViewBag:

// Create an array with points
var points = [];
<% foreach (var item in Model.Coords)
   {%>
       points.push(new GLatLng(<%= item.lat %>, <%= item.lng %>));
   <%} %>

应该输出到你的视图如下:

var points = [];
points.push(new GLatLng(59.6919, 17.8582));
points.push(new GLatLng(59.3030, 18.0395));
points.push(new GLatLng(58.9789, 17.5341));
//...et cetera

视图数据本质上是一个对象,不支持迭代器,因此必须强制类型转换。通过使用类型化集合,这就省去了视图中强制类型转换的需要。本例可以使用如下的简单模型:

public class CoordsModel 
{
    public List<CoOrd> Coords {get; set;}
}
public class CoOrd 
{
    public decimal lat {get; set;}
    public decimal lng {get; set;}
}