OpenLayers – Get GeoJSON from Database Using AJAX

ajaxgeojsonjqueryopenlayers

I have this code:

 if (ol.proj.proj4 && ol.proj.proj4.register) { ol.proj.proj4.register(proj4); }
            
            var features = new ol.format.GeoJSON().readFeatures(
                $.ajax({ 
                    type: 'GET', 
                    url: 'readGeojson.php', 
                    //data: { get_param: 'value' }, 
                    dataType: 'json',
                    success: function (data, status) { 
                        console.log(data);
                        geojson = data
                    }
                })
            );
            
            function reverseTransform(coordinates, output, dimensions) {
                var dims = dimensions || 2;
                for (var i=0; i<coordinates.length; i+=dims) {
                  var j = coordinates[i];
                  coordinates[i] = coordinates[i+1];
                  coordinates[i+1] = j;
                }
                return coordinates;
            }
            
            features.forEach(function(feature){
                feature.setId(undefined);
                feature.getGeometry().transform('EPSG:31700', 'EPSG:3857');
            });
            
            var map = new ol.Map({
                layers: [
                    new ol.layer.Tile({
                        source: new ol.source.OSM(),
                    }),
                    new ol.layer.Vector({
                        source: new ol.source.Vector({
                            features: features
                        })
                    })
                ],
                target: 'map',
                controls: ol.control.defaults({
                        attributionOptions:
                            ({
                                collapsible: false
                            })
                    }).extend([
                        new ol.control.OverviewMap(),
                        new ol.control.FullScreen(),
                        new ol.control.ScaleLine()
                        
                    ]),
                    interactions: [
                        new ol.interaction.DragRotateAndZoom(),
                        new ol.interaction.MouseWheelZoom(),
                        new ol.interaction.DragPan(),
                        new ol.interaction.DoubleClickZoom()
                    ],
                view: new ol.View({
                    center: ol.proj.transform([698282.236, 377375.758], 'EPSG:31700', 'EPSG:3857'),
                    zoom: 14,
                })
            });

I want to get a GeoJSON from the ajax database and display co-ordinates on the automatic map of how to load the page in OpenLayers.

I tried this way:

var features = new ol.format.GeoJSON().readFeatures(
            $.ajax({ 
                type: 'GET', 
                url: 'readGeojson.php', 
                //data: { get_param: 'value' }, 
                dataType: 'json',
                success: function (data, status) { 
                    console.log(data);
                    geojson = data
                }
            })
        );

And I got this error from the code:

Uncaught Error: Unsupported GeoJSON type: undefined
    at Af (GeoJSON.js:299)
    at e.readFeatureFromObject (GeoJSON.js:110)
    at e.readFeaturesFromObject (GeoJSON.js:146)
    at e.readFeatures (JSONFeature.js:56)
    at get_map (test1.php:3410)
    at HTMLButtonElement.onclick (test1.php:18) Af @ GeoJSON.js:299 e.readFeatureFromObject @ GeoJSON.js:110 e.readFeaturesFromObject @ GeoJSON.js:146 e.readFeatures @ JSONFeature.js:56 get_map @ test1.php:3410 onclick @ test1.php:18

This code generate GeoJSON :

$sql = "SELECT *, ST_AsGeoJSON(geometry) AS geojson FROM a_final order by ST_XMin(geometry) LIMIT 10";
    // echo $sql;
    $dbcon = pg_connect("host=localhost dbname=test user=postgres password=72342");
    
    $query = pg_query($dbcon,$sql); 
    $geojson = array(
        'type'      => 'FeatureCollection',
        'features'  => array()
    ); 
    while($edge=pg_fetch_assoc($query)) {  
        $feature = array
            (
            'type' => 'Feature',
            
            'geometry' => json_decode($edge['geojson'], true),
             'crs' => array(
                'type' => 'EPSG',
                'properties' => array('code' => '31700')
            ),
            'geometry_name' => 'wkb_geometry',
            'properties' => array
            (
                'ogc_fid' => htmlspecialchars($edge['ogc_fid']),
                'area_id' => $edge['area_id'],
                'building_id' => $edge['building_id'],
                'type' => $edge['type'],
                'area' => $edge['area'],
                'owner' => $edge['owner'],
                'description' => $edge['description'],
                'administration' => $edge['administration'],
                'address' => $edge['address'],
                'property' => $edge['property'],
                'layer' => $edge['layer'],
                'extendedentity' => $edge['extendedentity'],
                'linetype' => $edge['linetype'],
                'entityhandle' => $edge['entityhandle'],
                'text' => $edge['text'],
                'wkb_geometry' => $edge['geometry']
            )
        );
        array_push($geojson['features'], $feature);
    }
    
    pg_close($dbcon);
    header('Content-type: application/json',true);
    echo json_encode($geojson);

