如何使用ajax在openlayer3中添加层?

问题描述 投票:0回答:2

我是 Openlayers3 的新手.....我正在尝试使用 ajax 和 php 从数据库加载数据以将矢量数据加载到 openlayers3,我被卡住了,不知道是什么问题。 这是我的代码 任何人都可以帮助我吗?

$(document).ready(function()
{
//extent of the map
view = new ol.View({
    center:ol.proj.transform([125.7799,8.7965], 'EPSG:4326', 'EPSG:3857'),
    zoom:11,
    maxZoom:18,
    minZoom:2
});

//BaseLayer
var baseLayer = new ol.layer.Tile({
    source: new ol.source.OSM()
});

// create a vector source that loads a GeoJSON file
var vectorSource = new ol.source.Vector({
    projection: 'EPSG:4326',
    url: 'data/Boundaries.geojson',
    format: new ol.format.GeoJSON()

  });

var geoJSONFormat = new ol.format.GeoJSON();

var farmersSource = new ol.source.Vector({
  loader: function(extent, resolution, projection) {
    var url = 'allfarmers_geojson.php?p=' + extent.join(',');
    $.ajax({
      url: url,
      success: function(data) {
        var features = geoJSONFormat.readFeatures(data);
        farmersSource.addFeatures(features);
      }
    }); 
  },
  strategy: ol.loadingstrategy.bbox
});


// Polygons
var createPolygonStyleFunction = function() {
  return function(feature, resolution) {
    var style = new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'blue',
        width: 1

      }),
      fill: new ol.style.Fill({
        color: '#faeaac'
      }),
      //text: createTextStyle(feature)
    });
    return [style];
  };
};

// a vector layer to render the source
var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style:createPolygonStyleFunction()

});

var farmersLayer = new ol.layer.Vector({
    source: farmersSource
    //style:createPolygonStyleFunction()

});

//Map
var map = new ol.Map({
    target:'map',
    controls:ol.control.defaults().extend([
        new ol.control.ScaleLine(),
        new ol.control.ZoomSlider()
    ]),
    renderer: 'canvas',
    layers:[baseLayer,vectorLayer,farmersLayer],
    view:view
});

 //////////styling features and with mouse over color change/////////////
var highlightStyleCache = {};

var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector(),
map: map,
style: function(feature, resolution) {
  var text = resolution < 5000 ? feature.get('NAME_3') : '';
  if (!highlightStyleCache[text]) {
    highlightStyleCache[text] = new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#f00',
        width: 1
      }),
      fill: new ol.style.Fill({
        color: 'rgba(255,0,0,0.1)'
      }),
      text: new ol.style.Text({
        font: '12px Calibri,sans-serif',
        text: text,
        fill: new ol.style.Fill({
          color: '#f00'
        })
      })
    });
  }
  return highlightStyleCache[text];
}
});

var highlight;
var displayFeatureInfo = function(pixel) {

var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
      return feature;
    });

    if (feature !== highlight) {
      if (highlight) {
        featureOverlay.getSource().removeFeature(highlight);
      }
      if (feature) {
        featureOverlay.getSource().addFeature(feature);
      }
      highlight = feature;
    }

  };

  map.on('pointermove', function(evt) {
    if (evt.dragging) {
      return;
    }
    var pixel = map.getEventPixel(evt.originalEvent);
    displayFeatureInfo(pixel);
  });

  map.on('click', function(evt) {
    displayFeatureInfo(evt.pixel);
  });
//////////End of styling features and with mouse over color change/////////////

});

这是我的 php 文件

<?php
   $conn = new PDO('mysql:host=localhost;dbname=FarmersDB','root','admin');

   $sql = 'SELECT *, _coordinates__latitude AS x, _coordinates__longitude AS y FROM farmers';

 if (isset($_GET['bbox']) || isset($_POST['bbox'])) {
$bbox = explode(',', $_GET['bbox']);
$sql = $sql . ' WHERE x <= ' . $bbox[2] . ' AND x >= ' . $bbox[0] . ' AND y   <= ' . $bbox[3] . ' AND y >= ' . $bbox[1];
 }

$rs = $conn->query($sql);
if (!$rs) {
echo 'An SQL error occured.\n';
exit;
}

$geojson = array(
 'type'      => 'FeatureCollection',
 'features'  => array()
);


while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;

unset($properties['x']);
unset($properties['y']);
$feature = array(
    'type' => 'Feature',
    'geometry' => array(
        'type' => 'Point',
        'coordinates' => array(
            $row['x'],
            $row['y']
        )
    ),
    'properties' => $properties
);

array_push($geojson['features'], $feature);
}

