1 回答
TA贡献1873条经验 获得超9个赞
由于您使用的是 PHP,因此解决此问题的方法是将所有生成 geojson 的代码放入一个不同的 PHP 文件中,例如一个get-features.php仅调用的文件:
<?php
$conn = new PDO(/* stuff*/);
$rs = $conn->query('SELECT *, x AS x, y AS y FROM GPS');
if (!$rs) { /* handle error */ }
$geojson = array ('type' => 'FeatureCollection','features' => array());
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;
unset($properties['x']);
unset($properties['y']);
$array_push($geojson['features'], array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array($row['x'],$row['y']) ),
'properties' => $properties )
);
}
header('Content-Type: text/json')
echo JSON_encode($geojson);
?>
然后,让您的 JS 每五秒重新请求该 PHP 文件的 URL,例如:
setInterval(function(){
fetch('https://my-web-server/get-features.php')
.then(function(response){ return response.json() })
.then(function(json){
/* Do something with the GeoJSON */
});
}, 5000);
或者在请求之间等待五秒的循环中请求该 URL ,以避免潜在的竞争条件:
function requestGeoJson(){
fetch('https://my-web-server/get-features.php')
.then(function(response){ return response.json() })
.then(function(json){
/* Do something with the GeoJSON */
setTimeout(requestGeoJson, 5000);
});
};
requestGeoJson();
这与 [ L.GeoJSON](( https://leafletjs.com/reference-1.5.0.html#geojson ) 有什么关系?天真的方法是clearLayers()和addData(),例如:
// create an empty L.GeoJSON layer
var geoJsonLayer = L.geoJson().addTo(map);
function requestGeoJson(){
fetch('https://my-web-server/get-features.php')
.then(function(response){ return response.json() })
.then(function(json){
geoJsonLayer.clearLayers().addData(json);
setTimeout(requestGeoJson, 5000);
});
};
requestGeoJson();
还有其他方法可以使 JS 从网络服务器请求内容,例如使用$.getJSON或XMLHttpRequest代替fetch. 结果与您的场景相同。
还有其他方法可以使用 GeoJSON 数据移动标记而不是清空和重新填充L.GeoJSON实例。例如,遍历L.GeoJSONwith内部的层eachLayer(),然后检查 JSON 有效负载中是否有相应的功能(基于任何可用的唯一 ID)并查看坐标是否已更改。
请注意,JS 会每 5(ish) 秒向您的网络服务器发出一次 HTTP(S) 请求,从而使您的 PHP 代码随着每个请求再次运行。其他方法,例如使用数据库触发器和websockets允许仅在需要时发送更新,就在数据更改后,提供更好的延迟和没有重复的数据。
- 1 回答
- 0 关注
- 182 浏览
添加回答
举报