我有一個ajax請求,它可以幫助我從Web服務器獲取JSON對象!如何在three.js中基於JSON對象創建網格
function _loadModel(filename) {
var request = new XMLHttpRequest();
request.open("GET", filename);//open(method, url, async)
request.onreadystatechange = function() {
console.info(request.readyState +' - '+request.status);
if (request.readyState == 4) {//4 == finished download
if(request.status == 200) { //OK -> bezogen auf http Spezifikation
handleLoadedGeometry(filename,JSON.parse(request.responseText));
}
else if (document.domain.length == 0 && request.status == 0){ //OK but local, no web server
handleLoadedGeometry(filename,JSON.parse(request.responseText));
}
else{
alert ('There was a problem loading the file :' + filename);
alert ('HTML error code: ' + request.status);
}
}
}
request.send();// send request to the server (used for GET)
}
_loadModel('http://localhost:8080/bbox?XMIN=3500060&YMIN=5392691&XMAX=3500277&YMAX=5393413')
JSON文件:
[{"building_nr": 5, "geometry": "{\"type\":\"Polygon\",\"coordinates\":[[[3500267.16,5392933.95,456.904],[3500259.19,5392933.01,456.904],[3500258.586,5392938.152,456.904],[3500258.02,5392942.97,456.904],[3500265.98,5392943.94,456.904],[3500266.552,5392939.097,456.904],[3500267.16,5392933.95,456.904]]]}", "polygon_typ": "BuildingGroundSurface"}, ...]
這是一個對象,我這個數組中有很多人。
現在我想創建一個網格! 我認爲這是可以的功能handleLoadedGeometry()
//Callback funktion
function handleLoadedGeometry(filename, model) {
var geom = new THREE.BufferGeometry();
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = model.geometry[i].coordinates[0];
vertex.y = model.geometry[i].coordinates[1];
vertex.z = model.geometry[i].coordinates[2];
geometry.vertices.push(vertex);
}
geom.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
var material = new THREE.MeshBasicMaterial({ color: 0xff00f0 });
var mesh = new THREE.Mesh(geom, material);
Scene.scene.add(mesh);
}
最後我在瀏覽器中出現此錯誤內部完成:無法讀取屬性「0」的未定義
我怎麼可以參考geometry coordinates
裏面的JSON
?
感謝您的評論!但現在我有一個問題,因爲model.geometry是一個很大的字符串在我的情況:幾何:「」{「類型」:「多邊形」,「座標」:[[[3500267.16,5392933.95,456.904],[3500259.19,5392933.01, 456.904],[3500258.586,5392938.152,456.904],[3500258.02,5392942.97,456.904],[3500265.98,5392943.94,456.904],[3500266.552,5392939.097,456.904],[3500267.16,5392933.95,456.904]]}}「如果我想要選擇model.geometry.ccordinates它是未知的,我只能選擇model.geometry。 – Moehre
然後嘗試另一個JSON.parse調用或JSON可能有錯誤 –