我想從 url 讀取 kml 檔案 https://www.google.com/maps/d/u/0/kml?mid=1CUrmiiSysq2amCr5_6-YcOcg36sf3CpU&forcekml=1
當我在瀏覽器中輸入這個 url 時,我可以下載它,但是在嘗試讀取 php(服務器端)或 js 腳本(客戶端)時出現 CORS 錯誤:
Access to XMLHttpRequest at 'https://www.google.com/maps/d/u/0/kml?mid=1CUrmiiSysq2amCr5_6-YcOcg36sf3CpU&forcekml=1'
from origin 'https://my-app-domain.pl'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我正在使用的腳本
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// reading and parsing code will go here
}
};
xhttp.open("POST", "https://www.google.com/maps/d/u/0/kml?mid=1CUrmiiSysq2amCr5_6-YcOcg36sf3CpU&forcekml=1", true);
xhttp.send();
我想自動讀取此檔案以在 csv 檔案中提取和保存一些資料。
我曾嘗試使用上讀取服務器端(PHP腳本)KML檔案file_get_contents( "https://www.google.com/maps/d/u/0/kml?mid=1CUrmiiSysq2amCr5_6-YcOcg36sf3CpU&forcekml=1" )
作為Abronsius教授解釋如下,它是作業,如果沒有限制地訪問地圖。
當我將地圖設為私有時,出現錯誤: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
所以在服務器端訪問被禁止,在客戶端有 CORS 錯誤。
這個問題有什么解決方案嗎?
uj5u.com熱心網友回復:
我發現這個特定的端點不需要 cURL 來下載 - 一個簡單的file_get_contents就足夠了,所以 PHP 代理腳本可以非常簡單。如果您使用會話變數,則只需向 Google 發送一次請求 - 會話變數可以為后續請求提供服務。
例如:
<?php
session_start();
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['task'] ) && $_POST['task']=='download-kml' ){
if( !isset( $_SESSION['kml-file'] ) ){
$_SESSION['kml-file']=file_get_contents( 'https://www.google.com/maps/d/u/0/kml?mid=1CUrmiiSysq2amCr5_6-YcOcg36sf3CpU&forcekml=1' );
}
ob_clean();
header('Content-Type: application/xml');
exit( $_SESSION['kml-file'] );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Google Maps - KML cors issue bypass proxy</title>
</head>
<body>
<script>
let fd=new FormData();
fd.set('task','download-kml');
fetch( location.href, { method:'post', body:fd } )
.then( r=>{ return r.text() })
.then( data=>{
/* process the XML as you need */
console.info( data );
})
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/358046.html
上一篇:在組件Ionic中重新加載資料
