我正在尝试构建一个Web应用程序,它通过ASHX Handler从SQL Server提取数据,转换为有效的GeoJSON格式,并在传单地图上显示标记。我有查询从SQLServer(Description,LAT,LONG)中提取三个字段。我能够在Leaflet中显示GeoJSON数据(来自网站文档)。我无法弄清楚的是如何成功构建GeoJSON数据。有没有一种使用Javascript Serializer构建GeoJSON对象的简单方法,或者它是我必须在hanlder中构建的进程。
以下是我想要创建的GeoJSON文件示例:
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"name": "Placemarker 1",
"marker-color": "#0000ff",
"marker-symbol": "airport"
},
"geometry": {
"type": "Point",
"coordinates": [
-77.12911152370515,
38.79930767201779
]
}
},
{
"type": "Feature",
"properties": {
"name": "Placemarker 2",
"marker-color": "#FF0000",
"marker-symbol": "hospital"
},
"geometry": {
"type": "Point",
"coordinates": [
-7.12911152370515,
5.79930767201779
]
}
}]
}
以下是我目前构建一个简单JSON文件的ASHX文件的内容:
private class DataSet
{
public string description { get; set; }
public double valueLat { get; set; }
public double valueLong { get; set; }
}
public void ProcessRequest(HttpContext context)
{
List<DataSet> listResults = new List<DataSet>();
int recordCount = 0;
try
{
// Get Connection String From WEB.CONFIG
string connStr = ConfigurationManager.ConnectionStrings["myConnStr"].ConnectionString;
// Connect And Get Data
OdbcConnection sqlConn = new OdbcConnection(connStr.ToString());
OdbcCommand sqlCmd = new OdbcCommand("{call getSampleData}", sqlConn);
sqlConn.Open();
OdbcDataReader rdr = sqlCmd.ExecuteReader();
while (rdr.Read())
{
DataSet results = new DataSet();
results.description = rdr["description"].ToString();
results.valueLat = Convert.ToDouble(rdr["lat"]);
results.valueLong = Convert.ToDouble(rdr["long"]);
listResults.Add(results);
recordCount++;
}
sqlConn.Close();
}
catch (OdbcException o)
{
context.Response.Write(o.Message.ToString());
}
var result = new
{
iTotalRecords = recordCount,
aaData = listResults
};
JavaScriptSerializer js = new JavaScriptSerializer();
context.Response.Write(js.Serialize(result));
}
答案 0 :(得分:2)
这可以帮助您从SQL Server https://blogs.msdn.microsoft.com/sqlserverstorageengine/2016/01/05/returning-spatial-data-in-geojson-format-part-1/
将数据转换为geoJson格式根据评论进行编辑:
你也可以在javascript中循环遍历“listResults”并手动构建你的geoJson
//listResults...this is dummy data,
//but an example of what you are currently getting from SQL
var listResults =
[{
description:"description 1",
valueLat: 39.8282,
valueLong: -98.5795
},{
description:"description 2",
valueLat: 38.8282,
valueLong: -97.5795
},{
description:"description 3",
valueLat: 37.8282,
valueLong: -96.5795
}];
//empty geoJson collection
var geoJsonData = [];
//loop through the listResults to build individual geoJson features
for (var i = 0; i < listResults.length; i++) {
var result = listResults[i];
geoJsonData.push(
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [result.valueLong, result.valueLat]
},
"properties": {
"description": result.description
}
}
);
}
构建geoJson集合后,可以使用传单来使用它。