Tech Cruize Tech Cruize - 4 months ago 84
C# Question

Create a geoJson object in C#

am trying to create a GeoJson FeatureCollection object by passing ONLY lat and long to a function where it instantiate Below PoCo.

namespace PoCo
{

public class LocalGeometry
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}

public class Properties
{
public string name { get; set; }
public string address { get; set; }
public string id { get; set; }
}

public class LocalFeature
{
public string type { get; set; }
public LocalGeometry geometry { get; set; }
public Properties properties { get; set; }
}

public class geoJson
{
public string type { get; set; }
public List<LocalFeature> features { get; set; }
}

}


This is how am creating object

var CorOrd = new LocalGeometry();
CorOrd.coordinates.Add(Lat);
CorOrd.coordinates.Add(Lang);
CorOrd.type = "Point";


var geoJson = new geoJson
{
type = "FeatureCollection",
features = new LocalFeature
{
type = "Feature",
geometry = CorOrd
}
};


But Am Getting Error

CS0029 Cannot implicitly convert type 'PoCo' to 'System.Collections.Generic.List<PoCo.Local>'.


Any Suggestions how do i create a GeoJson Object here.

Win Win
Answer

The following assignment is not valid -

features = new LocalFeature

It should be a List of LocalFeature -

features = new List<LocalFeature>
{
   new LocalFeature { type = "Feature", geometry = CorOrd}
}

In addition, you will need to instantiate a list before adding. Otherwise, it will throw NullReferenceException.

ar CorOrd = new LocalGeometry();
CorOrd.coordinates = new List<double>(); // <=====
CorOrd.coordinates.Add(Lat);
CorOrd.coordinates.Add(Lang);
CorOrd.type = "Point";