2011-11-03 47 views
1

我想从VIEWBAG中传递值作为我在C#中的模型中的LatLons数组。我不知道如何动态循环的Viewbag阵列和这些cordinates添加到我的JavaScript数组传递到:用Google Maps和C#创建一个动态多段线.net

// 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数据迭代通过。

+0

这行: points.push(新的GLatLng(@ item.Latitude,@ item.Longitude); 应该是: points.push(新的GLatLng( @ item.Latitude,@ item.Longitude)); –

回答

2

取而代之的是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;} 
} 
+0

问题是我已经在使用这个视图的模型,它与坐标模型不同 - 因此我需要在ViewBag中传递控制器中的数据。想出这样的:VAR firstLoc; 变种secLoc; VAR点= []; @foreach(在ViewBag.LatLons VAR项) { points.push(new GLatLng(@ item.Latitude,@ item.Longitude); } ------------但它没有运行谷歌地图,如果我包括这个 - 但它遍历Lattable数据从列表中查看... – Aziz

+0

它是否抛出一个javascript错误?在您提供的评论中,您在for循环中发出的脚本行中缺少右括号。 –

+0

问题是,是有一个缺失的括号,但我也打电话错误的方法应该是:points.push(新google.maps.LatLng(parseFloat(@ Html.Raw(item.Latitude +“”)) ,parseFloat(@ Html.Raw(item.Longitude +“”)))); – Aziz