'How to pass a GeoJSON formatted array of longitude and latitude locations from php to javascript to create an Openlayers 6 map?

My php script successfully extracts data from a mysql database and creates a properly formatted and validated geojson array. But I can't figure out how to pass that array directly to the javascript.

I am able to manually copy the GeoJSON data to a file called manually_copied.json and then call that from the javascript using ol.source.Vector url option. That creates a proper map with all my points but I want to go directly from php to the script without writing a file to disk.

I am novice at openlayers and javascript.

Here is most of my php script,

<!DOCTYPE html>
<html lang="en">
<head>

<link rel="stylesheet" href="lib/openlayers/v6.13.0/css/ol.css" type="text/css">
<script src="lib/openlayers/v6.13.0/build/ol.js"></script>

<style>
.map {
    height: 600px;
    width: 100%;
}
</style>
</head>
<body>
<?php

echo "\n<div id=\"map\" class=\"map\"></div>";

//+++++

[ my code to extract a series of lon & lat values from an mysql database
[ to create an array called $geojson

//+++++

// unused
// echo json_encode($geojson, JSON_NUMERIC_CHECK);
?>

<script>

// How do I use this array??????
var geojson_from_php = <?php echo json_encode($geojson, JSON_NUMERIC_CHECK); ?>;
      
      var map = new ol.Map({
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        target: 'map',
        view: new ol.View({
          center: ol.proj.transform([-98.45, 38.714], 'EPSG:4326', 'EPSG:3857'),
          zoom: 4
        })
      });
      var vector = new ol.layer.Vector({
            source: new ol.source.Vector({
            url: 'manually_copied.json',
            format: new ol.format.GeoJSON()
        }),
            style: new ol.style.Style({
            image: new ol.style.Icon({
            src: 'images/marker.png'
          })
         })
      });
      map.addLayer(vector);
</script>



Solution 1:[1]

How about writing the geojson as a data-attribute?

<div id="map" data-geojson="<?= htmlspecialchars(json_encode($geojson)) ?>"></div>
<script>
const data = JSON.parse(document.getElementById('map').dataset.geojson);
</script>

Or as a data url?

const vector = new ol.layer.Vector({
    source: new ol.source.Vector({
    url: 'data:application/json;base64,<?= base64_encode(json_encode($geojson)) ?>',
    format: new ol.format.GeoJSON()}),
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1