du248227 2019-02-21 16:36
浏览 209

从Ajax请求获取JSON并在Leaflet中创建多边形图层

I need some help with a script, i have an ajax request that returns a GeoJSON

Images:

  1. PHP to Ajax
  2. TEST GeoJSON
  3. GeoJSON

JSON Format

  • "id_map": "2",
  • "description": "AC1",
  • "geojson": {a GeoJSON coordinate }
  • "file": "AC1.geojson"

I can use AJAX JSON Leaflet (plugin( to create a polygon layer using the JSON value file ex (ac1.geojson) and point it up to a folder with the GeoJSON files (ex. geojson), but i have the same GeoJSON saved as a text variable in a database and i want to use it besides the file because of the risk of losing the files, so i recover it (i use GeoJson.io to validate the geojson and copy paste it in a column in my database) using a database connection and then i JSON encode it, but i am unable to use it. And I'm having problems with the format that comes out from the PHP.

$(document).ready(function() {
  document.body.onload = function() {

    var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 20,
        minZoom: 13,
        attribution: 'x'
      }),
      latlng = L.latLng(-32.0312422, -52.0917713);

    var mymap = L.map('mapid', {
      center: latlng,
      zoom: 18,
      layers: [tiles]
    });
    L.marker([-32.0312422, -52.0917713]).addTo(mymap);

    function popUp(f, l) {
      var out = [];
      if (f.properties) {
        for (key in f.properties) {
          out.push(key + ": " + f.properties[key]);
        }
        l.bindPopup(out.join("<br />"));
      }
    }

    var j_url = "somephp.php";

    var results = $.ajax({
      url: j_url,
      dataType: 'json',
      cache: false,
      success: AjaxSucceeded,
      error: AjaxFailed
    });

    function AjaxSucceeded(results) {
      console.log("Data successfully loaded.");
      alert("OK");

      $.each(results, function(index, value) {
        var geojsonTESTE = {
          "type": "FeatureCollection",
          "features": [{
            "type": "Feature",
            "properties": {},
            "geometry": {
              "type": "Polygon",
              "coordinates": [
                [
                  [-52.101760, -32.031909],
                  [-52.102275, -32.028598],
                  [-52.100794, -32.028435],
                  [-52.099206, -32.029053],
                  [-52.097554, -32.029362],
                  [-52.097511, -32.029672],
                  [-52.096760, -32.029672],
                  [-52.096696, -32.029544],
                  [-52.095795, -32.029617],
                  [-52.094142, -32.029835],
                  [-52.088585, -32.030672],
                  [-52.088392, -32.030763],
                  [-52.088027, -32.034656],
                  [-52.101631, -32.032145],
                  [-52.101760, -32.031909]
                ]
              ]
            }
          }]
        };

        var geoObject = JSON.parse(value.geojson);

        L.geoJSON(geojsonTESTE).addTo(mymap);
        L.geoJSON(features).addTo(mymap);

        //With Leaflet Ajax e Files
        //j_url = "json/"+value.file;                            
        //var jsonTest = new L.GeoJSON.AJAX([j_url]{onEachFeature:popUp}).addTo(mymap);            
      });
    }

    function AjaxFailed(results) {
      console.log("ERROR AJAX");
      alert("ERRO");
    }

    $.when(results).done(function() {

    });

  };
});
<?php
header('Content-Type: application/json');

$connStr = { database connection string }
$conn   = pg_connect($connStr);
$result = pg_query($conn, "select * from mapas");

$qtd = pg_num_rows($result); 

$res = "[";

if($qtd > 0){   
   $i = 0;
   foreach(pg_fetch_all($result) as $row)
    {       
        $x = $row['geojson'];
        $patterns = array ('/[^A-Za-z0-9\-\,\"\:\{\}\[\]]/');
        $replace = array ('');
        $desc = preg_replace($patterns, $replace,$x);         
        $desc = str_replace('\"', '"', $desc, $count);
        
        $data['id_map']       = $row['id_map'];
        $data['description']  = $row['description'];
        $data['geojson']      = $desc;
        $data['file']         = $row['file'];
       
        $map = json_readable_encode($data,null,true); 
               
        $res .= $map;
        
        if($i < $qtd -1 ){
        $res .= ",";
        }
        $i++;
    }
}  
$res .= "]";

echo trim($res);

pg_free_result($result);
pg_close();
?>

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?
    • ¥100 求三轴之间相互配合画圆以及直线的算法