GeoJSON.NET with Google Maps in ASP.NET MVC
I am trying to create and load geoJSON data in Google Maps using GeoJSON.NET library using ASP.NET MVC5, although I am doing something wrong.
Using the example code posted on the GitHub site, my controller looks like this:
public ActionResult GetGeoJson()
{
    var point = new GeoJSON.Net.Geometry.Point(
                    new GeoJSON.Net.Geometry.GeographicPosition(45.79012, 15.94107));
    var featureProperties = new Dictionary<string, object> { {"Name", "Foo"} };
    var model = new GeoJSON.Net.Feature.Feature(point, featureProperties);
    var serializedData = JsonConvert.SerializeObject(model, Formatting.Indented,
               new JsonSerializerSettings
               {
                   ContractResolver = new CamelCasePropertyNamesContractResolver(),
                   NullValueHandling = NullValueHandling.Ignore 
               });
    return Json(serializedData, JsonRequestBehavior.AllowGet);
}
      
        
        
        
      
    
And my view looks like this:
@{
    ViewBag.Title = "Map";
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=foobar"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    function initialize() {
        var centerPoint = new google.maps.LatLng(53.710921, -1.626776);
        var mapOptions = {
            center: centerPoint,
            zoom: 12
        };
        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        map.data.loadGeoJson('/Home/GetGeoJson');
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas">
</div>
      
        
        
        
      
    
When I load the page and check the console in chrome I have the following error:
Uncaught InvalidValueError: not a function or FeatureCollection
If I go to my browser action, it outputs the following:
"{\r\n  \"geometry\":
{\r\n    \"coordinates\": [\r\n      15.94107,\r\n      45.79012\r\n    ],
\r\n    \"type\": \"Point\"\r\n  },
\r\n  \"properties\": {\r\n    \"name\": \"Foo\"\r\n  },
\r\n  \"type\": \"Feature\"\r\n}"
      
        
        
        
      
     
+3 
mheptinstall 
source
to share
      
1 answer
      
        
        
        
      
    
The linked SO question gave me the answer. I needed to change the return in my controller from
return Json(serializedData, JsonRequestBehavior.AllowGet);
      
        
        
        
      
    
to
return Content(serializedData, "application/json");
      
        
        
        
      
    
as JsonResult also serialized the serialized data.
+3 
mheptinstall 
source
to share