Home > Software design >  How to avoid CORS error when reading kml file from google maps
How to avoid CORS error when reading kml file from google maps

Time:11-15

I want to read kml file from url https://www.google.com/maps/d/u/0/kml?mid=1CUrmiiSysq2amCr5_6-YcOcg36sf3CpU&forcekml=1

I can download it when I enter this url to the browser, but I get CORS error when trying to read in php (server side) or js script (client side):

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.

scrip that I'm using

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();

I want to read this file automatically to extract and save some data in csv file.

I have tried to read kml file on server side (php script) using file_get_contents( "https://www.google.com/maps/d/u/0/kml?mid=1CUrmiiSysq2amCr5_6-YcOcg36sf3CpU&forcekml=1" ) as Professor Abronsius explained below, and it is working if access to the map is not restricted.

When I make map private I got error: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden

So on servers side access is forbidden and on client side there is CORS error.

Any solutions to this problem?

CodePudding user response:

I found that this particular endpoint does not need cURL to download - a simple file_get_contents is sufficient so the PHP proxy script can be very simple. If you use a session variable you need only send the request to Google a single time - subsequent requests can be served by the session variable.

For instance:

<?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>
  • Related