Aziz
Aziz

Reputation: 1614

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

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.

Upvotes: 1

Views: 2702

Answers (1)

Jonathan Bates
Jonathan Bates

Reputation: 1835

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;}
}

Upvotes: 2

Related Questions