我们试图通过for循环创建一个json对象。结果应该是这样的:
posJSON = [
{
"position": [msg[0].Longitude, msg[0].Latitude],
"radius": 0.05,
"color": [255, 255, 0, 255]
},
{
"position": [msg[1].Longitude, msg[1].Latitude],
"radius": 0.05,
"color": [255, 0, 0, 255]
}
]
如果我们只是使用这个代码创建对象^一切正常,但是如果我们试图以这种方式创建对象:
for(i=0; i < Object.keys(msg).length; i++) {
posJSON.push({
"position": [msg[i].Longitude, msg[i].Latitude],
"radius": 0.05,
"color": [255, 255, 0, 255]
});
}
它不起作用。我们显然使用了错误的语法,但我们无法理解错误的位置。 提前感谢能够回答我们问题的任何人。
这是函数的完整代码:
import React, {Component} from 'react';
import DeckGL, {PathLayer} from 'deck.gl';
import DeckGL, {ScatterplotLayer} from 'deck.gl';
import $ from 'jquery';
var tableJSONStringed = null;
var posJSON = [];
//Position tracker
window.setInterval(function(){
var request = $.ajax({
url: "https://nedo93.000webhostapp.com/phpgetcoords.php",
method: "POST",
dataType: "json"
});
request.done(function( msg ) {
tableJSONStringed = JSON.stringify(msg, null, " ");
var count = Object.keys(msg).length;
//CYCLE
for(i=0; i < Object.keys(msg).length; i++) {
posJSON.push({
"position": [msg[i].Longitude, msg[i].Latitude],
"radius": 0.05,
"color": [255, 255, 0, 255]
});
/*posJSON = [
{
"position": [msg[0].Longitude, msg[0].Latitude],
"radius": 0.05,
"color": [255, 255, 0, 255]
},
{
"position": [msg[1].Longitude, msg[1].Latitude],
"radius": 0.05,
"color": [255, 0, 0, 255]
}
];*/
});
request.fail(function( jqXHR, textStatus ) {
//alert( "Request failed: " + textStatus );
});
}, 5000);
export default class DeckGLOverlay extends Component {
static get defaultViewport() {
return {
longitude: 11.25,
latitude: 43.77,
zoom: 16,
maxZoom: 18,
pitch: 40, //viewport tilt
bearing: 0
};
}
_initialize(gl) {
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
}
//Add in const { }, new layers's ID
render() {
const {viewport, scatters, pos, icon, paths, trailLength, time} = this.props;
//Add another instance of a new layer here:
const layers = [
new ScatterplotLayer({
id: 'scatters',
data: scatters,
radiusScale: 100,
outline: false
}),
new ScatterplotLayer({
id: 'pos',
data: posJSON,
radiusScale: 100,
outline: false
}),
new PathLayer({
id: 'paths',
data: paths,
rounded: true,
getColor: paths => [255, 0, 0, 255],
getWidth: paths => 0.03,
widthScale: 100
})
];
return (
<DeckGL {...viewport} layers={layers} onWebGLInitialized={this._initialize} />
);
}
}
这里是运行for循环的控制台输出:Image
答案 0 :(得分:0)
var posJSON = [];
var msg = [
{Longitude: 1, Latitude:11, radius: 0.01, color: [221,2,32,1]},
{Longitude: 2, Latitude:21, radius: 0.11, color: [321,2,23,1]},
{Longitude: 3, Latitude:31, radius: 0.41, color: [521,2,22,1]},
{Longitude: 4, Latitude:41, radius: 0.11, color: [121,2,02,1]},
{Longitude: 5, Latitude:51, radius: 0.32, color: [253,2,22,1]},
]
msg.forEach(function(obj) {
posJSON.push({
"position": [obj.Longitude, obj.Latitude],
"radius": obj.radius,
"color": obj.color
});
});
console.log(posJSON);