header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>
php ajax openlayers-3
2个回答
0
投票

不确定你遇到了什么问题,但试试这个..你可能需要设置正确的投影并解析来自服务器的

data
响应..默认情况下投影是
EPSG:3857

  success: function(data) {
    var JSONData;
      try {
        JSONData = JSON.parse(data);
      } catch(err) {
        alert(err);
        return;
      }
      var format = new ol.format.GeoJSON();
      var features = format.readFeatures(JSONData, {
            featureProjection: 'EPSG:3857'
      });
      farmersSource.addFeatures(features);
      farmersSource.changed();
    }
   });

此外,在

var vectorSource
将项目更改为
EPSG:3857
。另一件事,您需要将
vectorloader
属性添加到您的 source.vector。例如:

 var locationSource = new ol.source.Vector({
   url: loc_url,
   format: new ol.format.GeoJSON({
    defaultDataProjection :'EPSG:3857' 
   }),
   loader: vectorLoader,
   strategy: ol.loadingstrategy.all
 });

vectorLoader 函数看起来像这样并使您对服务器进行 ajax 调用。 loader函数特别说明——在源层调用clear()时,会再次触发vector loader函数:

var vectorLoader = function(extent, resolution, projection) {
  var url = this.getUrl();
   utils.refreshGeoJson(this);
}


var utils = {
  refreshGeoJson: function(source,url) {
    var now = Date.now();
    if (typeof url == 'undefined') {
      url = source.getUrl();
    }
    url += '?t=' + now;  //Prevents browser caching if retrieving a geoJSON file
    console.info('refreshGeoJson url: ' + url);
  this.getJson(url).when({
     ready: function(response) {
     var JSONResponse;
     try {
       JSONResponse = JSON.parse(response);
     } catch(err) {
       alert(err + ' - ' + url);
       return;
     }
     var format = new ol.format.GeoJSON();
     var features = format.readFeatures(JSONResponse, {
        featureProjection: 'EPSG:3857'
     });
       source.addFeatures(features);
      source.changed();
    }
  });
},
getJson: function(url) {
     var xhr = new XMLHttpRequest(),
     when = {},
     onload = function() {
     console.log(url + ' xhr.status: ' + xhr.status);
    if (xhr.status === 200) {
     console.log('getJson() xhr: ');
     console.dir(xhr);
     console.log('getJson() xhr.response: ');
     console.dir(xhr.response);
      when.ready.call(undefined, xhr.response);
    }
    if (xhr.status === 404) {
      console.log('map file not found! url: ' + url);
    }
     },
     onerror = function() {
       console.info('Cannot XHR ' + JSON.stringify(url));
     };
      xhr.open('GET', url, true);
      xhr.setRequestHeader('cache-control', 'no-store');
      xhr.onload = onload;
      xhr.onerror = onerror;
      xhr.send(null);
      return {
        when: function(obj) { when.ready = obj.ready; }
      };
  }
};

在这里添加了很多额外内容,因为我不确定您的代码有什么问题。上面的示例非常适合我从服务器检索定期更改的 geoJSON 文件。如果调用 PHP 脚本,它应该对您同样有效,只需确保脚本根据此规范返回 geoJSON 数据:http:/ /geojson.org/geojson-spec.html


0
投票

如果有人需要为 OpenLayers v7.3.0 制作矢量图层,从数据库中提取数据,在 Laravel 项目中使用 npm 安装 OpenLayers 后,我按如下方式进行:

import {Vector as VectorSource} from 'ol/source';
import {Vector as VectorLayer} from 'ol/layer';
import GeoJSON from "ol/format/GeoJSON";

const propVectorSource = new VectorSource({
    format: new GeoJSON(),
    url: '/open-layers/get-properties',
});
const propVectorLayer = new VectorLayer({
    source: propVectorSource,
    name: 'VectorProperties',
    style: {
        'fill-color': 'rgba(248,243,185,0.2)',
        'stroke-color': '#ff8533',
        'stroke-width': 3,
    },
});
map.addLayer(propVectorLayer);

Then this url '/open-layers/get-properties' leeds to my method getProperties() where Im building the GeoJSON like so:

public function getProperties()
{
    $properties = Property::all();
    $features = [];
    foreach ($properties->toArray() as $key => $property) {

        $features[$key]['type'] = 'Feature';
        $features[$key]['geometry'] = $property['geom'];
        unset($property['geom']);
        $features[$key]['properties'] = $property;
    }

    return [
        'type' => 'FeatureCollection',
        'features' => $features
    ];
}

© www.soinside.com 2019 - 2024. All rights reserved.