【问题标题】:Creating a dynamic Polyline with Google Maps and C# .net使用 Google 地图和 C# .net 创建动态折线
【发布时间】:2011-11-03 15:41:21
【问题描述】:

我想将 VIEWBAG 中的值作为 LatLons 数组从我的 C# 模型中传递。我不确定如何动态循环 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数据中正确地迭代了点。

【问题讨论】:

  • 这一行:points.push(new GLatLng(@item.Latitude, @item.Longitude); 应该是:points.push(new GLatLng(@item.Latitude, @item.Longitude)) ;

标签: c# .net asp.net-mvc-3 google-maps-api-3


【解决方案1】:

如果您要使用视图模型,而不是 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;}
}

【讨论】:

  • 问题是我已经为这个视图使用了一个不同于坐标模型的模型——因此我需要在 ViewBag 中传递来自控制器的数据。我想出了这样的东西: var firstLoc;变种secLoc;变量点 = []; @foreach(ViewBag.LatLons 中的变量项){ points.push(new GLatLng(@item.Latitude, @item.Longitude); }------------ 但是如果我包含它,它不会运行谷歌地图 - 但是它会遍历视图包中的 LatLon 数据列表......
  • 它会抛出 javascript 错误吗?在您提供的评论中,您在 for 循环中发出的脚本行中缺少右括号。
  • 问题是,是的,缺少一个括号,但我也调用了错误的方法应该是:points.push(new google.maps.LatLng(parseFloat(@Html.Raw(item .Latitude + "")),parseFloat(@Html.Raw(item.Longitude + ""))));
猜你喜欢
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 2020-11-25
  • 2015-08-05
  • 2013-07-08
  • 2012-09-09
  • 2019-06-19
  • 1970-01-01
相关资源
最近更新 更多