1 回答

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
由于您使用的是 PHP,因此解決此問(wèn)題的方法是將所有生成 geojson 的代碼放入一個(gè)不同的 PHP 文件中,例如一個(gè)get-features.php僅調(diào)用的文件:
<?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 每五秒重新請(qǐng)求該 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);
或者在請(qǐng)求之間等待五秒的循環(huán)中請(qǐng)求該 URL ,以避免潛在的競(jìng)爭(zhēng)條件:
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 ) 有什么關(guān)系?天真的方法是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 從網(wǎng)絡(luò)服務(wù)器請(qǐng)求內(nèi)容,例如使用$.getJSON或XMLHttpRequest代替fetch. 結(jié)果與您的場(chǎng)景相同。
還有其他方法可以使用 GeoJSON 數(shù)據(jù)移動(dòng)標(biāo)記而不是清空和重新填充L.GeoJSON實(shí)例。例如,遍歷L.GeoJSONwith內(nèi)部的層eachLayer(),然后檢查 JSON 有效負(fù)載中是否有相應(yīng)的功能(基于任何可用的唯一 ID)并查看坐標(biāo)是否已更改。
請(qǐng)注意,JS 會(huì)每 5(ish) 秒向您的網(wǎng)絡(luò)服務(wù)器發(fā)出一次 HTTP(S) 請(qǐng)求,從而使您的 PHP 代碼隨著每個(gè)請(qǐng)求再次運(yùn)行。其他方法,例如使用數(shù)據(jù)庫(kù)觸發(fā)器和websockets允許僅在需要時(shí)發(fā)送更新,就在數(shù)據(jù)更改后,提供更好的延遲和沒(méi)有重復(fù)的數(shù)據(jù)。
- 1 回答
- 0 關(guān)注
- 206 瀏覽
添加回答
舉報(bào)