I tried to directly copy GeoJSON into the pickup variable and go so ….

GeoJSON:

  {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698282.236,377375.758],[698289.591,377372.136],[698183.88,377182.298],[698182.72,377197.045],[698282.236,377375.758]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"01020000000500000000FED478544F2541002731087F081741408D972E634F25418195438B70081741295C8FC28F4E254181E92631790517410AD7A3708D4E2541027B142EB405174100FED478544F2541002731087F081741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698289.591,377372.136],[698295.211,377369.369],[698184.767,377171.028],[698183.88,377182.298],[698289.591,377372.136]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"010200000005000000408D972E634F25418195438B700817411E31086C6E4F2541C022DB79650817416039B488914E25414108AC1C4C051741295C8FC28F4E254181E9263179051741408D972E634F25418195438B70081741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698307.17,377363.481],[698311.314,377361.44],[698321.211,377356.567],[698188.867,377118.9],[698185.72,377158.908],[698301.257,377366.392],[698307.17,377363.481]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"0102000000070000007F3D0A57864F25417F438BEC4D081741A09BC4A08E4F2541415C8FC2450817412131086CA24F254102A69B44320817417F6CE7BB994E25419A9999997B0417410AD7A370934E254180C0CAA11B051741FF8095837A4F2541C0726891590817417F3D0A57864F25417F438BEC4D081741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698191.282,377088.192],[698336.526,377349.026],[698348.895,377342.935],[698195.874,377068.133],[698192.739,377069.67],[698191.282,377088.192]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"010200000006000000E04D62909E4E254101A69BC40004174140DF4F0DC14F25417FBE9F1A14081741A0703DCAD94F2541BFA370BDFB071741A0ED7CBFA74E254102273188B00317413F355E7AA14E2541007B14AEB6031741E04D62909E4E254101A69BC400041741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698223.512,377072.661],[698215.605,377058.461],[698210.805,377060.814],[698218.769,377075.117],[698363.812,377335.59],[698368.608,377333.228],[698223.512,377072.661]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"01020000000700000021DD2406DF4E2541032FDDA4C2031741608FC235CF4E2541426210D889031741C1F5289CC54E25414037894193031741415EBA89D54E254100D9CE77CC031741C076BE9FF74F2541C3F5285CDE071741A0C64B370150254100D578E9D407174121DD2406DF4E2541032FDDA4C2031741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698227.007,377070.852],[698219.142,377056.727],[698215.605,377058.461],[698223.512,377072.661],[698368.608,377333.228],[698372.141,377331.489],[698227.007,377070.852]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"01020000000700000000819503E64E254141B07268BB0317416139B448D64E254141B072E882031741608FC235CF4E2541426210D88903174121DD2406DF4E2541032FDDA4C2031741A0C64B370150254100D578E9D4071741E126314808502541816ABCF4CD07174100819503E64E254141B07268BB031741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698230.934,377068.819],[698223.116,377054.779],[698219.142,377056.727],[698227.007,377070.852],[698372.141,377331.489],[698376.112,377329.534],[698230.934,377068.819]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"010200000007000000803F35DEED4E254180EFA746B3031741205A643BDE4E2541022DB21D7B0317416139B448D64E254141B072E88203174100819503E64E254141B07268BB031741E126314808502541816ABCF4CD07174161105839105025417FE5D022C6071741803F35DEED4E254180EFA746B3031741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698237.435,377065.453],[698229.695,377051.554],[698223.116,377054.779],[698230.934,377068.819],[698376.112,377329.534],[698377.635,377328.784],[698382.096,377326.587],[698382.684,377326.297],[698237.435,377065.453]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"010200000009000000DF51B8DEFA4E2541803BDFCFA50317413F0AD763EB4E2541C0C64B376E031741205A643BDE4E2541022DB21D7B031741803F35DEED4E254180EFA746B303174161105839105025417FE5D022C60717415FB81E45135025417FE5D022C307174180E926311C50254140871659BA071741803F355E1D50254182C42030B9071741DF51B8DEFA4E2541803BDFCFA5031741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698241.362,377063.42],[698233.669,377049.605],[698229.695,377051.554],[698237.435,377065.453],[698382.684,377326.297],[698386.655,377324.342],[698241.362,377063.42]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"010200000007000000601058B9024F2541027B14AE9D031741002B8756F34E2541BF1E856B660317413F0AD763EB4E2541C0C64B376E031741DF51B8DEFA4E2541803BDFCFA5031741803F355E1D50254182C42030B907174100295C4F25502541823F355EB1071741601058B9024F2541027B14AE9D031741"}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[698278.389,377044.249],[698271.143,377031.236],[698233.669,377049.605],[698241.362,377063.42],[698386.655,377324.342],[698424.092,377305.908],[698278.389,377044.249]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"","area_id":null,"building_id":null,"type":null,"area":null,"owner":null,"description":null,"administration":null,"address":null,"property":null,"layer":"Green Area","extendedentity":null,"linetype":null,"entityhandle":null,"text":null,"wkb_geometry":"01020000000700000000022BC74C4F254140DBF9FE50031741C04B37493E4F254101FCA9F11C031741002B8756F34E2541BF1E856B66031741601058B9024F2541027B14AE9D03174100295C4F25502541823F355EB1071741C09F1A2F7050254180C0CAA16707174100022BC74C4F254140DBF9FE50031741"}}]}

