Creating a dynamic Polyline with Google Maps and C# .net

为君一笑 提交于 2019-12-24 06:46:06

问题


I want to pass values from the VIEWBAG as an array of LatLons from my Model in C#. I am not sure how to dynamically loop the Viewbag array and add these cordinates to my javascript array to pass to:

    // 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);

I want to do something like the above, but without the static array.

Thanks in advance!

EDIT:

currently I have:

       var points = [];


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

But the google map will not show up when this is added, However the points are correctly iterated through from the viewbag data.


回答1:


Instead of the ViewBag, if you were to use a view model, you could use something like the following:

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

which should output into your view as:

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

The view data is inherently an object and doesn't support an iterator, so you would have to cast. This saves the need for the cast in the view by having a typed collection. This example could use a simple model like this:

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

public class CoOrd 
{
    public decimal lat {get; set;}
    public decimal lng {get; set;}
}


来源:https://stackoverflow.com/questions/7997705/creating-a-dynamic-polyline-with-google-maps-and-c-sharp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!