1

这是一个在我的脚本中重复几次的代码,所以我想把它作为函数。我希望它是最基本的功能。此外,如果有人能给我一个例子,我会非常感谢我如何在我的代码中调用一个函数。非常感谢您!

通过代码更改的内容被加粗(为了将来的目的:我使用 OpenLayers3 从 GeoServer 调用 WFS 层):

    // format used to parse WFS GetFeature responses
    var **layer**GeojsonFormat = new ol.format.GeoJSON();

    // source
    var **layer**Source = new ol.source.Vector({
      loader: function(extent, resolution, projection) {
        var url = 'http://localhost:8080/geoserver/wfs?service=WFS&' +
            'version=1.1.0&request=GetFeature&typename=**ws**:**layer**&' +
            'outputFormat=text/javascript&format_options=callback:**layer**LoadFeatures' +
            '&srsname=EPSG:3765&bbox=' + extent.join(',') + ',EPSG:3765';
        // use jsonp: false to prevent jQuery from adding the "callback"
        // parameter to the URL
        $.ajax({url: url, dataType: 'jsonp', jsonp: false});
      },
      strategy: ol.loadingstrategy.bbox
    });

    /**
     * JSONP WFS callback function.
     * @param {Object} response The response object.
     */
    window.**layer**LoadFeatures = function(response) {
      **layer**Source.addFeatures(**layer**GeojsonFormat.readFeatures(response));
    };

   // layer
    var **layer**Layer = new ol.layer.Vector({
      source: **layer**Source,
      style: **layer**Style
    });

稍后,每个图层都必须包含在地图中,所以我还需要返回 var 的 layerLayer:

// map
var map = new ol.Map({
  target: document.getElementById('map'),
  renderer: 'canvas',
  view: olview,
  layers: [layerOneLayer, layerTwoLayer, layerThreeLayer, ...],
    logo: false
});
4

2 回答 2

0

您可以使用此功能。

function functionName(parameter1, parameter2) {
// your code
}
// call function
functionName();
于 2021-02-20T12:33:13.977 回答
0

将代码包装在一个函数中,然后像这样调用它 - someFunction()

function someFunction() {
      // format used to parse WFS GetFeature responses
      var * * layer * * GeojsonFormat = new ol.format.GeoJSON();
  // source
  var * * layer * * Source = new ol.source.Vector({
    loader: function(extent, resolution, projection) {
      var url = 'http://localhost:8080/geoserver/wfs?service=WFS&' +
        'version=1.1.0&request=GetFeature&typename=**ws**:**layer**&' +
        'outputFormat=text/javascript&format_options=callback:**layer**LoadFeatures' +
        '&srsname=EPSG:3765&bbox=' + extent.join(',') + ',EPSG:3765';
      // use jsonp: false to prevent jQuery from adding the "callback"
      // parameter to the URL
      $.ajax({
        url: url,
        dataType: 'jsonp',
        jsonp: false
      });
    },
    strategy: ol.loadingstrategy.bbox
  });

  /**
   * JSONP WFS callback function.
   * @param {Object} response The response object.
   */
  window.* * layer * * LoadFeatures = function(response) { * * layer * * Source.addFeatures( * * layer * * GeojsonFormat.readFeatures(response));
  };

  // layer
  var * * layer * * Layer = new ol.layer.Vector({
    source: * * layer * * Source,
    style: * * layer * * Style
  });
}

someFunction()
于 2017-11-03T10:54:21.147 回答