2 votos

Mostrar puntos (capa) de la base de datos PostgreSQL en el mapa OpenLayers

Tengo este código, quiero cargar una colección de puntos almacenados en una tabla de la base de datos PostgreSQL, recibo el formato GeoJSON correctamente, pero los puntos nunca aparecen en el mapa.

A continuación se incluyen los tres archivos: (Archivo php + archivo html + archivo js)

// my php file to generate the geojson format

<?php 

require_once "connection.php";

// bd table to php array

function colsTabVersArray($nom_table){
    $res = array();
    $req = executerRequete("SELECT column_name FROM information_schema.columns WHERE table_name = '$nom_table'");
    while($ligne = pg_fetch_row($req)){
        $res[] = $ligne[0];
    }
    return $res;
}

// requete sql 

function executerRequete($requete){
    return pg_query($GLOBALS["db"], $requete);
}

// test

        $feature = array();
        $result = executerRequete("SELECT st_asgeojson(geom) AS geom FROM nyc_subway_stations");
        if($result)

        {
            while($row = pg_fetch_assoc($result)) {
                $type = '"type": "Feature"';
                $geometry = '"geometry": '.$row['geom'];
                unset($row['geom']);
                $properties = '"properties": '.json_encode($row);
                $feature[] = '{'.$type.', '.$geometry.', '.$properties.'}';

            }
            $header = '{"type": "FeatureCollection", "features": [';
            $footer = ']}';
            if(count($feature) > 0) {
                echo $header.implode(', ', $feature).$footer;
            }
            else {
                echo '{"type":"FeatureCollection", "features":"empty"}';
            }

        }

?>

**************************************************************************

// File Map.js 

data = {
    layer: true
}

actualiserCouche("couchePoint", 'couchePoint', 'Couche Point', data);
// /L'AJOUT D'UNE COUCHE

function actualiserCouche(couche, name, title, data) {

    geojson = new ol.format.GeoJSON();
    source_couche = new ol.source.Vector();

    // DÉFINITION DU STYLE DE LA COUCHE
    var myStyle = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 20,
        fill: new ol.style.Fill({color: 'black'}),
        stroke: new ol.style.Stroke({
        color: [255,0,0], width: 2
        })
      })
    })
    // /DÉFINITION DU STYLE DE LA COUCHE

    // DÉFINITION DE LA COUCHE ARRONDIS
    window[couche] = new ol.layer.Vector({
        name: name,
        title: title,
        visible: true,
        source: source_couche,
        style: myStyle
    });
    // /DÉFINITION DE LA COUCHE ARRONDIS

    // SUPPRESSION DU CONTENU DE LA COUCHE
    source_couche.clear();
    // /SUPPRESSION DU CONTENU DE LA COUCHE

    // L'APPEL AJAX AVEC LES PARAMÈTRES
    success = function (result) {
        console.log(result);
        var features = geojson.readFeatures(result, { featureProjection: 'EPSG:26918' });
        source_couche.addFeatures(features);
    }
    error_fatale = function (jqXhr) {
        console.log(jqXhr);
    }   
    ajax("index2.php", data, error_fatale, success);
    // /L'APPEL AJAX AVEC LES PARAMÈTRES

    // L'AJOUT DE LA COUCHE À LA CARTE
    map.addLayer(window[couche]);
    // /L'AJOUT DE LA COUCHE À LA CARTE

}

function ajax(url, data, error, success = function (resultat) {
    if (resultat.type == "erreur") {
        console.log("erreur", resultat.msg);
    }
    else if (resultat.type == "succes") {
        console.log("succes", resultat.msg);
    }
}, complete = null, beforeSend = null) {

    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        dataType: 'JSON',
        beforeSend: beforeSend,
        success: success,
        error: error,
        complete: complete
    });
}

**********************************************************************

//File : index.html to load the map 

<html lang="en">
  <head>
   <link rel="stylesheet" href="plugin/open-layers/css/ol.css">

    <style>
      .map {
        height: 100%;
        width: 100%;
      }
    </style>
       <title>OpenLayers example</title>
  </head>
  <body>
    <h2>My Map</h2>
    <div id="map" ></div>

<!-- SCRIPT D'OPEN LAYERS -->
    <script src="plugin/open-layers/js/ol.js"></script>

    <!-- /SCRIPT D'OPEN LAYERS -->
     <script>

  var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([-74.010806, 40.711412]),
          zoom: 10
        })
      });

       </script>

<script src="plugin/jquery/jquery.min.js"></script>
  <script src="map.js"></script>

  </body>

</html>

Esta es una parte del geojson que obtengo en el navegador de inicio de sesión

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type":"Point","coordinates":[583521.854408956,4507077.86259909]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[583324.48663246,4506805.37316021]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[583304.182399475,4506069.65404812]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590250.10594797,4518558.01992433]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590454.739989117,4519145.71961785]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590465.893419111,4519168.6974832]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590573.169495527,4520214.76617728]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[591252.83141041,4520950.35335555]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[590946.3972263,4521077.31897688]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[591583.611145281,4521434.84662681]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[591242.929957587,4521581.88593774]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[593778.100679278,4521296.80231282]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[591869.966492465,4522223.76481329]}, "properties": []}, {"type": "Feature", "geometry": {"type":"Point","coordinates":

1voto

hood Puntos 16

Lo que tienes mal es la especificación CRS al leer características de GeoJSON con readFeatures método. Este método tiene dos opciones de CRS: dataProjection indica la proyección de datos GeoJSON y featureProjection indica la proyección de las características generadas.

En su caso dataProjection debe ser 'EPSG:26918' y featureProjection por defecto 'EPSG:3857' :

var features = geojson.readFeatures(result, {dataProjection: 'EPSG:26918', featureProjection: 'EPSG:3857' });

Aquí está el cuadro de marcadores, basado en su muestra GeoJSON:

enter image description here

Para que la EPSG 26918 funcione es necesario definirla con proj4.js biblioteca:

<script type="text/javascript" src=https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.5.0/proj4.js"></script>

proj4.defs("EPSG:26918","+proj=utm +zone=18 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
ol.proj.proj4.register(proj4);

i-Ciencias.com

I-Ciencias es una comunidad de estudiantes y amantes de la ciencia en la que puedes resolver tus problemas y dudas.
Puedes consultar las preguntas de otros usuarios, hacer tus propias preguntas o resolver las de los demás.

Powered by:

X