1

I want to load a dynamic GeoJSON, I get the data for the search from a select, execute the query and write the GeoJSON file with a session_id like this

$element = $_POST['element'];
$query = "SELECT ...";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
//
$geojson = array(
    'type' => 'FeatureCollection',
    'features' => array()
);
$i = 0;
while ($line = pg_fetch_assoc($result)) {
    $feature = array(
    'geometry' => json_decode($line['geojson'], true),
    'properties' => $data[]=$line,
    'id' => $i++
    );
    array_push($geojson['features'], $feature);
}
$localData = json_encode($geojson);

$contData = "data/fileData_".session_id().".json";

$file = fopen($contData, "w");

fwrite($file, $localData);
fclose($file);

I define the js file with the options

Proj4js.defs["EPSG:25830"] = "+proj=utm +zone=30 +ellps=GRS80 +units=m +no_defs";

var projection = ol.proj.get('EPSG:3857');

var styleP = new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(255, 255, 255, 0.6)',
  }),
  stroke: new ol.style.Stroke({
    color: '#319FD3',
    width: 1,
  }),
});

var vectorParcels = new ol.source.Vector({
    //url: 'data/parcels.json',
    projection: 'EPSG:3857',
    format: new ol.format.GeoJSON(),
});
var Parcels = new ol.layer.Vector({ 
    name: 'Parcels',
    source: vectorParcels,
    visible:true,
    //active:false,
    displayInLayerSwitcher: false,
    style: styleP,
});

fetch('data/parcels.json')
  .then(function (response) {
    return response.json();
  })
  .then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(json,  {dataProjection: 'EPSG:25830', featureProjection: 'EPSG:3857'});
    vectorParcels.addFeatures(features);
  });
//
var view = new ol.View({
    projection: projection,
    zoom:5.6,
    center: [984934.497931, 5074393.544263]
});
//Map
var map= new ol.Map({
    target: 'map',
    view:view,
    layers: [osm, Parcels],
    controls: ol.control.defaults({
      zoom: false,
      attribution: false,
      rotate: false,
    }),
});

This is the GeoJSON resume

{
  "type": "FeatureCollection",
  "features": [
    {
"type":"Feature",      
"geometry": {
        "type": "MultiPolygon",
        "crs": {
          "type": "name",
          "properties": {
            "name": "EPSG:25830"
          }
        },
        "coordinates": [
          [
            [
              [
                646080.6495,
                4579915.348
              ],
              [
                646034.5,
                4579957.2185
              ],
              [
                646112.2905,
                4580038.588
              ],
              [
                646170.981,
                4580084.288
              ],
              [
                646183.7015,
                4580098.098
              ]
           ]
          ]
        ]
      },
"properties": {
        "id": "68",
        "cadastralcode": "50004A02500051",
        "poligon": "25",
        "parcel": "51",
        "zone": "ZONE 2",
        "longitude": "41.35836325085319",
        "latitude": "-1.2521282283817523",
        "altitude": "587",
        "geojson": "{\"type\":\"MultiPolygon\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:25830\"}},\"coordinates\":[[[[646080.6495,4579915.348],
[646034.5,4579957.2185],
[646112.2905,4580038.588],
[646170.981,4580084.288],
[646183.7015,4580098.098]]]]}"
         },
      "id": 0
    }
  ]
}

I don't know what I have to add to the project for it to work. I don't know what I'm doing wrong. Is there an example where I can see how to do it?

1 Answer 1

2

When defining vector source, you can leave ol.source.Vector option url out and read data later when available with fetch API, read them into features with .readFeatures method and then add them to the layer with .addFeatures method.

Since your GeoJSON data coordinates in EPSG:25830 projection, you'll also have to define this projection with proj4.defs, and then when reading data convert coordinates to the standard EPSG:3857 projection.

Code could then look something like this:

fetch('data/filedata_".session_id().".json')
  .then(function (response) {
    return response.json();
  })
  .then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(json,  {dataProjection: 'EPSG:25830', featureProjection: 'EPSG:3857'});
    vectorParcels.addFeatures(features);
  });
5
  • Let's see how I can apply it. But I found a problem with the GeoJSON,
    – user68481
    Jan 27, 2021 at 10:29
  • 2
    Your question way answered above. If you have some other problem/question, please post is as a new, separate question. GIS SE site has a policy of focused questions, which means one question per question.
    – TomazicM
    Jan 27, 2021 at 12:53
  • 2
    I see that now you posted your additional problem as a new question. If the answer above helped you resolve your initial question, it's customary on GIS SE to amrk it as accpeted to let other users know that problem was resolved.
    – TomazicM
    Jan 27, 2021 at 14:26
  • I solved the second question, but I'm not sure how to apply your solution for the first question.
    – user68481
    Jan 27, 2021 at 17:51
  • 1
    There must be some event that tells you that GeoJSON data has been created. When that event is fired, execute the above code.
    – TomazicM
    Jan 27, 2021 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.