Reputation: 1329
I'm attempting to retrieve some data from my database to use in the GoogleMaps API but I'm not sure how to format it as GeoJson.
Currently, my code look like:
public IActionResult GetAll()
{
using (var connection = new SqlConnection(_config.GetConnectionString("MainDatabase")))
{
var results = connection.Query(
@"SELECT [Car] = car_no,
[Latitude] = lat,
[Longitude] = lng,
[Status] = status
FROM dbo.vehicles vh"
);
return Json(results);
}
}
However this returns it in a "plain" json format and I need to format it to return in a format similar to this:
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [102.0, 0.5]
},
"properties": {
"car": "15",
"status": "arrived"
}
}]
}
Upvotes: 0
Views: 119
Reputation: 11265
You could use json.net to create the custom JSON string based on you query result (as I don't know in which format Query
returns the data I assumed properties in the code example)
var features = new JArray();
foreach (var result in results)
{
features.Add(new JObject(
new JProperty("type", "Feature"),
new JProperty("geometry", new JObject(
new JProperty("type", "Point"),
new JProperty("coordinates", new JArray(
new JValue(result.Latitude),
new JValue(result.Longitude)
))
)),
new JProperty("properties", new JObject(
new JProperty("car", result.Car),
new JProperty("status", "arrived")
))
));
}
var jsonObject = new JObject
{
new JProperty("type", "FeatureCollection"),
new JProperty("features", features)
};
var json = jsonObject.ToString();
Upvotes: 1