Ajax call to get GeoJson data from ASP.NET MVC Controller

Viewed 7203

Using ASP.NET MVC 3 with C# I have a web page to display a map onto which I want to add a polyline consisting of several latitude and longitude coordinates. With the Leaflet JavaScript library you can add GeoJson layers. I want to get the longitude and latitude coordinates from a Database in C# and pass the list of coordinates to the JavaScript to create GeoJson or as GeoJson.

Here is an example of the GeoJson I wish to create:

var polyline = {
      "type": "Feature",
      "geometry": {
      "type": "LineString",
                    "coordinates": [
                        [-105.00341892242432, 39.75383843460583],
                        [-105.0008225440979, 39.751891803969535] …
                    ]
                },
      "properties": {
      "popupContent": "This is a polyline of many coordinates.",
      "underConstruction": false
      }
};

How can I create GeoJson similar to that shown above and add location data to the “coordinates” section from the C# or JavaScript and then use it in JavaScript to add a layer as such:

var myLayer = L.geoJson().addTo(map);
myLayer.addData(polyline);

I have started using GeoJSON.net and have come up with this code:

foreach (Position point in Positions)
{
    coordinates.Add(point);
}

GeoJSON.Net.Geometry.LineString line = new GeoJSON.Net.Geometry.LineString(coordinates);

JavaScriptSerializer serializer = new JavaScriptSerializer();

var data = serializer.Serialize(lineString);

But I do not know how to pass this GeoJSON LinseString object from the C# to the JavaScript. i was unable to pass it using Json as such:

return Json(data, JsonRequestBehavior.AllowGet);
2 Answers
Related