我的json文件看起来像这样
{"level" :[
{"color" : "#FF6600", "Polygon" : [
{"lon" : 125.8575930951375,"latt": 36.95626849495004},
{"lon" : 125.8851548404469,"latt": 36.99677151742446},
{"lon" : 125.9128154107602,"latt": 37.03743133552931},
{"lon" : 125.9564137105485,"latt": 37.07788492352393},]},
{"color" : "#FFFF00", "Polygon" : [
{"lon" : 125.8575930951375,"latt": 36.95626849495004},
{"lon" : 125.8851548404469,"latt": 36.99677151742446},
{"lon" : 125.9128154107602,"latt": 37.03743133552931},
{"lon" : 125.9564137105485,"latt": 37.07788492352393},]},
]}
如果我在我的html中为上面的json格式声明一个变量,那么我设法使用以下代码操作数据
var dataObj = {"level" :[
{"color" : "#FF6600", "Polygon" : [
{"lon" : 125.8575930951375,"latt": 36.95626849495004},
{"lon" : 125.8851548404469,"latt": 36.99677151742446},
{"lon" : 125.9128154107602,"latt": 37.03743133552931},
{"lon" : 125.9564137105485,"latt": 37.07788492352393},]},
{"color" : "#FFFF00", "Polygon" : [
{"lon" : 125.8575930951375,"latt": 36.95626849495004},
{"lon" : 125.8851548404469,"latt": 36.99677151742446},
{"lon" : 125.9128154107602,"latt": 37.03743133552931},
{"lon" : 125.9564137105485,"latt": 37.07788492352393},]},
]}
function UseJSON(){
for (i = 0; i < dataObj.level.length; i++)
{
var polygon = [];
for (j = 0; j < dataObj.level[i].Polygon.length; j++)
{
var point = map.getTransformXY(dataObj.level[i].Polygon[j].lon, dataObj.level[i].Polygon[j].latt,"EPSG:4326","EPSG:900913");
polygon.push(new OpenLayers.Geometry.Point(point.x, point.y));
}
var style_polygon = {strokeColor: "#000000", strokeOpacity: 0.7, fillColor: dataObj.level[i].color, fillOpacity: 0.5, strokeWidth: 1};
var intensityPolygon = new vworld.Polygon(polygon, style_polygon);
map.vectorLayer.addFeatures([intensityPolygon]);
}
}
请参阅SO中的上一个答案:How to use json in html
我尝试按以下方式修改我的代码:
function UseJSON(){
$.getJSON('data.json', function(dataObj) {
for (i = 0; i < dataObj.level.length; i++)
{
var polygon = [];
for (j = 0; j < dataObj.level[i].Polygon.length; j++)
{
var point = map.getTransformXY(dataObj.level[i].Polygon[j].lon, dataObj.level[i].Polygon[j].latt,"EPSG:4326","EPSG:900913");
polygon.push(new OpenLayers.Geometry.Point(point.x, point.y));
}
var style_polygon = {strokeColor: "#000000", strokeOpacity: 0.7, fillColor: dataObj.level[i].color, fillOpacity: 0.5, strokeWidth: 0.5};
var intensityPolygon = new vworld.Polygon(polygon, style_polygon);
map.vectorLayer.addFeatures([intensityPolygon]);
}
});
}
但它似乎不起作用。因为它似乎没有从本地获取data.json文件。有什么想法吗?
谢谢