0

我正在尝试读取一个简单的 json 数据文件。但我不断收到“未捕获的类型错误:无法读取未定义的属性 '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}]}
4

2 回答 2

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);

    // ...

  }
}
于 2012-11-12T08:50:58.447 回答
0

你应该有一些东西来表示你的循环结束。

for (var i = 0; i < 1; i++) {

除此之外,您唯一遇到的错误latlon小写

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);

}

​</p>

于 2012-11-12T03:38:06.380 回答