我正在尝试阅读一个简单的json数据文件。但我一直得到" Uncaught TypeError:无法读取属性' lat'未定义" 错误。我不确定为什么。我尝试过多次尝试更改json文件的结构,但无济于事。任何协助都会受到欢迎。
for (var i = 0; i < 1000; i++) {
var dataCoal = data.coal[i];
// Creating a random position
var latLng = new google.maps.LatLng(dataCoal.lat,dataCoal.lon);
//Uncaught TypeError: Cannot read property 'lat' of undefined
// Creating a marker. Note that we don't add it to the map
var marker = new google.maps.Marker({
position: latLng
});
// Adding the marker to the markers array
markers.push(marker);
}
这是JSON文件中的一个条目
var data = { "coal": [{"NAME":"Haju Coal","Metals":"Coal","Lat":-0.11667,"Lon":114.85,"Accuracy":"approximate","DevStage":"Preproduction","ActStatus":"Temporarily On Hold","Company":"BHP Billiton Group","InSitu":700,"Metals_ft_style":0,"Accuracy_ft_style":0,"DevStage_ft_style":0,"ActStatus_ft_style":0}]}
答案 0 :(得分:0)
你应该有一些东西来表示你的循环结束。
for (var i = 0; i < 1; i++) {
除此之外,您唯一有错误的是lat
和lon
小写
var latLng = new google.maps.LatLng(dataCoal.Lat,dataCoal.Lon);
应该做的伎俩
所以看起来应该是
var data = { "coal": [{"NAME":"Haju Coal","Metals":"Coal","Lat":-0.11667,"Lon":114.85,"Accuracy":"approximate","DevStage":"Preproduction","ActStatus":"Temporarily On Hold","Company":"BHP Billiton Group","InSitu":700,"Metals_ft_style":0,"Accuracy_ft_style":0,"DevStage_ft_style":0,"ActStatus_ft_style":0}]}
for (var i = 0; data.length < 1000; i++) {
var dataCoal = data.coal[i];
// Creating a random position
var latLng = new google.maps.LatLng(dataCoal.Lat, dataCoal.Lon);
//Uncaught TypeError: Cannot read property 'lat' of undefined
// Creating a marker. Note that we don't add it to the map
var marker = new google.maps.Marker({
position: latLng
});
// Adding the marker to the markers array
markers.push(marker);
}
答案 1 :(得分:0)
我认为最好的方法是像PHP中的foreach一样迭代data.coal:
var coal;
for (var index in data.coal) {
if (data.coal.hasOwnProperty(index)) {
coal = data.coal[index];
var latLng = new google.maps.LatLng(coal.Lat, coal.Lon);
// ...
}
}