OpenLayers 3 Beginner’s Guide

Creating a loader function

Open sample in a new windows

<!doctype html>
    <title>Vector Examples</title>
    <link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
    <link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
    <div id="map" class="map"></div>
    <script src="../assets/ol3/js/ol.js"></script>
    <script src=""></script>
      // a tiled raster layer as the backdrop
      var tiledRaster = new ol.layer.Tile({
        source: new ol.source.OSM()

      // styles for the vector layer
      var fill = new{
        color: 'rgba(0,0,0,0.2)'

      var stroke = new{
        color: 'rgba(0,0,0,0.4)'

      var circle = new{
        radius: 6,
        fill: fill,
        stroke: stroke

      var vectorStyle = new{
        fill: fill,
        stroke: stroke,
        image: circle

      // when loading from a features from a remote server, we need to provide
      // a loading function that handles the actual communication
      // using jQuery's ajax function, we can load the data and ask the WFS
      // server to use jsonp and send the results to the loadFeatures function
      var vectorLoader = function(extent, resolution, projection) {
        var url = '' +
            'version=1.1.0&request=GetFeature&typename=osm:builtup_area&' +
            'outputFormat=text/javascript&format_options=callback:loadFeatures' +
            '&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
          url: url,
          dataType: 'jsonp'

      // this will be called when the server data has been loaded, we can
      // use the source to read the features using its configured format
      var loadFeatures = function(response) {
        var features = vectorSource.readFeatures(response);

      // the source is configured with a format, loader function and a
      // strategy, the strategy causes the loader function to be called
      // in different ways.  With the tile strategy, it will call with
      // extents matching tile boundaries for the current zoom level
      var vectorSource = new ol.source.ServerVector({
        format: new ol.format.GeoJSON(),
        loader: vectorLoader,
        strategy: ol.loadingstrategy.createTile(new ol.tilegrid.XYZ({
          maxZoom: 19

      // a vector layer, this time with some style options
      var serverVector = new ol.layer.Vector({
        source: vectorSource,
        style: vectorStyle

      var center = ol.proj.transform([-72.6, 41.7], 'EPSG:4326', 'EPSG:3857');
      var view = new ol.View({
        center: center,
        zoom: 12
      var map = new ol.Map({
        target: 'map',
        layers: [tiledRaster, serverVector],
        view: view