Search code examples
javascriptajaxopenlayers

Load GeoJSON from file


First of all to say that I'm trying to learn Openlayers, I'm working with version 6.4.3. I want to load a GeoJON from a file generated from a postgresql query, I send the data to the query, I execute it and generate a .json file (GeoJSON). OK, the problem is when I want to load the file on the map. As I'm doing now, it already shows me the file loaded on the map, I want to load it at the moment that I select something in the html select. As I said, it shows me already loaded, I make a select, I run the query and it clears the map, and until I reload the page, I don't see the new data.

var vectorData = new ol.source.Vector({
    //url: 'data/data.json',
    projection: 'EPSG:3857',
    format: new ol.format.GeoJSON(),
});
var vectorlayer = new ol.layer.Vector({ 
    source: vectorData,
    visible:true,
    displayInLayerSwitcher: false,
    style: styleFunction,
});
fetch('data/data.json')
    .then(function (response) {
        return response.json();
    })
    .then(function (json) {
    var features = new ol.format.GeoJSON().readFeatures(json, {dataProjection: 'EPSG:3857', featureProjection: 'EPSG:3857'});
    vectorData.addFeatures(features);
    //map.getView().fit(vectorData.getExtent());//zoom to
    //vectorData.refresh();
});

Once I run it, in addition to loading the data on the map, I want to zoom to the data, right now the getExtent (which is commenting) makes it appear at the beginning with the zoom to the data when I open the map. I tried putting vectorData.refresh (); in the script that sends the data to the php file that executes the query, but it doesn't work.

function search(){
        var data = document.getElementById("formData");
        object = document.getElementById('data');
        var txt='';
        txt = "\""+object.value+"\"";
        url_object = 'data='+txt;
        xhr(url_object);
    }

    var xmlhttp; 
    function xhr(formParcel){ 
            if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                }
            else
                {// code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = RespuestaModel;
            xmlhttp.open("POST", "DataConsult.php", true);
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlhttp.send(formParcel);
    }

    function RespuestaModel(){
            if(xmlhttp.readyState == 4) {
                if(xmlhttp.status == 200) {
                    vectorData.refresh();
                }
            }
    }

Solution

  • I Solved it. The Loader wasn't receiving the data sent by Post. So, now the page where I do the query, receives the data in json format. Also I removed the vecLayer from the Map Layer Array, and added it to the map later because the vecLayer doesn't exist. I put it all in one function, and now it works. I would have to adjust map.getView (). fit (vectorParcels.getExtent ()); because it zooms in too big for me, if the polygon thant I want to visualize is large, it doesn't grab into the map container div.

    DataParcel.php

    ...
    $params = json_decode(file_get_contents('php://input'), true);
    $parcel = $params["parcel"];
    ...
    

    OL script whith a loader Method

    function drawParcel(parcelId){
        var vectorParcels = new ol.source.Vector({
            format: new  ol.format.GeoJSON(),
            loader: function(extent, resolution, projection) {
                var proj = projection.getCode();
                var url = "functionsPHP/DataParcel.php"
                var xhr = new XMLHttpRequest();
    
                var params = {
                    parcel: parcelId
                }
    
                xhr.open('POST', url);
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                var onError = function() {
                   vectorParcels.removeLoadedExtent(extent);
                }
                xhr.onerror = onError;
                xhr.onload = function() {
                    xhr.responseText;
                    console.log(xhr.responseText);
                    if (xhr.status == 200) {
                        vectorParcels.addFeatures(
                        vectorParcels.getFormat().readFeatures(xhr.responseText));
                        map.getView().fit(vectorParcels.getExtent());
                        $("#formParcel")[0].reset();
                   } else {
                     onError();
                   }
                 }
                 xhr.send(JSON.stringify(params));
            },
        });
        var vectorlayer = new ol.layer.Vector({
            source:vectorParcels,
            visible:true,
            displayInLayerSwitcher: false,
            style: styleFunction,               
        });
    
        map.addLayer(vectorlayer)
    }