【发布时间】:2017-09-29 09:23:26
【问题描述】:
我开发了示例网页,可查看开放的街道地图并通过 Json (javascript) 从 sql server 数据库中读取数据
让我看到这个错误
leaflet.js:6 Uncaught TypeError: Cannot read property 'lat' of null
函数成功从数据库返回数据
模型文件
这里通过json返回数据
[HttpPost]
public JsonResult GetMap()
{
var data1 = (from p in db.Map
select new
{
Name = p.Name,
Latitude = p.Latitude,
Logitude = p.Logitude,
Location = p.Location,
Description = p.Description,
Id = p.Id
}).ToList().Select(res => new Map
{
Name = res.Name,
Latitude = res.Latitude,
Logitude = res.Logitude,
Location = res.Location,
Description = res.Description,
Id = res.Id
});
return Json(data1, JsonRequestBehavior.AllowGet);
}
查看文件
这里从json函数中获取数据并成功获取数据
<body>
<div id="mapid" style="height:600px"></div>
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
var map = L.map('mapid').setView([31.291340, 34.244190], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
$.ajax({
type: "POST",
url: '/Maps/GetMap',
success: function (data) {
//var result = JSON.stringify(data);
var result = data;
for (var i = 0; i < data.length; ++i) {
var popup =
'<b>Name:</b> ' + data[i].Name
+
'<br/><b>Latitude:</b> ' + data[i].Latitude +
'<br/><b>Longitude:</b> ' + data[i].Logitude +
'<br/><b>Location:</b> ' + data[i].Location
;
alert(data[i].Name + " " + data[i].Latitude + " / " + data[i].Logitude + " / " + data[i].Location);
L.marker(data[i].Logitude, [data[i].Latitude])
.bindPopup(popup)
.addTo(map);
}
},
error: function (xhr) {
console.log(xhr.responseText);
alert("Error has occurred..");
}
});
});
</script>
【问题讨论】:
-
var data1 = (from p in db.Map ...).ToList()=> 首先将查询内容具体化为IEnumerable。
标签: javascript json asp.net-mvc