Mi secuencia de comandos php extrae con éxito datos de una base de datos mysql y crea una matriz geojson validada y formateada correctamente. Pero no puedo entender cómo pasar esa matriz directamente al javascript.
Puedo copiar manualmente los datos de GeoJSON en un archivo llamado manualmente_copied.json y luego llamarlo desde javascript usando la opción url ol.source.Vector. Eso crea un mapa adecuado con todos mis puntos, pero quiero pasar directamente de php al script sin escribir un archivo en el disco.
Soy novato en openlayers y javascript.
Aquí está la mayor parte de mi script php,
<!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>¿Qué tal escribir el geojson como un atributo de datos?
<div id="map" data-geojson="<?= htmlspecialchars(json_encode($geojson)) ?>"></div> <script> const data = JSON.parse(document.getElementById('map').dataset.geojson); </script>¿O como una URL de datos?
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()}), })