My GeoJSON its this:

{"type":"FeatureCollection","features":[{"type":"Feature","id":"2","geometry":{"type":"LineString","coordinates":[[698282.236,377375.758],[698289.591,377372.136],[698183.88,377182.298],[698182.72,377197.045],[698282.236,377375.758]]},"crs":{"type":"EPSG","properties":{"code":"31700"}},"geometry_name":"wkb_geometry","properties":{"ogc_fid":"2","area_id":"2","building_id":"2","type":"test","area":"test","owner":"test","description":"test","administration":"test","address":"test","property":"test","layer":"Green Area","extendedentity":null,"linetype":"test","entityhandle":null,"text":"test","wkb_geometry":"01020000000500000000FED478544F2541002731087F081741408D972E634F25418195438B70081741295C8FC28F4E254181E92631790517410AD7A3708D4E2541027B142EB405174100FED478544F2541002731087F081741"}}]}

Best Answer

Below is code that works. It's almost exact copy of code from question, except that EPSG:31700 definition is added and geojson data is imported through geojson variable.

<script src="geojson.js"></script>

proj4.defs('EPSG:31700',
     '+proj=sterea +lat_0=46 +lon_0=25 +k=0.99975 +x_0=500000 +y_0=500000 +ellps=krass +towgs84=28,-121,-77,0,0,0,0 +units=m +no_defs');                      
ol.proj.proj4.register(proj4);

var features = (new ol.format.GeoJSON()).readFeatures(geojson);

features.forEach(function(feature){
    feature.setId(undefined);
    feature.getGeometry().transform('EPSG:31700', 'EPSG:3857');
});

var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
        }),
        new ol.layer.Vector({
            source: new ol.source.Vector({
                features: features
            })
        })
    ],
    target: 'map',
    controls: ol.control.defaults({
            attributionOptions:
                ({
                    collapsible: false
                })
        }).extend([
            new ol.control.OverviewMap(),
            new ol.control.FullScreen(),
            new ol.control.ScaleLine()

        ]),
        interactions: [
            new ol.interaction.DragRotateAndZoom(),
            new ol.interaction.MouseWheelZoom(),
            new ol.interaction.DragPan(),
            new ol.interaction.DoubleClickZoom()
        ],
    view: new ol.View({
        center: ol.proj.transform([698282.236, 377375.758], 'EPSG:31700', 'EPSG:3857'),
        zoom: 14,
    })
});

Here is the result:

enter image description here

EDIT1: If you want to read data with jquery ajax, where data is stored in file data.geojson on server, then replace line

var features = (new ol.format.GeoJSON()).readFeatures(geojson);

with

var features;

$.ajax({
    type: "GET",
    url: "data.geojson",
    dataType: 'json',
    async: false,
    success: function (response) {
       features = new ol.format.GeoJSON().readFeatures(response);
    }
});