渲染Geojson非常不稳定

时间:2015-10-20 11:49:11

标签: json openlayers-3

从Openlayers-2.11转到ol3时,我遇到了一个奇怪的问题。从mysql数据库动态提取的geojson文件有时会被渲染,有时则不会。提取是通过PHP脚本完成的。请see this link获取实时示例。 我已通过几个在线json验证器运行该文件,但所有这些都提出了#34;有效的json"结果。由于geojson文件是动态的,我首先想到的是文件中可能隐藏了一些非法字符,但我找不到任何字符。 ol3实现很简单;

var image = new ol.style.Circle({
  radius: 5,
  fill: null,
  stroke: new ol.style.Stroke({color: 'red', width: 1})
});

var styles = {
 'Point': [new ol.style.Style({image: image})]
};

var styleFunction = function(feature, resolution) {
  return styles[feature.getGeometry().getType()];
};  

var vectorLayer = new ol.layer.Vector({
    source: new ol.source.GeoJSON({
                url: '../../../../yg/utils/retriveData.php',
                projection: 'EPSG:3857'
            }),
    style: styleFunction
});

我已经通过相同的代码运行其他静态json文件而没有麻烦。问题似乎只出现在这个动态文件中。

我可以请求在这种情况下可能是最好的调试策略的指导。

PHP脚本看起来像这样;

<?php
$conn = new mysqli("localhost", "xxxxxxxx", "1234", "xxxxx");

$sql = 'SET names utf8';

$rs = $conn->query($sql);

if (!$rs) {
  echo 'An SQL error occured.\n';
  exit;
}

$sql = 'SELECT * FROM extract_data';

# Try query or error
$rs = $conn->query($sql);
if (!$rs) {
   echo 'An SQL error occured.\n';
exit;
}

# Build GeoJSON feature collection array
$geojson = array(
   'type'      => 'FeatureCollection',
   'features'  => array()
);

# Loop through rows to build feature arrays
while ($row = $rs->fetch_array(MYSQLI_ASSOC)) {
   $properties = $row;
   # Remove x and y fields from properties (optional)
   unset($properties['lat']);
   unset($properties['lon']);
   $feature = array(
    'type' => 'Feature',
    'geometry' => array(
        'type' => 'Point',
        'coordinates' => array(
            $row['lon'],
            $row['lat']
        )
    ),
    'properties' => $properties
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}

header('Content-type: application/json');

echo json_encode($geojson, JSON_NUMERIC_CHECK);

$conn = NULL;
?>

1 个答案:

答案 0 :(得分:0)

可能与您的问题无关但我在您的代码中发现了错误

您没有正确调用styleFunction,而且您没有传递featureresolution个参数。

您可以尝试进行调试:

var styleFunction = function(feature, resolution) {
  return styles['Point']; //for debugging
};  

var vectorLayer = new ol.layer.Vector({
    source: new ol.source.GeoJSON({
                url: '../../../../yg/utils/retriveData.php',
                projection: 'EPSG:3857'
            }),
    style: styleFunction()
});

另外,从OL3 Documentation开始,您应该从geojson创建矢量图层,如下所示:

var vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
                url: '../../../../yg/utils/retriveData.php',
                format: new ol.format.GeoJSON(),
                projection: 'EPSG:3857'
            }),
    style: styleFunction()
});