3

I am trying to create and load geoJSON data into Google Maps using the GeoJSON .NET library using ASP.NET MVC5 though I am doing something wrong somewhere.

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 is as follows:

@{
    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 Feature or FeatureCollection

If I go to my Action within the brower 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}"

1 Answer 1

3

A related 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 the JsonResult was also serializing the serialized data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.