SuperMap iClient for OpenLayers

This guide will quickly get you started on SuperMap iClient for OpenLayers. You can get detailed interface parameters on the API page.

The version of OpenLayers that SuperMap iClient for OpenLayers depends on has been fully upgraded to OpenLayers 6, and also compatible with OpenLayers 5.
There is no change in the API interface, but there are new adjustments in the introduction and modular development part.
Here we mainly introduce the latest version development method, for the development method of OpenLayers 4 or lower versions, please refer to: SuperMap iClient 10i Development Manual

Preparing your page

Get OpenLayers and SuperMap iClient for OpenLayers

Before writing any code for the map, you need to import OpenLayers and SuperMap iClient for OpenLayers, including CSS file and JavaScript file. You can obtain these files in the following ways:

OpenLayers

SuperMap iClient for OpenLayers

Import

Import files

Once you've got the files, just import them with the <script> tag just like a normal JavaScript library. Here's how to import OpenLayers and SuperMap iClient for OpenLayers through the online site.

Note: In the current version, iclient-openlayers.js has been renamed to iclient-ol.js.

Create a new HTML file, include the JavaScript and CSS files in the <head> of your HTML file.

                                <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link href="https://iclient.supermap.io/web/libs/openlayers/7.5.2/ol.min.css" rel="stylesheet">
    <script type="text/javascript" src="https://iclient.supermap.io/web/libs/openlayers/7.5.2/ol.js"></script>
</head>
</html>
                            

Introduce the iclient-ol CSS file and JS file, and fill in the SuperMap iClient for OpenLayers online site address:

                                <!DOCTYPE html>
<html>
<head>
    <link href="https://iclient.supermap.io/web/libs/openlayers/7.5.2/ol.min.css" rel="stylesheet" />
    <link href='https://iclient.supermap.io/dist/ol/iclient-ol.min.css' rel='stylesheet' />
    <script type="text/javascript" src="https://iclient.supermap.io/web/libs/openlayers/7.5.2/ol.js"></script>
    <script type="text/javascript" src="https://iclient.supermap.io/dist/ol/iclient-ol.min.js"></script>
</head>
</html>
                            

npm

Before using this method, please check if the application Node.js is installed on your computer. If it is not installed, you can install it by downloading the installer . Then install SuperMap iClient for OpenLayers by entering the following command on the command line:

                                            npm install @supermapgis/iclient-ol
                                        

If you need to use v11.1.1 or earlier versions, please install @supermap/iclient-ol.

If you are using OpenLayers v4.6.5, please install @supermap/iclient-openlayers.

Import the CSS files

Create a new HTML file and import the OpenLayers CSS file and the iclient-ol CSS file into the <head> tag as follows:

                                            <link href='https://iclient.supermap.io/web/libs/openlayers/7.5.2/ol.min.css' rel='stylesheet' />
<link href='https://iclient.supermap.io/dist/ol/iclient-ol.min.css' rel='stylesheet' />
                                

Modular Development

ES6

You need to use npm to install dependencies before development, and then import the corresponding modules through ES6's import module loading syntax.

On demand:

First, install @supermapgis/babel-plugin-import:

                              npm install @supermapgis/babel-plugin-import -D
                              

Then edit .babelrc:

                                {
  "plugins": [
    ["@supermapgis/babel-plugin-import",
      {
      "libraryName": "@supermapgis/iclient-ol"
      }
    ]
  ]
}
                              

Next, if you need TileSuperMapRest, edit:

                                            import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import { TileSuperMapRest } from '@supermapgis/iclient-ol';

var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = new Map({
    target: 'map',
    view: new View({
        center: [0, 0],
        zoom: 2,
        projection: 'EPSG:4326'
    })
});
var layer = new TileLayer({
    source: new TileSuperMapRest({
        url: url,
        wrapX: true
    }),
    projection: 'EPSG:4326'
});
map.addLayer(layer);
                                

Note: import { SuperMap } from 'iclient-ol' will be deprecated

CommonJS

CommonJS is a JavaScript modular specification based on the Node.js environment. Use npm to install dependencies before development, and then introduce the corresponding modules via the require method.

                                    var Map = require('ol/Map').default;
var View = require('ol/View').default;
var TileLayer  = require('ol/layer/Tile').default;
var control = require('ol/control');
var Logo = require('@supermapgis/iclient-ol').Logo;
var TileSuperMapRest = require('@supermapgis/iclient-ol').TileSuperMapRest;

var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = new Map({
    target: 'map',
    controls: control.defaults({attributionOptions: {collapsed: false}})
        .extend([new Logo()]),
    view: new View({
        center: [0, 0],
        zoom: 2,
        projection: 'EPSG:4326'
    })
});
var layer = new TileLayer({
    source: new TileSuperMapRest({
        url: url,
        wrapX: true
    }),
    projection: 'EPSG:4326'
});
map.addLayer(layer);
                                        

AMD

The following example uses the RequireJS library to implement; Download ol.js and iclient-ol.js through " Get OpenLayers and SuperMap iClient for OpenLayers " and place them in the directory where the entry master file specified by RequireJS is located.

  Import all modules

                                            
require(['js/ol.js'], function(ol) {
    window.ol = ol;
    require(['js/iclient-ol.js'], function() {
        var url = 'https://iserver.supermap.io/iserver/services/map-world/rest/maps/World';
        var map = new ol.Map({
            target: 'map',
            controls: ol.control
                .defaults({ attributionOptions: { collapsed: false } })
                .extend([new ol.supermap.control.Logo()]),
            view: new ol.View({
                center: [0, 0],
                zoom: 2,
                projection: 'EPSG:4326'
            })
        });
        var layer = new ol.layer.Tile({
            source: new ol.source.TileSuperMapRest({
                url: url,
                wrapX: true
            }),
            projection: 'EPSG:4326'
        });
        map.addLayer(layer);
    });
});
                                        

CMD

The following example uses the SeaJS library to implement; Download ol.js and iclient-ol.js through " Get OpenLayers and SuperMap iClient for OpenLayers " and place them in the directory where the entry master file specified by SeaJS is located.

                                                define(function(require, exports, module) {
    require('./ol.js');
    require('./iclient-ol.js');

    var url = 'https://iserver.supermap.io/iserver/services/map-world/rest/maps/World';
    var map = new ol.Map({
        target: 'map',
        controls: ol.control
            .defaults({ attributionOptions: { collapsed: false } })
            .extend([new ol.supermap.control.Logo()]),
        view: new ol.View({
            center: [0, 0],
            zoom: 2,
            projection: 'EPSG:4326'
        })
    });
    var layer = new ol.layer.Tile({
        source: new ol.source.TileSuperMapRest({
            url: url,
            wrapX: true
        }),
        projection: 'EPSG:4326'
    });
    map.addLayer(layer);
});
                                            

Package configuration

Since SuperMap iClient for OpenLayers uses ES6 syntax, in order to be compatible with browsers that do not support ES6 syntax, you need to do some configuration during the packaging process, including syntax conversion.

The packaged configuration here is for ES6 and CommonJS modular development, and for projects developed for AMD and CMD modules, there is no need to utilize packaging tools.

Take webpack4 as an example. Since the different package managers will cause the structure of the installation package to be different, the following examples describe the npm and cnpm configurations:

If you use npm install or cnpm install --by=npm to install dependencies, you need to add the following configuration items in the webpack.config.js.

                                            module: {
    rules: [{
        // Convert ES6 syntax to ES5 using babel-loader
        test: /\.js$/,
        loader: 'babel-loader',
        options: {
            presets: ['@babel/preset-env']
        }
    }]
}
                                    

If you use cnpm install to install dependencies, you need to add the following configuration items in the webpack.config.js.

                                            module: {
    rules: [{
        // Convert ES6 syntax to ES5 using babel-loader
        test: /\.js$/,
        loader: 'babel-loader',
        options: {
            presets: ['@babel/preset-env']
        }
    }]
}
                                        

Creating a map

Map published by SuperMap iServer

In the Preparing your page section, you have created a new html page, and continue to add following code to create a map in your page:

Taking the world map published in SuperMap iServer as an example, add code to <script>, and initialize the map information:

                                    var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
// Initialize the map information
var map = new ol.Map({
    target: 'map',
    controls: ol.control.defaults({attributionOptions: {collapsed: false}})
        .extend([new ol.supermap.control.Logo()]),
    view: new ol.View({
        center: [0, 0],
        zoom: 2,
        projection: 'EPSG:4326'
    })
});
// Add layers
var layer = new ol.layer.Tile({
    source: new ol.source.TileSuperMapRest({
        url: url,
        wrapX: true
    }),
    projection: 'EPSG:4326'
});
map.addLayer(layer);See full example code »
                                        

Enjoy the result.

Third-party map

SuperMap iClient for OpenLayers encapsulates a variety of Internet map information, such as Baidu maps, Tianditu, and so on. Taking the Tianditu as an example, SuperMap iClient for OpenLayers provides tiandituSource, codes as following:

                                        var map = new ol.Map({
target: 'map',
controls: ol.control.defaults({attributionOptions: {collapsed: false}})
    .extend([new ol.supermap.control.Logo()]),
view: new ol.View({
    center: [116.402, 39.905],
    zoom: 5,
    projection: "EPSG:4326"
}),
// Add Tianditu Layer
layers: [
    new ol.layer.Tile({
        source: new ol.source.Tianditu({
            layerType: 'ter',
            projection: "EPSG:4326"
        });
    }),new ol.layer.Tile({
        source: new ol.source.Tianditu({
            layerType: 'ter',
            isLabel: true,
            projection: "EPSG:4326"
        });
    })];
});See full example code »
                            

Enjoy the result.

Setting map projection

SuperMap iClient for OpenLayers supports multi-projection by setting the projection parameter of the view property in the map.

                                var map = new ol.Map({
    view: new ol.View({
        projection: 'EPSG:4326'
    });
});
                            

In addition to supporting EPSG code strings, projection parameter also supports custom projection parameters. You can set custom projection parameters through the ol.proj.Projection class.

                                    var swissProjection = new ol.proj.Projection({
    code: 'EPSG:21781',
    // Extent is used to determine the zoom level
    // Refer to https://epsg.io/ for projection extent
    extent: [485869.5728, 76443.1884, 837076.5648, 299941.7864],
    units: 'm'
});
ol.proj.addProjection(swissProjection);
var map = new ol.Map({
    view: new ol.View({
        projection: swissProjection
    });
});
                            

For parameter definitions of various projections, you can refer to https://spatialreference.org. If there is a definition, you can search for and view its projection parameters, such as EPSG: 21418, and its projection parameters are https://spatialreference.org/ref/epsg/21418/proj4/.

Adding controls

By adding controls to the map, you can achieve interactive operations such as zooming in, zooming out, and layer switching. Commonly used controls:

Control Class name Introduction
Eagle-eye map ol.control.OverviewMap The default is in the lower right corner of the map
Zoom ol.control.Zoom The default is in the top left corner of the map
Scale ol.control.ScaleLine The default is at the bottom left corner of the map
Layer switching ol.control.LayerSwitcher The default is in the top right corner of the map
Swipe ol.control.Attribution Swipe appears in the center of the map by default

When adding a control, should initialize the map first, and then add the control to the map by using the addTo() method, for example:

Zoom control

                                    scaleControl = new ol.control.ScaleLine();
map.addControl(scaleControl);See full example code »
                                

Enjoy the result.

Layer switch control:

                                    var layerSwitcher = new ol.control.LayerSwitcher({});
map.addControl(layerSwitcher);See full example code »
                                

Enjoy the result.

Using vector tiles

Vector tiles are to organize and define vector data through different description files, analyze data in real time and complete rendering on the client. SuperMap iServer provides vector tile layers, namely ol.supermap.tiledVectorLayer(url, options).

  • ur:Map service address
  • mapJSONObj:Map JSON object (a map object in JSON format returned by the getMapInfor() method)

Vector tiles example: using default style

                        new ol.supermap.MapService(url).getMapInfo(function (serviceResult) {
// Vector tiles style parameters object
var stylesOptions = {
    url: url,
    view: map.getView()
};
// Create tiles style object
var vectorTileStyles = new ol.supermap.VectorTileStyles(stylesOptions);
// Obtain tiles parameters object by map infomation
var vectorTileOptions = ol.source.VectorTileSuperMapRest.optionsFromMapJSON(url, serviceResult.result);
// Add vector tile layer
var vectorLayer = new ol.layer.VectorTile({
    source: new ol.source.VectorTileSuperMapRest(vectorTileOptions),
    style: vectorTileStyles.getFeatureStyle
});
map.addLayer(vectorLayer);See full example code »
                                    

Enjoy the result.

Drawing symbols and graphics

The graphics drawing methods of OpenLayers include basic drawing, handwriting drawing, and capturing drawing. The drawing of geometric shapes generally includes the drawing of points, lines, polygons, and circles.

Basic drawing

First add a button for geometry drawing on the sample interface and set its style. The following code takes the drawing point as an example.

                                        // Set the drawing control interface
<div class="btn-group">
    <button id="drawPoint" value='Point' type="button" class="btn btn-default">Draw point</button>
</div>
                                    

In this case, first load a vector layer drawing layer in the map container and create a drawing control object (ol.interaction.Draw), then add the drawing graphic control by calling the addInteraction() method, and then drawing layers according to the set geometry. The core code for drawing a layer is as follows:

                                        // Get the type you need to draw
var buttons = $('.btn-group').children();
// Instantiate a vector layer as a drawing layer
var vector = new ol.layer.Vector({
    source: source
});
map.addLayer(vector);
// Create a drawing control object
var draw = new ol.interaction.Draw({
    source: source,
    type: buttons[key].value,
    snapTolerance: 20
});
// Add drawing control
map.addInteraction(draw); See full example code »
                                    

Enjoy the result.

Handwriting drawing

Handwriting drawing is holding down the left button and draw the graph at will, and release it to finish drawing. The key code is as follows:

                                    // Get the type you need to draw
var buttons = $('.btn-group').children();
// Create a vector layer as a drawing layer
var vector = new ol.layer.Vector({
    source: source
});
map.addLayer('vector');
// Create a handwritten graphic drawing control
var draw = new ol.interaction.Draw({
    source: source,
    type: buttons[key].value,
    snapTolerance: 20,
    freehand: true // Handwriting drawing configuration
});
// Add handwriting drawing control
map.addInteraction(draw);See full example code »
                    

Enjoy the result.

Capture drawing

Capture drawing means that the mouse enters a certain tolerance range of an already drawn point when drawing, and the mouse is absorbed to the position of the already drawn point.

                                            var source = new ol.source.Vector({wrapX: false});
// Create a capture drawing control
var snap = new ol.interaction.Snap({
    source: source
});
// Add capture drawing control
map.addInteraction(snap);See full example code »
                            

Enjoy the result.

Area and distance measurement

SuperMap iClient for OpenLayers supports area and distance measurement.

Distance measurement

Here are the steps to create distance measurement function:

1. Construct service parameters class

The measurement service parameter class provides the information required by the service request, which provides the query parameter encapsulation of the measurement. Parameters provided include geometry and unit, which are used to define the geometric objects and units of the measurement, the code as follows:

                                            // Set the parameters for measurement service
var distanceMeasureParam = new ol.supermap.MeasureParameters(feature.getGeometry());
// Set the vector object ({line} or {Polygon}) to measure, and geometry can obtain by initialization
distanceMeasureParam.geometry= geometry;
                                        

2. Construct the service class and send the request

The measurement service class is responsible for sending requests to the server and getting the query results returned. The service class needs to specify service parameters such as URL, send request information to the server, and then request the complete event via the listener service. The results can be obtained from the event service data class, and handled according to the requirements. Please refer to the following code:

                                // Submit service request, pass the service query parameters, get the returned results and process them according to user needs
var url="https://iserver.supermap.io/iserver/services/map-world/rest/maps/World"; // Service access address
new ol.supermap.MeasureService(url, {measureMode: ""}).measureDistance(distanceMeasureParam).then(function (serviceResult) {
    function doSomething(serviceResult);
        // Get the results returned by the server
        var result=serviceResult.result;
});See full example code »
                                    

Enjoy the result.

Area measurement

1. Instantiate the measurement service constructor. The code is as follows:

                                var areaMeasureParam = new ol.supermap.MeasureParameters(feature.getGeometry());
                            

2. Call the measurement function

Call the measurement function(ol.supermap.MeasureService.measureArea), and get the return result, the code is as follows:

                                // Set area measurement service parameters
var areaMeasureParam = new ol.supermap.MeasureParameters(feature.getGeometry());
new ol.supermap.MeasureService(url).measureArea(areaMeasureParam).then(function (serviceResult) {
    // Get the result from server
    var result = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Feature query

The feature query functions supported by SuperMap iClient for OpenLayers mainly include:

  • Query by specifying ID
  • Query by specifying conditions
  • Query by specifying rectangle bounds
  • Query by specifying arbitrary geometric range
  • Distance query
  • Buffer query
  • Query grid information
  • Query field information

Query by specifying ID

Query geographic features with specified IDs in a dataset and display the results on the client. This example queries geographic features with specified IDs in the World dataset.

Use the ol.supermap.FeatureService interface to query geospatial features with IDs 233 and 234 in the dataset "World:Countries".

                                        url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
var idsParam = new ol.supermap.GetFeaturesByIDsParameters({
    IDs: [233, 234],
    datasetNames: ["World:Countries"]
});
// Send a request to the server and get the result
new ol.supermap.FeatureService(url).getFeaturesByIDs(idsParam).then(function (serviceResult) {
    var features = serviceResult.result.features;
});See full example code »
                                    

Enjoy the result.

Query by specifying SQL conditions

Query by specifying SQL, you can find vector features that match the SQL condition in the specified dataset collection and display them in the client. This example is: Querying the elements of the specified SMID in the World data service.

Use the ol.supermap.FeatureService interface to query vector features with "SMID = 234" in the dataset "World:Countries".

                                        var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
var sqlParam = new ol.supermap.GetFeaturesBySQLParameters({
    queryParameter: {
        name: "Countries@World",
        attributeFilter: "SMID = 234"
    },
    datasetNames: ["World:Countries"]
});
// Send a request to the server and get the result
new ol.supermap.FeatureService(url).getFeaturesBySQL(sqlParam).then(function (serviceResult) {
    var features = serviceResult.result.features;
});See full example code »
                                    

Enjoy the result.

Query by specifying rectangle bounds

You can find vector features in the specified dataset collection that match the rectangular extent and display them in the client. This example queries the World Data Service for features that specify a range of rectangles.

Use the ol.supermap.Feature Service interface to find vector features that match this rectangular extent in the dataset "World:Capitals".

                                        var polygon = new ol.geom.Polygon([[[-20, 20], [-20, -20], [20, -20], [20, 20], [-20, 20]]]);
var polygonSource = new ol.source.Vector({
    features: [new ol.Feature(polygon)],
    wrapX: false
});
var boundsParam = new ol.supermap.GetFeaturesByBoundsParameters({
    datasetNames: ["World:Capitals"],
    bounds: polygon.getExtent()
});
// Send a request to the server and get the result
new ol.supermap.FeatureService(url).getFeaturesByBounds(boundsParam).then(function (serviceResult) {
    // Get returned features data
    var features = serviceResult.result.features;
});See full example code »
                                

Enjoy the result.

Query by specifying arbitrary geometric range

You can find vector features in the specified dataset collection that match the arbitrary geometric range and display them in the client. This example queries the features in World data service by specifying an arbitrary geometry range.

Use the interface ol.supermap.FeatureService to query the vector features in this geometric range using the intersecting spatial query mode in the "World:Countries" dataset.

                                    var polygon = new ol.geom.Polygon([[[0, 0], [-10, 30], [-30, 0], [0, 0]]])
var geometryParam = new ol.supermap.GetFeaturesByGeometryParameters({
    datasetNames: ["World:Countries"],
    geometry: polygon,
    spatialQueryMode: "INTERSECT"
});
// Create a query instance
new ol.supermap.FeatureService(url).getFeaturesByGeometry(geometryParam).then(function (serviceResult) {
    // Get returned features data
    var features = serviceResult.result.features;
});See full example code »
                               

Enjoy the result.

Distance query

Distance query, which finds a vector feature that meets the certain distance requirement in specified layer in the map service, and displays results in the client. This example is: Querying vector features that match distances requirement in the World Maps service.

Using ol.supermap.QueryServicethe interface to find the vector feature in the layer "Capitals@World.1" whose distance from the specified point is 10 degrees (map coordinate units).

                                    // Add a query center point
point = new ol.geom.Point([104, 30]);
var feature = new ol.Feature(point);
var param = new ol.supermap.QueryByDistanceParameters({
    queryParams: {name: "Capitals@World.1"},
    distance: 10, // The unit of distance is the same as the coordinate system of the object, here is degree
    geometry: point
});
// Create a distance query instance
new ol.supermap.QueryService(url).queryByDistance(param).then(function (serviceResult) {
    // Get returned features data
    var features = serviceResult.result.features;
});See full example code »
                                

Enjoy the result.

Buffer query

Buffer query is to find vector elements that match the buffer requirement in a specified set of datasets in the data service, displays it in the client. This example is: Querying the features of the specified buffer in the World Data Service.

Use the ol.supermap.FeatureService interface to find the vector elements whose buffer range is 10 degrees (map coordinate units) in the dataset "World:Capitals".

                                    var polygon = new ol.geom.Polygon([[[-20, 20], [-20, -20], [20, -20], [20, 20], [-20, 20]]]);
var bufferParam = new ol.supermap.GetFeaturesByBufferParameters({
    datasetNames: ["World:Capitals"],
    bufferDistance: 30, // The unit of bufferDistance is the same as the coordinate system of the object, here is degree
    geometry: polygon
});
// Create a buffer query instance
new ol.supermap.FeatureService(url).getFeaturesByBuffer(bufferParam).then(function (serviceResult) {
    // Get returned features data
    var features = serviceResult.result.features;
});See full example code »
                                

Enjoy the result.

Query grid information

Query grid information is find the pixel value information corresponding to a geographical location in the specified dataset and display it in the client.

Use the ol.supermap.GridCellInfosService interface to query grid information in the dataset "WorldEarth". The sample code is as follows:

                                    var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
map.on("click", function (evt) {
    // Get the (x,y) of the current click
    var x = evt.coordinate[0];
    var y = evt.coordinate[1];
    if (x < -180.0 || x > 180.0 || y < -90 || y > 90) {
        return;
    }
    // Set the parameter information of the raster query
    var getGridCellInfosParam = new ol.supermap.GetGridCellInfosParameters({
        dataSourceName: "World",
        datasetName: "WorldEarth",
        X: x,
        Y: y
    });
    // Create a raster query instance
    new ol.supermap.GridCellInfosService(url).getGridCellInfos(getGridCellInfosParam).then(function (serviceResult) {
        if (!serviceResult.result) {
            return;
        }
        // Get the data returned by the server
        var result = serviceResult.result;
    });
});See full example code »
                                

Enjoy the result.

Query field information

Query field information, that is, find the vector elements with specified information in the specified dataset collection, and display them in the client. This example is: Querying the features of the specified field in the World Data Service.

Use ol.supermap.FieldService interface to query the field information of the field "SmID" in the dataset "continent_T". And count SmID in the dataset to find the average, maximum, minimum and so on.

                                    var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data"
var param = new ol.supermap.FieldParameters({
    datasource: "World",
    dataset: "continent_T"
});
var fieldName = 'SmID';
// Create a field query instance
new ol.supermap.FieldService(url).getFields(param).then(function (serviceResult) {
    fieldStatistic(fieldName);
});
// Query a specified field
function fieldStatistic(fieldName) {
    var param = new ol.supermap.FieldStatisticsParameters({
        datasource: currentData.dataSourceName,
        dataset: currentData.dataSetName,
        fieldName: fieldName,
        statisticMode: [
            ol.supermap.StatisticMode.MAX,
            ol.supermap.StatisticMode.MIN,
            ol.supermap.StatisticMode.SUM,
            ol.supermap.StatisticMode.AVERAGE,
            ol.supermap.StatisticMode.STDDEVIATION,
            ol.supermap.StatisticMode.VARIANCE
        ]
    });
    // Send a request to the server
    new ol.supermap.FieldService(dataURL).getFieldStatisticsInfo(param, function (serviceResult) {
        // Get the data returned by the server
        var result = serviceResult.result;
    });
}See full example code »
                                

Enjoy the result.

Feature editing

Feature editing, including the editing of points, lines, polygon, etc., such as line type, color, line width, etc. If you don't have a custom style set, the interactive controls would drawn with the default style.

                                            // Instantiate feature editing parameter class
var addFeatureParams = new ol.supermap.EditFeaturesParameters({
    features: pointFeature,
    dataSourceName: "World",
    dataSetName: "Capitals",
    editType: "add",
    returnContent: true
});
// Create a feature editing service, url is supermap iserver data service
var editFeaturesService = new ol.supermap.FeatureService(url);
editFeaturesService.editFeatures(addFeatureParams).then(function (serviceResult) {
    // Get returned data
    var result = serviceResult.result;
});See full example code » 
                            

Enjoy the result.

Thematic map

In cartography, those map that highten one or more elements or phenomena, and or concentrates on representing one theme is called a thematic map. In SuperMap, the thematic map is a symbolic display of the map layer, that is, graphically representing a certain aspect of the feature element using various graphic rendering styles (size, color, line type, fill, etc.). The thematic map can be created directly based on the API of the GIS client, or it can be created by the GIS server by invoking the back end map service. The way of making thematic map by the server side has relatively higher performance and higher efficiency of drawing; the thematic map s produced by the client can introduce the latest front-end technology to achieve more intuitive and beautiful display effects and interactive effects.

Server thematic map

The Server thematic map is made by the server, that is, the client sends the parameters to the server, such as the name of the dataset, the style and so on. The server makes the thematic map according to the parameters, returns the map to the client, and displays it by the client.

Taking the dot density thematic maps as an example.

The dot density thematic map uses the same point of certain size and shape to represent the distribution of the phenomenon, the quantitative characteristics and the distribution density. The number of points and the meaning they represent are determined by the content of the map. The dot density thematic map uses the number or intensity of points to reflect the theme values corresponding to a region or range.

                                // Instantiate dot density map
var themeDotDensity = new ol.supermap.ThemeDotDensity({
    dotExpression: "Pop_1994",
    value: 5000000,
    style: new ol.supermap.ServerStyle({
        markerSize: 3,
        markerSymbolID: 12
    })
});
// Thematic map parameter class. This class stores the parameters needed to create a topic, including data sources, dataset names, and thematic map objects.
var themeParameters = new ol.supermap.ThemeParameters({
    themes: [themeDotDensity],
    // An array of datasets used to create thematic maps, required
    datasetNames: ["Countries"],
    // An array of datasources used to create thematic maps, required
    dataSourceNames: ["World"]
});
// Thematic map service class. The thematic map results are obtained by the listener function parameters of the events supported by the class.
new ol.supermap.ThemeService(url).getThemeInfo(themeParameters).then(function (serviceResult) {
    var result = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Client thematic map

The client thematic map is performing corresponding calculations on the client based on the shape and attribute of the data, and assigns different drawing styles through the feature layer or any layer and displays the thematic map on the client.

The thematic map supported by SuperMap iClient for OpenLayers include:

  • unique value thematic map
  • Range thematic map
  • Graduated symbols thematic map
  • Label thematic map
  • Statistics thematic map
unique value thematic map

The unique value map is to classify the elements with the same thematic value into one class, and set a rendering style for each class, such as color or symbol, etc. The features with the same thematic value use the same rendering style to distinguish different category.

The following codes shows how SuperMap iClient for OpenLayers build a unique value thematic map object:

                                // The resource of unique value thematic map layers
var themeSource = new ol.source.Unique("ThemeLayer", {
    // Thematic map ID
    map: map,
    attributions: " ",
    // Thematic map style
    style: {
        shadowBlur: 3,
        shadowColor: "#000000",
        shadowOffsetX: 1,
        shadowOffsetY: 1,
        fillColor: "#FFFFFF"
    },
    // Whether to enable the hover event
    isHoverAble: true,
    // Triggered style when hover event is enabled
    highlightStyle: {
        stroke: true,
        strokeWidth: 2,
        strokeColor: 'blue',
        fillColor: "#00F5FF",
        fillOpacity: 0.2
    },
    // Specify to create the thematic map field
    themeField: "LANDTYPE",
});
// Create a unique value map layer
var themeLayer = new ol.layer.Image({
    source: themeSource
});
                            

unique value map type and color configuration, the code is as follows:

                                Unique value thematic type style group
styleGroups: [
    {
        value: "草地",
        style: {
            fillColor: "#C1FFC1"
        }
    },
    {
        value: "城市",
        style: {
            fillColor: "#CD7054"
        }
    },
    {
        value: "灌丛",
        style: {
            fillColor: "#7CCD7C"
        }
    }
];See full example code »
                            

Enjoy the result.

Range thematic map
In the range thematic map, theme values are divided into multiple range items in accordance with a range mode, and factors are assigned to one of the range items according to their theme value, the factors in the same range item use the same color, filling, symbol style etc, to display. The theme variable based by range thematic map must be numeric, range thematic map is commonly used to reflect the amount or degree characteristics of continuous distribution phenomenon, such as the distribution of precipitation, the distribution of soil erosion intensity, etc.

SuperMap iClient for OpenLayers implements the range thematic map by the following code:

                                // Resource of the range thematic map
var themeSource = new ol.source.Range("ThemeLayer",{
    map: map,
    // Copyright Information
    attributions: " ",
    // Range thematic map style
    style: {
        shadowBlur: 16,
        shadowColor: "#000000",
        fillColor: "#FFFFFF"
    },
    // Whether to enable hover event
    isHoverAble: true,
    // Triggered style when hover event is enabled
    highlightStyle: {
        stroke: true,
        strokeWidth: 4,
        strokeColor: 'blue',
        fillColor: "#00EEEE",
        fillOpacity: 0.8
    },
     // Specify to create the thematic map field
    themeField: "POP_DENSITY99",
    // Configure a range thematic type style group
    styleGroups: [
        {
            start: 0,
            end: 0.02,
            style: {
                color: '#FDE2CA'
            }
        },
        {
            start: 0.02,
            end: 0.04,
            style: {
                color: '#FACE9C'
            }
        }
    ];
});
// Create a range thematic layer
var themeLayer = new ol.layer.Image({
    source: themeSource
});See full example code »
                            

Enjoy the result.

Graduated symbols thematic map

The graduated symbols thematic map is represented on the map by a set of grade symbols according to a certain number of characteristics of each element based on certain classification method, so as to present the quantity relative relationship between the elements.

SuperMap iClient for OpenLayers implements the graduated symbols thematic map by the following code:

                                var themeSource = new ol.source.RankSymbol("RankSymbolLayer", "Circle",
    {
        map: map,
        attributions: " ",
        themeField: "CON2009",
        // Configure chart parameters
        symbolSetting: {
            // Required parameter
            codomain: [0, 40000], // The range of values allowed for the graphic display. Data outside this range will not be graphed.
            // The maximum radius of Circular, default is 100
            maxR: 100,
            // The minmum radius of Circular, default is 0
            minR: 0,
            // The style of circular
            circleStyle: {fillOpacity: 0.8},
            // The color to fill in the symbol thematic map
            fillColor: "#FFA500",
            // Hover style of thematic map
            circleHoverStyle: {fillOpacity: 1}
        }
});
// Create a graduated symbols thematic layer
var themeLayer = new ol.layer.Image({
    source: themeSource
});See full example code »
                            

Enjoy the result.

Label thematic map

Some marking is essential to the map, not only to help users to better distinguish the features, but also to show some important attributes of the features, such as administrative divisions, rivers, organs, names of tourist attractions, elevation of the contour lines, etc. In SuperMap, users can easily implement map annotation by making label thematic map.

The mainly code that SuperMap iClient for OpenLayers used to implement the label thematic map is as follows:

                                // Label thematic map resource
var themeSource = new ol.source.Label("labelThemeLayer", {
    map: map,
    attributions: " ",
    // The style of label thematic map
    style: new ol.supermap.ThemeStyle({
        labelRect: true,
        fontColor: "#000000",
        fontWeight: "bolder",
        fontSize: "18px",
        fill: true,
        fillColor: "#FFFFFF",
        fillOpacity: 1,
        stroke: false,
        strokeColor: "#8B7B8B"
    }),
    // Specify to create the thematic map field
    themeField: "aqi",
    // Label thematic map type style group
    styleGroups: [
        {
            start: 0,
            end: 51,
            style: {
                fillColor: "#6ACD06",
                fontSize: "17px"
            }
        }, {
            start: 51,
            end: 101,
            style: {
                fillColor: "#FBD12A",
                fontSize: "19px"
            }
        },
    ];
});
// Create a label thematic map layer
var themeLayer = new ol.layer.Image({
    source: themeSource
});See full example code »
                            

Enjoy the result.

Statistics thematic map

Statistics thematic map reflect the size of their corresponding theme values by drawing statistics graphs for each factor or record. The statistics thematic map can be based on multiple variables, reflecting multiple attributes, that is, the values of multiple thematic variables can be plotted on a statistics graph. Statistics thematic maps can be used to form horizontal and vertical comparisons between regions themselves and each region. It is usually used in maps with relevant quantitative characteristics, such as grain output, GDP and population of different regions for many years, and passenger volume and subway flow at different times.

In a statistics thematic map, each region has a statistical graph showing the value of each theme in the region. There are many forms of representation. Currently available types are: histogram, line chart, 3D column chart, dot chart, pie chart, ring chart.

The mainly code that SuperMap iClient for OpenLayers used to implement the statistics thematic map is as follows:

                                // The configuration of the histogram and the 3D histogram
var chartsSettingForBarAddBar3DCommon = {
    width: 260,
    height: 120,
    codomain: [0, 40000],   // The range of values allowed to be shown in the chart, data outside this range will not be displayed
    xShapeBlank: [15, 15, 15],
    axisYTick: 4,
    axisYLabels: ["4万", "3万", "2万", "1万", "0"],           // The Content of Y axis label
    axisXLabels: ["09年", "10年", "11年", "12年", "13年"],   //  The Content of X axis label
    backgroundRadius: [5, 5, 5, 5],
    backgroundStyle: {      // Parameters of fillet in background frame
        fillColor: "#d1eeee",
        shadowBlur: 12,
        shadowColor: "#d1eeee"
    }
};
// Chart configuration of point and line
var chartsSettingForPointOrLine = {
    width: 220,
    height: 100,
    codomain: [0, 40000],
    xShapeBlank: [10, 10],
    axisYTick: 4,
    axisYLabels: ["4万", "3万", "2万", "1万", "0"],
    axisXLabels: ["09年", "10年", "11年", "12年", "13年"],
    backgroundStyle: {fillColor: "#d1eeee"},
    backgroundRadius: [5, 5, 5, 5],
    useXReferenceLine: true,
    pointStyle: {
        pointRadius: 5,
        shadowBlur: 12,
        shadowColor: "#D8361B",
        fillOpacity: 0.8
    },
    pointHoverStyle: {
        stroke: true,
        strokeColor: "#D8361B",
        strokeWidth: 2,
        fillColor: "#ffffff",
        pointRadius: 4
    },
};

// Configuration of pie chart and ring chart
var chartsSettingForPieOrRing = {
    width: 240,
    height: 100,
    codomain: [0, 40000],       // The range of values allowed to be shown in the chart, data outside this range will not be displayed
    sectorStyle: {fillOpacity: 0.8},      // The style of the bar (representing the value of the field value) in the histogram
    sectorStyleByFields: [
        {fillColor: "#FFB980"},
        {fillColor: "#5AB1EF"},
        {fillColor: "#B6A2DE"},
        {fillColor: "#2EC7C9"},
        {fillColor: "#D87A80"}],
    sectorHoverStyle: {fillOpacity: 1},
    xShapeBlank: [10, 10, 10],      // Blank spacing parameter in the horizontal direction
    axisYLabels: ["4万", "3万", "2万", "1万", "0"],         // The Content of Y axis label
    axisXLabels: ["09年", "10年", "11年", "12年", "13年"],         // The Content of X axis label
    backgroundStyle: {fillColor: "#CCE8CF"},        // The style of background
    backgroundRadius: [5, 5, 5, 5],        // Parameters of background frame fillet
};

// Set graphThemeLayer option parameters
var themeLayerOptions = {
    map: map,
    attributions: " ",
    themeFields: ["CON2009", "CON2010", "CON2011", "CON2012", "CON2013"],
    opacity: 0.9,
    chartsSetting: {},
};
// Create a statistic thematic map source
var themeSource = new ol.source.Graph("BarLayer", "Bar", themeLayerOptions);
// Create a statistic thematic map layer
var themeLayer = new ol.layer.Image({
    source: themeSource
});See full example code » 
                            

Enjoy the result.

Spatial analysis

Spatial analysis is a spatial data analysis technology based on the location and morphological features of geographic objects. The purpose of spatial analysis is to extract and transmit spatial information. The spatial analysis functions supported by SuperMap iClient for OpenLayers include:

  • Buffer analysis
  • Thiessen polygon
  • Overlay analysis
  • Min distance calculation
  • Surface analysis
  • Dynamic segmentation
  • Route calculate measure
  • Route locator point
  • Route locator line
  • Interpolation analysis
  • Grid algebraic aalculation
  • Terrain slope calculation
  • Terrain aspect calculation
  • Terrain curvature calculation
  • Terrain cut and fill calculation
  • Kernel density analysis

Buffer Analysis

Buffer analysis is an analytical method that automatically establishes a range of regions of a certain width based on the specified distance around the point, line, and polygon features. For example, in environmental governance, a certain width is often drawn around polluted rivers to indicate contaminated areas. At airports, a range of areas are often zoned around a non residential area due to health needs.

Here we create a round buffer with the buffer radius of 10 meters around a road for Changchun data.

Set parameters for buffer analysis, set buffer analysis common parameters

                                // Set parameters for buffer analysis
var dsBufferAnalystParameters = new ol.supermap.DatasetBufferAnalystParameters({
    // The dataset name in the datasource used for buffer analysis
    dataset: "RoadLine2@Changchun",
    filterQueryParameter: new ol.supermap.FilterParameter({
        attributeFilter: "NAME='Tuanjie Road'"
    }),
    // Set buffer analysis common parameters
    bufferSetting: new ol.supermap.BufferSetting({
        // The buffer endpoint enumeration values, including FLAT and ROUND
        endType: ol.supermap.BufferEndType.ROUND,
        // Left radius
        leftDistance: {value: 10},
        // Right radius
        rightDistance: {value: 10},
        // The number of the line segments at the circular arc
        semicircleLineSegment: 10
    })
});
                            

Set the buffer analysis service object, which is used to pass parameters specified at the client side to the server side and receive the data from returned from the server. When a request has been sent to the server and the server has returned the result successfully, the user can handle the results of buffer analysis from the server.

                                var serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst"
// Define buffer analysis service
new ol.supermap.SpatialAnalystService(serviceUrl).bufferAnalysis(dsBufferAnalystParameters).then(function (serviceResult) {
    // Get the results returned from the server
    var featuers = serviceResult.result.recordset.features;
});See full example code »
                            

Enjoy the result.

Thiessen polygon

Dutch meteorologist A.H.Thiessen proposed a method of calculating average precipitation based on the precipitation measurements at discretely distributed meteorological stations. In the method, all the neighboring stations are connected to form a series of triangles. Then the perpendicular bisectors of the triangle sides can be drawn. For each station, the bisectors surrounding it form a polygon. The precipitation in the polygon region can then be represented by the precipitation measured at that station, which is also the only station within the polygon. This polygon is named Thiessen polygon. The Thiessen polygon, also known as the Voronoi diagram, consists of a set of continuous polygons that form a vertical bisector that connects the lines of two adjacent points.

The characteristics of Thiessen polygons:

  • Every Thiessen polygon contains only one discrete point;
  • For any location in a Thiessen polygon, the discrete point associated with that polygon is the closest one among all the discrete points;
  • The points located on a side of a Thiessen polygon have equal distance to the two discrete points defining that side.

The interface of the Thiessen polygon is used as follows:

Taking the dataset Thiessen polygon as an example, the Thiessen polygon service object is set up to pass the client's Thiessen polygon service parameters to the server, and receive the result data of the Thiessen polygon analysis returned by the server.

                                var serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst";
// Set the parameters for the Thiessen polygon analysis
var dThiessenAnalystParameters = new ol.supermap.DatasetThiessenAnalystParameters({
    dataset: "Factory@Changchun"
});
// Define Thiessen polygon analysis
new ol.supermap.SpatialAnalystService(serviceUrl).thiessenAnalysis(dThiessenAnalystParameters).then(function (serviceResult) {
    // Get the returned features data
    var features = serviceResult.result.regions;
})See full example code »
                            

Enjoy the result.

Overlay Analysis

Overlay analysis is a very important spatial analysis function in GIS. It refers to the process of generating new datasets through a series of set operations on two datasets under the unified spatial Reference system, which aims to extract the new spatial geometry information needed by the user via processing or analyzing spatial data. At the same time, the various attribute information of the data will be processed by the overlay analysis.

At present, overlay analysis is widely used in resource management, urban construction assessment, land management, agriculture, forestry, animal husbandry, statistics and other fields. The role of overlay analysis in various fields:

  • Resource management is mainly used in the fields of agriculture and forestry to solve the problems of distribution, change and statistics of various resources.
  • Urban construction assessment should be used to analyze the development and change of urban population, economy and construction, and the trend and law of the change.
  • Land and cadastre management involves the change of land use nature, the change of plot boundary and the change of cadastral ownership, which can be accomplished efficiently with high quality under the help of GIS overlay analysis.
  • Ecological and environmental management evaluation is used for regional ecological planning evaluation, environmental status assessment, environmental impact assessment, pollutant reduction and allocation of decision-making support, etc.
  • Geoscience research and application is used for topographic analysis, watershed analysis, land use research, economic geography research, spatial statistical analysis, cartography, etc.

Here we overlay the administrative boundary of Beijing and Tianjin area and that of neighboring areas.

Set overlay analysis parameters

                                // Set overlay analysis parameters
var datasetOverlayAnalystParameters = new ol.supermap.DatasetOverlayAnalystParameters({
    sourceDataset: "BaseMap_R@Jingjin",
    operateDataset: "Neighbor_R@Jingjin",
    tolerance: 0,
    operation: ol.supermap.OverlayOperationType.UNION
});
                            

Set the overlay analysis service object, which is used to pass parameters specified at the client side to the server side and receive the data from returned from the server. When a request has been sent to the server and the server has returned the result successfully, the user can handle the results of overlay analysis from the server.

                                // Define overlay analysis service
// Send the request to the server and display the results returned from the server on the map
new ol.supermap.SpatialAnalystService(serviceUrl).overlayAnalysis(datasetOverlayAnalystParameters).then(function (serviceResult) {
    // Get the returned features data
    var features = serviceResult.result.recordset.features;
});See full example code »
                            

Enjoy the result.

Min distance calculation

The calculation of min distance is calculating the min distance between features in the calculated dataset to features within the query bounds of the reference dataset. Currently, only 2D point dataset is supported for calculated dataset. The reference dataset can be 2D point, line, region or 2D network dataset.

Here we find the closest geometric object to a point in Changchun data.

                                    // The point need to find closest geometric object
pointGeometryData = {
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [2000, -3500]
    }
};
// Min distance calculation parameters
var minDistanceAnalystParameters = new ol.supermap.GeometryMinDistanceAnalystParameters({
    inputGeometries: [pointGeometryData],
    referenceDatasetName: "Park@Changchun",
    createResultDataset: false,
    minDistance: 0,
    maxDistance: -1 // -1 indicates that there is no maximum query distance limitation
})
// Create min distance calculation service instance
var serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst";
var minDistanceAnalystService = new ol.supermap.SpatialAnalystService(serviceUrl);
// Send a request to the server and get the returned result
minDistanceAnalystService.minDistanceAnalysis(minDistanceAnalystParameters).then(function (serviceResult) {
    // Get the result returned by the server
    var minDistanceAnalystResult = serviceResult.result.distanceResults;
});See full example code »
                            

Enjoy the result.

Extract isolines/isoregions

Surface analysis includes extracting isolines and extracting isoregions. Isolines are lines connected with adjacent points with same values, commonly used for contour lines for height, depth, temperature, precipitation, etc. The distribution of isolines reflects the change of the value on the grid surface, and the denser the contour lines are, the more drastic the change of the grid surface values. At places where the contour distribution is sparse, the change of grid surface values is smaller. By extracting isolines, we can find places where the elevation, temperature or precipitation is the same. Meanwhile, the distribution of isolines can also reflect where the value change is steep or gentle. The isoregions is composed by closing adjacent contour lines. The change of the isoregions can intuitively indicate the change between adjacent isolines, such as elevation, precipitation, temperature or atmospheric pressure. Places where the elevation, precipitation or temperature is equivalent can be obtained by extracting the isoregions.

This section will introduce the usage of surface analysis interface by extracting contour lines based on temperature resample points of China.

Set surface analysis parameters

                                // Set clip area
var region = new ol.geom.Polygon([[
    [0, 4010338],
    [1063524, 4010338],
    [1063524, 3150322],
    [0, 3150322]
]]);
// The parameters of surface analysis Extraction operating
var surfaceAnalystParameters = new ol.supermap.DatasetSurfaceAnalystParameters({
    // Set surface analysis parameters
    extractParameter: new ol.supermap.SurfaceAnalystParametersSetting({
        // The datum value in surface analysis
        datumValue: 0,
        // The interval value
        interval: 2,
        // The resample tolerance
        resampleTolerance: 0,
        // The method used for smoothing
        smoothMethod: ol.supermap.SmoothMethod.BSPLINE,
        // The smoothness of contour lines
        smoothness: 3,
        // The clip object
        clipRegion: region
    }),
    // The name of the source dataset in overlay analysis
    dataset: "SamplesP@Interpolation",
    // The resoluton of intermediate results
    resolution: 3000,
    // The name of the field used for extraction
    zValueFieldName: "AVG_TMP"
});
                            

Set the surface analysis service object, which is used to pass parameters specified at the client side to the server side and receive the data from returned from the server. When a request has been sent to the server and the server has returned the result successfully, the user can handle the results of surface analysis from the server.

                                // Initialize surface analysis service instance
var surfaceAnalystService = new ol.supermap.SpatialAnalystService(serviceUrl);
surfaceAnalystService.surfaceAnalysis(surfaceAnalystParameters).then(function (surfaceAnalystServiceResult) {
    // Get the returned data
    var result = surfaceAnalystServiceResult.result.recordset.features;
});See full example code »
                            

Enjoy the result.

Dynamic Segmentation

Dynamic segmentation technology is based on the traditional GIS data model, using linear reference technology to realize the dynamic display, analysis and output of attribute data on the map. It is an important technical means in GIS spatial analysis.It is not a physical segmentation of the online feature along a certain attribute of the line. Instead, it uses the idea and algorithm of the linear reference system based on the traditional GIS data model to store the changes along the attribute as independent attributes table field (event attribute table); In the analysis, display, query and output, the linear elements are dynamically logically segmented according to the distance values in the event attribute table, and the relative position description is used to generate events on the line, which is easier to locate than the traditional GIS elements. In addition, the technology also improves data production efficiency and data storage space utilization, reducing the complexity of data maintenance. It has been widely used in public transportation management, road quality management, navigation line simulation, communication network management, power grid management and many other fields.

This section introduces to you how to show the road traffic (blocked/congested/expedite) in real-time on the client side based on dynamic segmentation technology to prompt motorists to avoid entering the congested road and choose the appropriate route using data for Changchun city road map as the sample data. The usage of the dynamic segmentation interface is as follows:

Set parameters including DataReturnOption and generateSpatialDataParams for dynamic segmentation on the client side.

                                // Configure dynamic segmentation parameters
var generateSpatialDataParameters = new ol.supermap.GenerateSpatialDataParameters({
    // The route ID
    routeTable: "RouteDT_road@Changchun",
    // The identification field of the routing dataset
    routeIDField: "RouteID",
    // The event table used to generate spatial data
    eventTable: "LinearEventTabDT@Changchun",
    // The route ID of the event table used to generate spatial data
    eventRouteIDField: "RouteID",
    // The measure field of the event table used to generate spatial data
    measureField: "",
    // The from field of the event table
    measureStartField: "LineMeasureFrom",
    // The to field of the event table
    measureEndField: "LineMeasureTo",
    // The offset field for measure values
    measureOffsetField: "",
    // The error message field
    errorInfoField: "",
    // Set DataReturnOption
    dataReturnOption: new ol.supermap.DataReturnOption({
        expectCount: 1000,
        dataset: "generateSpatialData@Changchun",
        // If the user-named result dataset name is the same as the existing dataset, delete the existing dataset
        deleteExistResultDataset: true,
        // Set the data return mode to DATASET_ONLY
        dataReturnMode: ol.supermap.DataReturnMode.DATASET_ONLY
    })
});
                            

Set the dynamic segmentation service object, which is used to pass parameters(generateSpatialDataParams) specified at the client to the server and receive the data returned from the server. When a request has been sent to the server and the server has returned the result successfully, the user can handle the results of dynamic segmentation from the server. The road condition information in the spatial data is presented to the user in the form of theme graph.

                                // Construct dynamic segmentation service
var serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst"
// Send the request to the server and display the results on the client side as thematic map
new ol.supermap.SpatialAnalystService(serviceUrl).generateSpatialData(generateSpatialDataParameters).then(function (serviceResult) {
    // Get the returned data
    var result = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Route Calculate Measure Services

Route Calculate Measure calculates the M-value of a point to the starting point of the route. For example, a user may want to know where an accident occurred to determine the distance of the point from a certain intersection.

Here we calculate the distance from an accident point to the road intersection (route ID 1690). The sample data used is Changchun data.

The usage for the interface of Route Calculate Measure Service is as follows:

After the map loading is completed, we will perform the Route Calculate Measure operation. First, we need to get the route object according to the RouteID, and then proceed to subsequent operation.

                                // Establish route through SQL query
var queryBySQLService = new ol.supermap.QueryService(baseUrl);
// Set SQL query parameters
var queryBySQLParams = new ol.supermap.QueryBySQLParameters({
    queryParams: [
        new ol.supermap.FilterParameter({
            name: "RouteDT_road@Changchun",
            attributeFilter: "RouteID=1690"
        })
    ]
});
// Construct SQL query server
queryBySQLService.queryBySQL(queryBySQLParams).then(function (SQLQueryServiceResult) {
    // Get the results of SQL query
    var queryBySQLResult = SQLQueryServiceResult.result.recordsets[0].features;
    // Extract the points that form the route to construct the parameter sourceRoute
    var pointsList = [];
    var routeObj = queryBySQLResult.features[0].geometry.coordinates[0];
    for (var i = 0; i < routeObj.length; i++) {
        pointsList.push([routeObj[i][0], routeObj[i][1],routeObj[i][2]])
    }
    var routeLine = new ol.geom.LineString([pointsList]);

    // Select a query point (the 8th point in the array) from the points that make up the route and add it to the map.
    var point = new ol.geom.Point([routeObj[7][0], routeObj[7][1]]);

    // Route Calculate Measure Services
    var routeCalculateMeasureService = new ol.supermap.SpatialAnalystService(serviceUrl);
    var routeCalculateMeasureParameters = new ol.supermap.RouteCalculateMeasureParameters({
        "sourceRoute": routeLine,   // Route Type
        "point": point,            // Required
        "tolerance": 10,
        "isIgnoreGap": false
    });
    // Send the request to the server and handle the results returned from the server
    routeCalculateMeasureService.routeCalculateMeasure(routeCalculateMeasureParameters).then(function (routeCalculateServiceResult) {
        // Get the results returned from the server
        var result = routeCalculateServiceResult.result;
    });
});See full example code »
                            

Enjoy the result.

Route Locator Point Services

Route Locator Point determines the point according to the M value. The application scenario is opposite to Route Calculate Measure. It will be used to determine the precise coordinates of an accidient position on the premise of the M value from the point to the road intersection.

Here we will determine the precise coordinates of an accidient position on the premise of the M value from the point to the road intersection is 800 m on the route with the ID of 1690. The sample data used here is Changchun data, the usage of Route Locator Point interface:

After the map loading is completed, we will perform the Route Locator Point operation. First, we need to get the route object according to the RouteID, and then proceed to subsequent operation.

                                // Establish route through SQL query
var queryBySQLService = new ol.supermap.QueryService(baseUrl);
// Set SQL query service parameters
var queryBySQLParams = new ol.supermap.QueryBySQLParameters({
    queryParams: [
        new ol.supermap.FilterParameter({
            name: "RouteDT_road@Changchun",
            attributeFilter: "RouteID=1690"
        })
    ]
});
// Create query service
queryBySQLService.queryBySQL(queryBySQLParams).then(function (SQLQueryServiceResult) {
    // Get SQL query results
    var queryBySQLResult = SQLQueryServiceResult.result.recordsets[0].features;
    // Extract the points that form the route to construct polyline of sourceRoute
    var pointsList = [];
    var routeObj = queryBySQLResult.features[0].geometry.coordinates[0];
    for (var i = 0; i < routeObj.length; i++) {
        pointsList.push([routeObj[i][0], routeObj[i][1], routeObj[i][2]])
    }
    var routeLine = new ol.geom.LineString([pointsList]);
    // Construct Route Locator Point service
    var routeLocatorService = new ol.supermap.SpatialAnalystService(serviceUrl);
    // Set Route Locator Point parameters
    var routeLocatorParameters_point = new ol.supermap.RouteLocatorParameters({
        "sourceRoute": routeLine,
        "type": "POINT",
        "measure": 800,
        "offset": 0,
        "isIgnoreGap": true
    });
    // Send the request to the server and get the returned results
    routeLocatorService.routeLocate(routeLocatorParameters_point).then(function (routeLocateServiceResult) {
        // Get the results returned by server.
        var result = routeCalculateServiceResult.result;
    })
});
See full example code »
                            

Enjoy the result.

Route Locator Line Services

Route Locator Line determines the line object on the route according to the specified range. For example, you need to know the precise position of a line segment when we know there is a line segment blocked.

Here we introduce how to determine precise position of a line segment on the premise of the measure values of the line segment to the road intersection are 200 meters to 1000 meters.

After the map loading is completed, we will perform the Route Locator Line operation. First, we need to get the route object according to the RouteID, and then proceed to subsequent operation. The usage for the interface of Route Locator Line Services is as follows:

                                // Create route by SQL query
var queryBySQLService = new ol.supermap.QueryService(baseUrl);
// Set SQL query service parameters
var queryBySQLParams = new ol.supermap.QueryBySQLParameters({
    queryParams: [
        new ol.supermap.FilterParameter({
            name: "RouteDT_road@Changchun",
            attributeFilter: "RouteID=1690"
        })
    ]
});
// Create SQL query service
queryBySQLService.queryBySQL(queryBySQLParams).then(function (SQLQueryServiceResult) {
    // Get SQL query results
    var queryBySQLResult = SQLQueryServiceResult.result.recordsets[0].features;
    // Extract the points that form the route to construct routeLine of sourceRoute
    var pointsList = [];
    var routeObj = queryBySQLResult.features[0].geometry.coordinates[0];
    for (var i = 0; i < routeObj.length; i++) {
        pointsList.push([routeObj[i][0], routeObj[i][1], routeObj[i][2]])
    }
    var routeLine = new ol.geom.LineString([pointsList]);

    // Construct Route Locator Line server instance
    var routeLocatorService = new ol.supermap.SpatialAnalystService(serviceUrl);
    // Set the parameters of Route Locator Line server
    var routeLocatorParameters_line = new ol.supermap.RouteLocatorParameters({
        "sourceRoute": routeLine,
        "type": "LINE",
        "startMeasure": 200,
        "endMeasure": 1000,
        "isIgnoreGap": true
    });
    // Send the request to the server and get the returned results
    routeLocatorService.routeLocate(routeLocatorParameters_line).then(function (routeLocateServiceResult) {
        // Get the results returned by server.
        var result = routeCalculateServiceResult.result;
    });
});See full example code »
                            

Enjoy the result.

Interpolation Analyst

Interpolation analysis can predict the numerical conditions around the sampling point by interpolating the finite sample point data, so as to master the overall distribution of the data in the study area, the discrete points not only reflect the numerical conditions of their location, but also reflect the numerical distribution of the region. Three kinds of interpolation methods are provided in SuperMap: Inverse Distance Weighted(IDW), Kriging interpolation square (Kriging), Radial basis function interpolation (RBF). The chose of interpolation analysis usually depends on the distribution of sample data and the type of surface to be created.

No matter which interpolation method is chosen, the more data and the wider the distribution of known points, the closer to the actual situation the interpolation results will be. The following is the example of the Inverse Distance Weighted(IDW).

                                // Create parameters for point density interpolation analysis
var interpolationAnalystParameters = new ol.supermap.InterpolationIDWAnalystParameters({
    // The name of the dataset in the data source used for interpolation analysis
    dataset: "SamplesP@Interpolation",
    // The name of interpolation analysis result dataset
    outputDatasetName: "IDW_result",
    // The name of the source dataset of interpolation analysis result
    outputDatasourceName: "Interpolation",
    // The pixel format of the resulting raster dataset storage
    pixelFormat: ol.supermap.PixelFormat.DOUBLE,
    // Store the field names used for interpolation analysis
    zValueFieldName: "AVG_TMP",
    resolution: 7923.84989108,
    // The number of points participating in the operarion is fixed
    searchMode: "KDTREE_FIXED_COUNT",
    // In the fixed point number search mode, the number of points participating in the interpolation defaults to 12
    expectedCount: 12,
    bounds: [-2640403.63, 1873792.1, 3247669.39, 5921501.4]
});
new ol.supermap.SpatialAnalystService(serviceUrl).interpolationAnalysis(interpolationAnalystParameters).then(function (serviceResult) {
    // Get the data returned by the server
    interpolationAnalystResult = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Grid Algebraic Operation

Grid algebraic operation idea is to use algebra view of characteristics of geographical phenomena and spatial analysis. Essentially, it conducts the mathematical operation and functional operation for multiple raster datasets. The pixel value of the result raster data is obtained by algebraic operation from the pixel value of the same position of one or more input raster data.

In order to better implement the function of raster algebra, SuperMap provides a wealth of operators, functions and operation expressions, in addition to commonly used arithmetic operations (such as plus, minus, multiply, divide, toInt and toFloat), also supports users-defined expressions for raster arithmetic, conditional operations, logic operations, function operations (including common functions, trigonometric functions, etc.) and compound operations, users can achieve a variety of raster analysis needs through raster algebra operations.

The interface of grid algebraic operation is used as follows

                                // Create grid algebraic operation server
var mathExpressionAnalysisParameters = new ol.supermap.MathExpressionAnalysisParameters({
    // Specify dataset, required
    dataset: "JingjinTerrain@Jingjin",
    // The algebraic expression of the grid operation to be executed, required
    expression: "[Jingjin.JingjinTerrain] + 600",
    // The data source that stores the result dataset, required
    targetDatasource: "Jingjin",
    // The name of result dataset, required
    resultGridName: "MathExpressionAnalysis_Result",
    deleteExistResultDataset: true
});
// Initiate a raster algebraic operation request to iServer
    new ol.supermap.SpatialAnalystService(serviceUrl).mathExpressionAnalysis(mathExpressionAnalysisParameters).then(
    function (serviceResult) {
        // Get the data returned by the server
        mathExpressionAnalysisResult = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Terrain slope calculation

Slope is one of the important terrain factors, in which slope denotes the measurement of the ratio of height change of a certain location on the earth surface. Terrain slope calculation is used to calculate the slope value of each pixel in the raster dataset. The bigger the slope value, the steeper the terrain; on the contrary, the smaller the slope value, the flatter the terrain.

In SuperMap, slope calculation provides three ways to denote, including degrees, radians and percentages. Because there is no practical significance to calculate the slope and aspect of point, the method calculates the mean value of the slope of each pixel in a raster dataset.

Here we calculate the slope value of each pixel in Jingjin data. The map needs to be initialized before the terrain calculation process. The terrain slope calculation analysis is performed after the map is loaded.

                                // Terrain slope calculation parameters
var terrainSlopeCalculationParameters = new ol.supermap.TerrainSlopeCalculationParameters({
    dataset: "JingjinTerrain@Jingjin",
    zFactor:0.00001, // Elevation scaling factor
    slopeType:"DEGREE", // The unit type of slope result 
    terrainAnalystSetting: new ol.supermap.terrainAnalystSetting({
        boundsType: ol.supermap.BoundsType.UNION, // The range type of Analysis result dataset
        cellSizeType: ol.supermap.CellSizeType.MAX // The cell type of Analysis result dataset
    }), 
    resultDatasetName:"testSlope", 
    deleteExistResultDataset:true
});
// Create terrain slope calculation service instance
var serviceUrl ="https://iserver.supermap.io/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst";
// Send a request to the server and get the returned result
var terrainSlopeCalculationService = new ol.supermap.SpatialAnalystService(serviceUrl);
terrainSlopeCalculationService.terrainAspectCalculate(terrainSlopeCalculationParameters).then(function (serviceResult) {
    // Get the result returned by the server
    var terrainSlopeCalculationResult = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Terrain aspect calculation

Aspect is one of the important terrain factors, in which aspect denote the measurement of slope direction variation of a certain location on the earth surface. Terrain aspect calculation is used to calculate the aspect of each pixel in the raster dataset. Aspect is represented in degrees, the range of aspect analysis result is 0° to 360°. Starts form due north 0° and moves clockwise and ends at 360°. flat slope has no direction and the value is -1.

Here we calculate the aspect value of each pixel in Jingjin data. The map needs to be initialized before the terrain calculation process. The terrain aspect calculation analysis is performed after the map is loaded.

                                // Terrain aspect calculation parameters
var terrainAspectCalculationParameters = new ol.supermap.TerrainAspectCalculationParameters({
    dataset: "JingjinTerrain@Jingjin",
    // Basic environment settings of terrain analysis
    terrainAnalystSetting: new ol.supermap.terrainAnalystSetting({
        boundsType: ol.supermap.BoundsType.UNION,// The range type of Analysis result dataset
        cellSizeType: ol.supermap.CellSizeType.MAX// The cell type of Analysis result dataset
    }), 
    resultDatasetName:"testAspect", 
    deleteExistResultDataset:true
})

// Create terrain aspect calculation service instance
var serviceUrl ="https://iserver.supermap.io/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst";
// Send a request to the server and get the returned result
var terrainAspectCalculationService = new ol.supermap.SpatialAnalystService(serviceUrl);
terrainAspectCalculationService.terrainAspectCalculate(terrainAspectCalculationParameters).then(function (serviceResult) {
    // Get the result returned by the server
    var terrainAspectCalculationResult = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Terrain curvature calculation

Terrain curvature calculation is used to calculate the curvature of the surface of the raster data. Curvature is the second derivative of the surface, or it can be called the slope of the slope, which is one of the main parameters to express topographic surface structure. The output is the surface curvature of each cell of the terrain raster, which is obtained by fitting the cell to eight adjacent cells. The resulting output is a raster dataset with output curvature types: mean curvature, profile curvature, and plane curvature, the mean curvature is the necessary output, and the profile curvature and plane curvature are selectable outputs. Wherein, the curvature of the profile refers to the curvature along the direction of the maximum slope, and the curvature of the plane refers to the curvature perpendicular to the direction of the maximum slope.

Elevation scaling factor: when calculating curvature, the unit that requires the grid value of the terrain (the elevation value) is the same as that of the X, Y coordinates, and usually requires the elevation value multiplied by a height scaling coefficient, which makes the three units consistent. For example, the units in the direction of X and Y are meters, while the units in Z direction are feet. As 1 feet are equal to 0.3048 meters, the scaling factor is 0.3048. If set to 1, the representation is not zoomed.

The map needs to be initialized before the terrain curvature calculation process.

The terrain curvature calculation analysis service is performed after the map is loaded.

                                // Construct terrain curvature calculation service parameters instance
var terrainCurvatureCalculationParameters = new ol.supermap.TerrainCurvatureCalculationParameters({
    dataset: "JingjinTerrain@Jingjin",
    zFactor: 1.0,
    averageCurvatureName: "CurvatureA",
    deleteExistResultDataset: true
});
// Initiate terrain curvature calculation request to the iServer
new ol.supermap.SpatialAnalystService(serviceUrl).terrainCurvatureCalculate(terrainCurvatureCalculationParameters).then(
    function (serviceResult) {
        // Get the data returned by the server
        terrainCurvatureCalculationResult = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Terrain cut and fill calculation

The objects on a surface may move because of deposition and erosion, the result is the increasing of surface objects at some region and the reducing of surface objects at other region. In project, the reducing of surface objects is called Cut and the increasing of surface objects is called Fill. We can calculate the area and volume of cut and fill when one situation change to another.

Here we calculate the area and volume of cut and fill in Jingjin data.

                                // Terrain cut and fill calculation parameters
var terrainCutFillCalculationParameters = new ol.supermap.TerrainCutFillCalculationParameters({
    dataset: "JingjinTerrain@Jingjin",
    cutFillType:"REGION3D",
    // Create three-dimensional surface object as the cut and fill calculation object
    region3D: new ol.supermap.Geometry3D({
        points:[
            {"x":116.2,"y":40.1,"z":-5.0},
            {"x":116.5,"y":40.5,"z":0.0},
            {"x":116.5,"y":40.1,"z":30.0},
            {"x":116.2,"y":40.1,"z":-5.0}
        ],
        rotationX: 0.0,
        rotationY: 0.0,
        rotationZ: 0.0,
        scaleX: 0.0,
        scaleY: 0.0,
        scaleZ: 0.0,
        type: "REGION3D",
    }),
    resultDataset:"cutfill", 
    buildPyramid:true, // Whether to create a pyramid for the result raster dataset
    deleteExistResultDataset:true
});
// Construct cut and fill calculation service instance
serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst";
var terrainCutFillCalculateService = new ol.supermap.SpatialAnalystService(serviceUrl);
// Send a request to server and get the result
terrainCutFillCalculateService.minDistanceAnalysis(minDistanceAnalystParameters).then(function (serviceResult) {
    // Get the data returned by the server
    var terrainCutFillCalculationResult = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Kernel Density Analysis

Kernel density analysis: used to calculate density per unit of the point, line feature measurement value in the specified neighborhood. In simple terms, it can visually reflect the distribution of discrete measurements over successive regions. The result is a smooth surface with big values in the center and small values around. The grid value is the density and is reduced to 0 at the boundary of the neighborhood.

Kernel density analysis can be used to calculate population density, building density, access to crime reports, population monitoring of tourist areas, chain stores operating analysis and so on. For example:

A number of high-rise apartments and houses are distributed in a certain block, the number of people in each building is known, this function can be used to obtain the population distribution in the area. This is equivalent to distributing the population of each building into the specified circle neighborhood with the change trend of the Kernel function, and the overlapping areas are summed to obtain the population density throughout the neighborhood. The population density results can be used for store location decision, crime rate estimation, etc.

Before performing kernel density analysis, you need to initialize the map.

The kernel density analysis service is performed after the map is loaded.

                                // Construct kernel density analysis parameter instance
var densityAnalystParameters = new ol.supermap.DensityKernelAnalystParameters({
    // Specify dataset
    dataset: "Railway@Changchun",
    // Specify range
    bounds: [3800, -3800, 8200, -2200],
    // Specify fields for kernel density analysis in the dataset
    fieldName: "SmLength",
    searchRadius: 50, // The unit of Railway@Changchun is meters
    // The name of result dataset
    resultGridName: "KernelDensity_Result",
    deleteExistResultDataset: true
});
new ol.supermap.SpatialAnalystService(serviceUrl).densityAnalysis(densityAnalystParameters).then(function (serviceResult) {
    // Get the data returned by the server
    densityAnalystResult = serviceResult.result;
});See full example code »
                            

Enjoy the result.

Traffic transfer analysis

The use of traffic transfer analysis is as follows:

  • Define the query function for the start site and end site;
  • Add traffic transfer query funciton. It is necessary to set a traffic transfer parameter for sending to the server on the client, and define a traffic transfer service for sending a request to the server and obtaining the traffic transfer result data from the server. Finally the returned results are displayed on the client.

Taking the bus route data simulated by Changchun traffic data as an example. The example is from "省汽修" to "中安大厦", the transfer method is the least time. Users can choose the most suitable travel route according to his own needs.

1. Query traffic transfer plan

This method returns all the ride plans, and users can obtain a specific ride route according to the introduction information in the plan. Firstly, set the traffic transfer parameters, including solutionCount, transferTactic, walkingRatio, points. Define the traffic transfer service function, send a request to the server, and wait for the server to successfully process and return the result.

                                    // Define traffic transfer query
paths.points = [26, 180];
var params = new ol.supermap.TransferSolutionParameters({
    solutionCount: 6,        // Maximum number of transfer guides
    transferTactic: LESS_TIME,  // Traffic transfer strategy type
    walkingRatio: 10,        // Consumption weight ratio of walking and bus
    points: paths.points     // Starting point coordinates
});
// Send a request to server and get the result
new ol.supermap.TrafficTransferAnalystService(serviceUrl)
    .analysisTransferSolution(params).then(function (serviceResult) {
        // Get the result return from server
        var result = serviceResult.result;
    });
                                

2. Query driving route

Get detailed information about a particular route based on the ride plan obtained from the transfer results(transfersolution).

                                    // Click on a plan on the map and get a specific route to construct the transLines parameter
// Get details of the ride route
// Set the query parameters
var params = new ol.supermap.TransferPathParameters({
    points: paths["points"],
    transferLines: transLines
});
// Send request to the server and get the data
new ol.supermap.TrafficTransferAnalystService(serviceUrl)
    .analysisTransferPath(params).then(function (serviceResult) {
        // Get the details of the returned route
        var transGuide = serviceResult.result;
    });See full example code »
                                

Enjoy the result.

Here is the result of the least time query, in which the departure station is "省汽修" and the destination is "中安大厦". The effect is as follows:

Network analysis

SuperMap iClient for OpenLayers supports:

  • Service area analysis
  • Closest facility analysis
  • Location-allocation analysis
  • Multi-traveler analysis / logistics distribution
  • Best route analysis
  • Connected edges analysis
  • TraceUp and traceDown analysis

Service area analysis

The service area analysis is to find the service scope for the designated service center point on the network. For instance, the 30-minute service area for a certain point on a network, the time from any point in the service area to that point will not exceed 30 minutes.

Taking Changchun data as an example, select the service center point to be analyzed in the map (support multi-center), perform buffer analysis according to the incremented values of 400, 500, 600... as the service radius according to the order of selected service center points. That is, the service radius of the first service center point is 400, the service radius of the second service center point is 500, and so on.

Service area analysis interface usage:

Set the parameter findServiceAreasParams, including network analysis common parameters, route sites, and so on.

                    // Create service analysis parameter instance
var resultSetting = new ol.supermap.TransportationAnalystResultSetting({
    // Whether to include arc feature collections in the analysis results
    returnEdgeFeatures: true,
    // Whether the geometric component information is included in the returned arc feature collection
    returnEdgeGeometry: true,
    // Whether the arc ID is included in the result
    returnEdgeIDs: true,
    // Whether to include a collection of node features in the analysis result
    returnNodeFeatures: true,
    // Whether the returned feature set contains geometric object information
    returnNodeGeometry: true,
    // Whether the result contains passed node IDs
    returnNodeIDs: true,
    // Whether the travel guide set is included in the analysis result
    returnPathGuides: true,
    // Whether the analysis result contains the collection of routing objects
    returnRoutes: true
});
// Service area analysis result parameter class
var analystParameter = new ol.supermap.TransportationAnalystParameter({
    resultSetting: resultSetting,
    weightFieldName: "length"
});
// Service area analysis parameter
var parameter = new ol.supermap.FindServiceAreasParameters({
    centers: [point],
    isAnalyzeById: false,
    parameter: analystParameter
});
                

Define the service area analysis service object. The service area analysis object is used to pass the service area analysis parameters(findServiceAreasParams) set by client to server, and receive the dynamic segmentation analysis result data returned by the server. When the request is sent to server and the server successfully returns the result, users can process the obtained service area analysis result accordingly.

                    // Define service area analysis service
new ol.supermap.NetworkAnalystService(serviceUrl).findServiceAreas(parameter).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});
                

Enjoy the result.

Find closest facility

Closest facility analysis is to give an incident and a set of facilities on a network, to find one or several facilities that can be reached with minimum cost for incident, and the results show the best path, cost, and direction of travel from the incident to the facility or from the facility to the incident. For instance, you can set up a closest facility problem to search for hospitals within a 20-minute drive of the site of an accident. Any hospitals that Taking longer than 20 minutes to reach are not included in the results. In this case, the accident is the incident and surrounding hospitals are facilities. Closest facilities analysis is actually a path analysis. Therefore, it is also possible to apply the settings of the obstacle side and the obstacle point. These obstacles will not be traversed on the road and will be considered in the path analysis.

Taking Changchun data as an example, mark the incident on the map, and then perform closest facilities analysis for the three hospitals.

Set the parameters, including network analysis general parameters, incident, facilities, search radius, etc.

                    // Add event point
var eventPoint = new ol.geom.Point([5000, -3700]);
// Set parameter for network analysis result
var resultSetting = new ol.supermap.TransportationAnalystResultSetting({
    returnEdgeFeatures: true,
    returnEdgeGeometry: true,
    returnEdgeIDs: true,
    returnNodeFeatures: true,
    returnNodeGeometry: true,
    returnNodeIDs: true,
    returnPathGuides: true,
    returnRoutes: true
});
// Network analysis common parameters
var analystParameter = new ol.supermap.TransportationAnalystParameter({
    resultSetting: resultSetting,
    turnWeightField: "TurnCost",
    weightFieldName: "length"  // length, time
});
// Set closest facility analysis parameters
var findClosetFacilitiesParameter = new ol.supermap.FindClosestFacilitiesParameters({
    // Event point, required
    event: eventPoint,
    // The number of facilities to find. The default is 1
    expectFacilityCount: 1,
    // Facilities collection, required
    facilities: [new ol.geom.Point([2500, -3500]), new ol.geom.Point([5500, -2500]), new ol.geom.Point([7000, -4000])],
    isAnalyzeById: false,
    parameter: analystParameter
});See full example code »
                

Define the service area analysis service object. The service area analysis object is used to pass the service area analysis parameters(findServiceAreasParams) set by client to server, and receive the dynamic segmentation analysis result data returned by the server. When the request is sent to server and the server successfully returns the result, users can process the obtained service area analysis result accordingly.

                    // Create a service area analysis service instance
new ol.supermap.NetworkAnalystService(serviceUrl).findClosestFacilities(findClosetFacilitiesParameter).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});See full example code »
                

Enjoy the result.

Location-allocation analysis

Location-allocation analysis is to determine the optimal location of one or more facilities to be built so that the facility can provide services or goods to the demanding party in the most cost-effective manner. The location-allocation analysis is not only a site selection process, but also the demand point needs to be allocated to the service area of the corresponding new facility, so it is called site selection and allocation.

Set location-allocation analysis parameters, including traffic network analysis common parameters, route sites, etc.

                    // Set up a resource supply center for facilities
var supplyCenterType_FIXEDCENTER = ol.supermap.SupplyCenterType.FIXEDCENTER;
var supplyCenterType_NULL = ol.supermap.SupplyCenterType.NULL;
var supplyCenterType_OPTIONALCENTER = ol.supermap.SupplyCenterType.OPTIONALCENTER,
// Taking one center point as an example
supplyCenters = [new ol.supermap.SupplyCenter({
    maxWeight: 500,             // The maximum cost of the resource supply center, required
    nodeID: 139,                // The node ID number of the resource supply center point, required
    resourceValue: 100,         // The maximum amount of service or quantity of goods that the resource supply center can provide, required
    type: supplyCenterType_OPTIONALCENTER      // The types of resource centers include fixed centers and optional centers
})];
// Set the location-allocation analysis parameters
var findLocationParameter = new ol.supermap.FindLocationParameters({
    // Number of resource supply centers expected to be used for final facility siting, required
    expectedSupplyCenterCount: 8,
    // Whether to allocate resources from the central point. Default is false
    isFromCenter: false,
    nodeDemandField: "Demand",
    // Turn weight field name
    turnWeightField: "TurnCost",
    // The name of the resistance field, required
    weightName: "length",
    // Resource supply center collection, required
    supplyCenters: supplyCenters
});
                

Define the location-allocation analysis service object, which is used to pass the location zoning analysis service parameter set by the client to the server, and receive the dynamic segmentation analysis result data returned by the server. When the request is sent to the server and the server successfully returns the result, the user can process the obtained closest facility analysis result accordingly.

                    // Create a location-allocation analysis service instance
new ol.supermap.NetworkAnalystService(serviceUrl).findLocation(findLocationParameter).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Multi-traveler analysis / logistics distribution

Multi-traveler analysis, also known as logistics distribution, is to find M distribution center points and N delivery destinations (M, N is an integer greater than zero) in the network dataset, find a cost-effective delivery path, and give The corresponding walking route. The multi-traveler analysis function is to solve how to properly distribute the delivery order and delivery route, to minimize the total cost of distribution or to minimize the cost per distribution center.

The results of the multi-traveler analysis will give the delivery destinations that each distribution center is responsible for, and when a distribution center delivers the goods to its responsible delivery destination, It also gives the order through the various delivery destinations, and the corresponding walking routes, thereby minimizing the distribution cost of the distribution center or minimizing the total cost of all distribution centers.

Taking Changchun data as an example, you can analyze the distribution routes of various warehouse distribution centers of food factories to user-designated retail stations through multi-traveler analysis and traveler analysis, and get the shortest route that taken by quality inspectors when check the goods at each retail station.

Set the parameter findMTSPPathsParams, including network analysis common parameters, distribution center point collection, distribution target point collection, distribution mode, etc.

                    // Set network analysis result parameters
var resultSetting = new ol.supermap.TransportationAnalystResultSetting({
    returnEdgeFeatures: true,
    returnEdgeGeometry: true,
    returnEdgeIDs: true,
    returnNodeFeatures: true,
    returnNodeGeometry: true,
    returnNodeIDs: true,
    returnPathGuides: true,
    returnRoutes: true
});
// Network analysis common parameters
var analystParameter = new ol.supermap.TransportationAnalystParameter({
    resultSetting: resultSetting,
    weightFieldName: "length"  //"length" or "time"
});
// Service area analysis parameter
var findMTSPPathsParameter = new ol.supermap.FindMTSPPathsParameters({
    centers: [new ol.geom.Point([6000, -5500]), new ol.geom.Point([5500, -2500]), new ol.geom.Point([2500, -3500])],
    isAnalyzeById: false,
    nodes: [new ol.geom.Point([5000, -5000]), new ol.geom.Point([6500, -3200])],
    hasLeastTotalCost: true,
    parameter: analystParameter
});
                

Submite the request parameters of the logistics distribution analysis to the server. After the server successfully processes and returns the results, the user can obtain the best route for the goods to be delivered to the respective delivery destinations by the distribution center in turn.

            // Create a logistics distribution analysis service instance
new ol.supermap.NetworkAnalystService(serviceUrl).findMTSPPaths(findMTSPPathsParameter).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Best path analysis

The best path analysis is to solve the path with the least impedance between the two points in a network, and the nodes in the network must be accessed according to the order of selection of the nodes. There are many understandings of “minimum impedance”, such as the shortest time, the lowest cost, the best scenery, the best road conditions, the least bridges, the least toll stations, and the most rural areas based on single factor considerations, etc.

Let's take the Changchun data as an example to calculate the best path between the places in the map that will walk.

Set the parameter findPathParams, including network common parameters, route sites, etc.

                    // Set network analysis result parameters
var resultSetting = new ol.supermap.TransportationAnalystResultSetting({
    returnEdgeFeatures: true,
    returnEdgeGeometry: true,
    returnEdgeIDs: true,
    returnNodeFeatures: true,
    returnNodeGeometry: true,
    returnNodeIDs: true,
    returnPathGuides: true,
    returnRoutes: true
});
var analystParameter = new ol.supermap.TransportationAnalystParameter({
    resultSetting: resultSetting,
    weightFieldName: "length"
});
var findPathParameter = new ol.supermap.FindPathParameters({
    isAnalyzeById: false,
    nodes: [new ol.geom.Point([4000, -3000]), new ol.geom.Point([5500, -2500]), new ol.geom.Point([6900, -4000])],
    hasLeastEdgeCount: false,
    parameter: analystParameter
});
                

Submit the request for the best path analysis to the server. After the server to successfully process and return the best path analysis result, the serviceResult will parse it, and display the driving route in the map and give the driving guidance information.

                    // Ceate a best route analysis instance
new ol.supermap.NetworkAnalystService(serviceUrl).findPath(findPathParameter).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Connected edges analysis

The network may not be fully connected in the real world. You can use connected edges analysis to determine which points/edges are connected with some others. Connected edges analysis does not need to consider the network impedance, and the difference between the network elements is the state of connectivity (connected or disconnected).

Here we query the connected or disconnected roads in Changchun data.

Set the connected edges analyst parameters, including whether to query the connected or disconnected arcs, analyze the return result, and so on.

                            // Connected edges analyst parameters
var connectedEdgesAnalystParameters = new L.supermap.ConnectedEdgesAnalystParameters({
    edgeIDs:[100],
    connected: true// Query the connected arcs
});
                        

Send a tracing analyst request to the server and recieve the returned analysis result.

                            // Ceate a connected edges analysis instance
var serviceUrl = "https://iserver.supermap.io/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun";
var connectedEdgesAnalystService = new L.supermap.NetworkAnalystService(serviceUrl);
connectedEdgesAnalystService.connectedEdgesAnalyst(connectedEdgesAnalystParameters).then(function (serviceResult) {
    // Get the result from server
    var result = serviceResult.result;        
});See full example code »
                        

Enjoy the result.

TraceUp and traceDown analysis

TraceUp and traceDown analysis starts from a node according to a specified rule, and then search all the arcs connected by this node. For instance, if some area of water is polluted, tracing upstream analysis can be used to find where the contaminants may come from, and tracing downstream analysis can be used to trace the range polluted by the pollution source. Tracing data must have a flow direction.

Here we trace the upstream arcs of a node for Changchun data.

Set the tracing analysis parameters,including tracing type, the arc or node ID of query, the validation of uncertain flow direction, and so on.

                            // Tracing analyst parameters
var traceAnalystParameters = new L.supermap.TraceAnalystParameters({
    edgeID:101,
    traceType:0,// 0 denotes tracUp and 1 denotes traceDown
    weightName:"",
    isUncertainDirectionValid: true,// True indicates that the uncertain flow direction is valid, and false indicates that the uncertain flow direction is invalid
    returnFeatures: true
});
                        

Send a tracing analyst request to the server and recieve the returned analysis result.

                            // Ceate a tracing analysis instance
var serviceUrl = "https://iserver.supermap.io/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun";
var traceAnalystService = new L.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and process the returned result
traceAnalystService.traceAnalyst(traceAnalystParameters).then(function (serviceResult) {
    // Get the result from server
    var result = serviceResult.result;
}); See full example code »
                        

Enjoy the result.

Client computing

SuperMap iClient for OpenLayers provides Turf.js for client computing.

Turf is a JavaScript library for spatial analysis. It includes traditional spatial operations, helper functions for creating GeoJSON data, and data classification and statistics tools. Turf can be added to your website as a client-side plugin, or you can run Turf server-side with Node.js.

Turf uses GeoJSON for all geographic data. Turf expects the data to be standard WGS84 longitude, latitude coordinates. Check out geojson.io for a tool to easily create this data.

Most Turf functions work with GeoJSON features. These are pieces of data that represent a collection of properties (ie: population, elevation, zipcode, etc.) along with a geometry. GeoJSON has several geometry types such as:

  • Point
  • LineString
  • Polygon

This example needs to import

Turf (https://github.com/Turfjs/turf/)
                                

Taking Turf grid analysis as an example

                            // Build turf resources
var turfSource = new ol.source.Turf({
    wrapX: false,
    attributions: new ol.Attribution({
        html: ""
    }),
}),
// Taking the Grids.squareGrid analysis type as an example for client computing
turfSource.process("Grids.hexGrid", {
    "bbox": bbox,
    "cellSide": cellSide,
    "units": units,
    "triangles": triangles
});See full example code »
                    

Enjoy the result.

Geocoding

SuperMap iClient for OpenLayers supports for address match service. Address match service is the process of establishing a correspondence between a literal description address and its geographic location coordinates, which includes geocoding and geodecoding. That is, the user can find the address location by location name, also can find places in the specified location.

Geocoding

Geocoding returns the corresponding geographical coordinates and structured address details according to the location description, city range, and supports Chinese fuzzy matching.

                        // Geocoding parameters
var geoCodeParam = new ol.supermap.GeoCodingParameter({
    address: "超图软件", // Address
    fromIndex:0, // Start index value of the returned object
    toIndex:10, // End index value of the returned object
    filters: "北京市,朝阳区", // Filter condition
    prjCoordSys:{epsgcode26}, // Coordinate setting
    maxReturn:3 // Maximum number of returned results
});
// Create address match service
var addressUrl = "https://iserver.supermap.io/iserver/services/addressmatch-Address/restjsr/v1/address",
addressMatchService = new ol.supermap.AddressMatchService(addressUrl);
// Send a request to the server for geocoding and get the returned result
addressMatchService.code(geoCodeParam).then(function (obj){
    // Get the result returned by the server
    var featuers = obj.result;
});See full example code »
                    

Enjoy the result.

Geodecoding

Geodecoding is the process of back (reverse) coding of a point location (latitude, longitude) to a readable address or place name.

                        // Geodecoding parameters
var geoDecodeParam = new ol.supermap.GeoDecodingParameter({
    x: 116.3518541194, // X coordinate
    y: 40.00097839595, // Y coordinate
    fromIndex: 0, // Start index value of the returned object
    toIndex: 10, // End index value of the returned object
    filters: "", // Filter field
    prjCoordSys: {epsgcode26}, // Coordinate setting
    maxReturn: 3, // Maximum number of results
    geoDecodingRadius: 1000 // Query radius
});
// Create address match service
var addressUrl = "https://iserver.supermap.io/iserver/services/addressmatch-Address/restjsr/v1/address",
addressMatchService = new ol.supermap.AddressMatchService(addressUrl);
// Send a request to the server for geocoding and get the returned result
addressMatchService.decode(geoDecodeParam).then(function (obj){
    // Get the result returned by the server
    var featuers = obj.result;
});See full example code »
                    

Enjoy the result.

Big data analysis

The SuperMap iClient for OpenLayers is connected to the distributed analysis service of SuperMap iServer to provide users with big data analysis functions, including:

  • Density analysis
  • Point aggregation analysis
  • Single object spatial query analysis
  • Regional summary analysis
  • Vector cropping analysis
  • Summary attributes analysis
  • Topology validator analysis

Density analysis

Density analysis includes simple point density analysis and kernel density anlysis.

  • Simple point density analysis is used to calculate the magnitude per unit area within the specified neighborhood shape for each point. The calculation method is that measured value of the point is divided by the specified neighborhood area. Where the neighborhood of the point is superimposed, the density values are also added. The density of each output raster is the sum of all neighborhood density values superimposed on the grid. The unit of the result raster value is the reciprocal of the square of the original dataset unit, that is, if the original dataset unit is meter, the unit of the result raster value is per square meter.
  • Kernel density analysis is used to calculate the unit density of point and the line feature measurements over a specified neighborhood. It can intuitively reflect the distribution of discrete measurements in a continuous region. The result is a smooth surface with a large median value and a small peripheral value. The raster value is the unit density and falls to zero at the neighborhood boundary. Kernel density analysis can be used to calculate population density, building density, access to crime reports, population density monitoring in tourist areas, analysis of chain store operations, and more.

Here are the basic steps to implement a simple density analysis function, and the mesh type is quadrilateral.

Set the parameter kernelDensityJobParam, includes dataset, analysis method, analysis type, mesh size, etc.

                        // Density analysis parameter
var kernelDensityJobParam = new ol.supermap.KernelDensityJobParameter({
    // The name of datase
    datasetName: "newyork_taxi_2013_01_14k_csv_newyork_taxi_2013-01_14k",
    // Mesh size. For a quadrilateral mesh, it's the side length of the mesh. For a hexagonal mesh, it's the distance from the vertices of the hexagon to the center point
    resolution: 80,
    // Analysis method. 0 represents simple point density analysis, and 1 represents kernel density analysis
    method:0,
    // 0 represents quadrilateral mesh, and 1 represents hexagonal mesh
    meshType:0,
    // Specify the set of field index column numbers where the weight value of the point to be analyzed is located, and the field index starts from 0
    fields: col7,col8,
    // Range
    query: [-74.050,40.650,-73.850,40.850],
    // Affected radius of analysis
    radius: 300,
    // Unit of grid size
    meshSizeUnit: ol.supermap.AnalystSizeUnit.METER,
    // Unit of search radius
    radiusUnit: ol.supermap.AnalystSizeUnit.METER,
    // Unit of area
    areaUnit: ol.supermap.AnalystAreaUnit.SQUAREMILE,
});
                    

The request for density analysis is submitted to the server, and is parsed after the server successfully processes and returns the density analysis result.

                        // Create a density analysis instance
var processingService = new ol.supermap.ProcessingService(processingsUrl);
processingService.addKernelDensityJob(kernelDensityJobParameter).then(function (serviceResult) {
    // Get the data returned by the server
    var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Point aggregation analysis

Point aggregation analysis is a spatial analysis job for making aggregate graphs of point-to-point datasets. The map point features are divided by mesh region or polygons, and then the number of point features in each polygon object is calculated, and as the statistical value of the polygon object. The weight information of the points can also be introduced, and the weighted value of the points in the polygon object is used as the statistical value of the region object. Finally, based on the statistical value of the region object, according to the result of sorting the statistical value, color filling is performed on the opposite object based on ribbon.

Point aggregation analysis types include mesh aggregation and polygon aggregation. The mesh polygon aggregation graph can be divided into quadrilateral mesh and hexagon mesh according to mesh type.

Here are the basic steps to implement a point aggregation analysis function, and the aggregation type is quadrilateral.

Set the point aggregation analysis parameter summaryMeshJobParam, includes dataset, aggregation type, statistical mode, mesh size, etc.

                        // Point aggregation analysis parameters
var summaryMeshJobParam = new ol.supermap.SummaryMeshJobParameter({
    // The name of dataset
    datasetName: "newyork_taxi_2013_01_14k_csv_newyork_taxi_2013-01_14k",
    // Mesh size. For a quadrilateral mesh, it's the side length of the mesh. For a hexagonal mesh, it's the distance from the vertices of the hexagon to the center point
    resolution: 80,
    // 0 represents quadrilateral mesh, and 1 represents hexagonal mesh
    meshType:0,
    // Specify the set of field index column numbers where the weight value of the point to be analyzed is located, and the field index starts from 0
    fields: col7,
    query: [-74.050,40.650,-73.850,40.850], // Range
    statisticModes: ol.supermap.StatisticAnalystMode.MAX,// Statistical mode. Must be consistent with the number of weight fields
    type: ol.supermap.SummaryType.SUMMARYMESH// Aggregation type
    // regionDataset: 'regionDataset', used in polygon aggregation
});
                    

Send a request to the server for point aggregation anlysis and get the returned result. After the server successfully processes and returns the result, it is parsed.

                        // Create a point aggregation analysis instance
var processingService = new ol.supermap.ProcessingService(processingsUrl);
processingService.addSummaryMeshJob(summaryMeshJobParameter).then(function (serviceResult) {
    // Get the result from server
    var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Single object spatial query analysis

Spatial query is a way to construct a filter condition by spatial positional relationship between geometric objects. For example, Spatial queries can be used to find spatial objects contained in polygons, separated or adjacent spatial objects, etc.

Single object spatial query analysis in distribute analysis service from SuperMap iServer refers to a single object in the query object dataset to do spatial query on the dataset being queried. If there are multiple objects in the clip datasets, by default, the spatial query with the queryed dataset is done by default with the object with the smallest SmID.

Here are the basic steps to implement a single object query analysis function, and the query mode is intersect.

Set the single object spatial query analysis parameters SingleObjectQueryJobsParam, includes dataset, query object dataset, query mode.

                        // Single object spatial query analysis parameters
var singleObjectQueryJobsParam = new ol.supermap.SingleObjectQueryJobsParameter({
    datasetName: 'ProcessingData_processing_newyorkZone_R', // Name of dataset
    datasetQuery: 'ProcessingData_processing_singleRegion_R', // The name of the dataset where the query object is located
    mode:SpatialQueryMode // Spatial query mode
});
                    

Send a request to the server for point aggregation anlysis and get the returned result. After the server successfully processes and returns the result, it is parsed.

                        // Create a single object spatial query analysis instance
var processingService = new ol.supermap.ProcessingService(processingsUrl);
processingService.addQueryJob(singleObjectQueryJobsParameter).then(function (serviceResult) {
    // Get the result from server
    var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Regional summary analysis

Regional summary analysis is a spatial analysis job that creates aggregated graphs for line datasets and polygon datasets. The map line or polygon feature is divided by a mesh surface or a polygon, and then each grid unit inner line or polygon feature is counted by a standard attribute field or a weight field, and the statistical result is used as a statistical value of the grid unit. Finally, the grid cells are sorted according to the size of the grid cells, and the grid cells are color-filled by the ribbon.

The concept of regional summary analysis is similar to the concept of point aggregation analysis. The difference is that point aggregation analysis is a statistical calculation of point datasets, while regional summary analysis is a statistical calculation of line datasets and polygon datasets. There are two statistical of grid unit statistics methods in regional summary analysis, includes statistics by standard attribute fields and statistics by weight fields.

Here are the basic steps to implement a regional summary analysis function, and the summary type is mesh summary, the mesh type is quadrilateral.

Set the parameter summaryRegionJobParam, includes dataset, summary type, mesh type, etc.

                        // Parameters of regional summary analysis
var summaryRegionJobParam = new ol.supermap.SummaryRegionJobParameter({
    // The name of dataset
    datasetName: 'ProcessingData_processing_newyorkZone_R',
    // regionDataset: 'regionDataset', Summary polygon dataset, used in polygon summary
    // Symmary type, includes mesh summary and polygon summary
    type: ol.supermap.SummaryType.SUMMARYMESH,
    // 0 represents quadrilateral mesh, and 1 represents hexagonal mesh,
    // Range
    query: [-74.050,40.650,-73.850,40.850],
    // Whether to count in the standard attribute field
    standardSummaryFields: true,
    // The mode of statistics by standard attribute fields
    standardStatisticModes: ol.supermap.StatisticAnalystMode.MAX,
    // The name of statistics by standard attribute fields
    standardFields: "LocationID",
    // Whether to count by weight fields
    weightedFields:false,
    // The mode of statistics by weight fields
    weightedStatisticModes: "",
    // The name of statistics by weight fields
    weightedSummaryFields: "",
    // Mesh size. For a quadrilateral mesh, it's the side length of the mesh. For a hexagonal mesh, it's the distance from the vertices of the hexagon to the center point
    resolution:100,
    meshSizeUnit: ol.supermap.AnalystSizeUnit.METER, // The unit of mesh size
    sumShape:true // Whether to count the length or area
});
                    

Submit the request of the regional summary analysis to the server. After the server has successfully processed and returns the analysis results, the parsing is processed.

                        // Construct regional summary analysis instance
var processingService = new ol.supermap.ProcessingService(processingsUrl);
processingService.addSummaryRegionJob(summaryRegionJobParameter).then(function (serviceResult) {
    // Get the data returned by the server
    var result = serviceResult.result;
});See full example code »
                        

Enjoy the result.

Vector clip analysis

Vector clip includes inside clip and outside clip. For inside cliping, the portion of the clipped vector within the clipping region is retained in the result dataset. For outside cipping, the portion of the data that is not within the clipping region is preserved the result dataset.

For vector clip in distributed anlysis services, it is supported to clip the source dataset with one object from the clip dataset. If there are multiple objects in the clip datasets, by default, the object with the smallest SmID value will be used to clip the source dataset.

Here are the steps to implement a vector clip analysis function, and the clip mode is inside clip.

Set the parameter vectorClipJobsParam, includes source dataset, clip dataset, clip analysis mode, etc.

                        // The parameter of vectorr clip analysis
var vectorClipJobsParam = new ol.supermap.VectorClipJobsParameter({
    datasetName: 'ProcessingData_newyork_taxi_2013-01_14k', // Dataset name
    datasetOverlay: 'ProcessingData_processing_singleRegion_R', // The name of the dataset where the clipped object is located
    mode:ol.supermap.ClipAnalystMode.CLIP // Clip analyst mode
});
                    

Send a request to the server for vector clip analysis and get the returned result. After the server successfully processes and returns the result, it is parsed.

                        // Create a vector clip analysis instance
var processingService = new ol.supermap.ProcessingService(processingsUrl);
processingService.addVectorClipJob(vectorClipJobsParameter).then(function (serviceResult) {
    // Get the data returned by the server
    var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Summary attributes analysis

Summary attributes analysis refers to summarize the specified fields of the input dataset and calculate statistics on the specified attribute field. By setting the group field, attribute field and which kind of statistics, it can calculate the summary results.

Summary attributes analysis in distribute analysis service from SuperMap iServer will calculate the statistics on all the objects by default. You can also set multi-field with "," to separate each other and summarize attributes in each group fields. Supported statistic mode: max, min, average, sum, variance, stdDeviation.

Here are the basic steps to implement a summary attributes analysis function, and the statistic mode is sum.

Set the summary attributes analysis parameters summaryAttributesJobsParameter, includes summary attributes dataset , group field, attribute field and statistic modes.

                            // Summary attributes analysis parameters
var summaryAttributesJobsParameter = new ol.supermap.SummaryAttributesJobsParameter({
    datasetName: 'sample_processing_newyorkZone_R',
    groupField: 'borough',
    attributeField: 'LocationID',
    statisticModes: 'sum'
});
                        

Send a request to the server for summary attributes analysis and get the returned result. After the server successfully processes and returns the result, it is parsed.

                             // Create a summary attributes analysis instance
var processingUrl ="https://iserver.supermap.io/iserver/services/spatialprocessing/rest/v1/jobs";
var processingService = new ol.supermap.ProcessingService(processingUrl);
// Send a request to the server for summary attributes analysis and get the returned result
processingService.addSummaryAttributesJob(summaryAttributesJobsParameter, function(serviceResult){
    //  Get the result from server
    var result = serviceResult.result;
});See full example code »
                        

Enjoy the result.

Topology validator analysis

Topology validator analysis is used to check whether the given point, line or region data meets the specific topology rule, if not, it will return the objects that don't meet the rule.

Topology validator analysis in distribute analysis service from SuperMap iServer supports the following 7 topology rules: RegionNoOverlap, RegionNoOverlapWith, RegionCoveredByRegion, RegionContainedByRegion, LineNoOverlap, LineNoOverlapwith, PointNoIdentical.

Here are the basic steps to implement a topology validator analysis function, and the topology rule is RegionCoveredByRegion.

Set the topology validator analysis parameters topologyValidatorJobsParameter, includes topology validator dataset, topology rule and tolerance.

                            // Topology validator analysis parameters
var topologyValidatorJobsParameter = new ol.supermap.TopologyValidatorJobsParameter({
    datasetName: 'samples_processing_newyorkZone_R',
    datasetTopology: 'samples_processing_newyorkResidential_R',// The name of the dataset where the validate object is located
    rule: ol.supermap.TopologyValidatorRule.REGIONCOVEREDBYREGION,// Topology rule
    tolerance: 0.000001// Tolerance
});
                        

Send a request to the server for topology validator analysis and get the returned result. After the server successfully processes and returns the result, it is parsed.

                            // Create a topology validator analysis instance
var processingUrl ="https://iserver.supermap.io/iserver/services/spatialprocessing/rest/v1/jobs";
var processingService = new ol.supermap.ProcessingService(processingUrl);
// Send a request to the server for topology validator analysis and get the returned result
processingService.addTopologyValidatorJob(topologyValidatorJobsParameter, function(serviceResult){
    // Get the result from server
    var result = serviceResult.result;
});See full example code »
                        

Enjoy the result.

Data Flow

SuperMap iServer provides data flow service which realizes low latency and real-time data transfer between client and server.Data flow service uses WebSocket protocol to support full-duplex, two-way communication. The server can broadcast the result of real-time data analysis to the clients. Once the connection established between clients and data flow service, the clients can automatically receive broadcast data from the server.

Simulate real-time data by querying a line, and broadcast a point every two seconds to data flow service through dataFlowService. You can broadcast other real-time data to SuperMap iServer through dataFlowService

// Instantiate DataFlow object
var source = new ol.source.DataFlow({
    ws: urlDataFlow
});
// Binding add feature events for content assignment and coordinate position settings
source.on('addfeature', function (e) {
    var feature = e.feature;
    content.innerHTML = feature.get('time');
    overlay.setPosition(feature.getGeometry().getCoordinates());
});
var resultLayer = new ol.layer.Vector({
    source: source,
    style: new ol.style.Style({
        image: new ol.style.Circle({
        fill: fill,
        radius: 6
        }),
    fill: fill,
    })
});
// Simulate real-time data
// Querying a line, and broadcast a point every two seconds to data flow service through dataFlowService
new ol.supermap.QueryService(urlQuery)
    .queryBySQL(param).then(function (serviceResult) {
        featureResult = serviceResult;
        dataFlowBroadcast = new ol.supermap.DataFlowService(urlDataFlow).initBroadcast();
        dataFlowBroadcast.on('broadcastSocketConnected').then(function (e) {
            // Always call the broadcast function below
            timer = window.setInterval("broadcast()", 2000);
            })
        map.addLayer(resultLayer);
});

The broadcast function is continuously called by a timer of 2s interval, and the real-time data position is simulated by the increment of count to generate real-time data.

var count = 200;
function broadcast() {
    // If count is greater than the length of the analog coordinate point array, clear the timer
    if (count >= featureResult.result.recordsets[0].features.features[0].geometry.coordinates.length) {
        window.clearInterval(timer);
        return;
    }
    var point = featureResult.result.recordsets[0].features.features[0].geometry.coordinates[count];
    var feature = {
        geometry: {
            coordinates: [point[0], point[1]],
            type: "Point"
        },
        type: "Feature",
        properties: {
            id: 1,
            time: new Date()
        }
    };
    // Push data to the dataflow service
    dataFlowBroadcast.broadcast(feature);
    count += 3;
}See full example code »

Enjoy the result.

Data visualization

This guide will show you how to create data visualization with SuperMap iClient for OpenLayers.

Heat map

A heat map is a two-dimensional representation of data in which values are represented by colors. A simple heat map provides an immediate visual summary of information. There are three items to draw a heat map with SuperMap iClient for OpenLayers:

  • Data. A heat map is created from point GIS data. Each data needs to have a geographical location and a weight value (can clearly represent the frequency of an event and the density of things distributed in a certain location, such as temperature, population density, etc.)
  • Heat attenuation gradient fill color set. This set is used to render a gradient of each hot spot as it decays from the center outward
  • Raduis. Each hotspot needs to be calculated for the attenuation from the center of the outer point according to the radius, and the color value that needs to be rendered for each pixel in the heat attenuation zone, then rendered in client.

Since the attenuation of the heat map is based on pixel, the visual effect is excellent, but it cannot be in one-to-one correspondence with the specific data.It can only indicate the difference between the weights, so it can be used for some precision requirements that are not high and need to be emphasized. In the gradual industry, for example, it is possible to make a weather effect comparison dynamic effect map, a seismic point intensity map, and the like.

Example code

                                        // Create a heat map
var xmax = 130, xmin = 80, ymax = 50, ymin = 20;
for (var i = 0; i < 100; i++) {
    heatPoints[i] = new ol.Feature(new ol.geom.Point([Math.floor(Math.random() * (xmax - xmin + 1) + xmin), Math.floor(Math.random() * (ymax - ymin + 1) + ymin)]));
}
var heatMap = new ol.layer.Heatmap({
    source: new ol.source.Vector({
        // Heat points array
        features: heatPoints,
        wrapX: false
        }),
    blur: blur,
    radius: radius
});
map.addLayer(heatMap);See full example code »
    

Enjoy the result.

Aggregation point map

OpenLayers provides OL3-AnimatedCluster to implement aggregation point map. OL3-AnimatedCluster is cluster layer for OpenLayers (ol3/ol4) that animates clusters on zoom change and a select interaction that spread out cluster to allow feature selection in it.

Download OL3-AnimatedCluster

1.Download OL3-AnimatedCluster from GitHub:

            https://github.com/Viglino/OL3-AnimatedCluster
                

2. Include the following files in your page:

<script src="animatedCluster.js"></script>

Example code:

var clusterSource = new ol.source.Cluster({
    // Min distance between aggregation points
    distance: 40,
    source: new ol.source.Vector(),
    // Whether to wrap the world horizontally. The default, undefined, is to request out-of-bounds tiles from the server. When set to false, only one world will be rendered. When set to true, tiles will be requested for one world only, but they will be wrapped horizontally to render multiple worlds.
    wrapX: false
});
// Instantiate the AnimatedCluster plugin object layer class
var clusterLayer = new ol.layer.AnimatedCluster({
    name: 'Cluster',
    source: clusterSource,
    // Animation duration
    animationDuration: 700,
    // Use a style function for cluster symbolisation
    style: getStyle
});
map.addLayer(clusterLayer);
// Add features to the aggregate object
function addFeatures(nb) {
    var features = [];
    var xmax = 130, xmin = 80, ymax = 50, ymin = 20;
    for (var i = 0; i < nb; ++i) {
        features[i] = new ol.Feature(new ol.geom.Point([Math.floor(Math.random() * (xmax - xmin + 1) + xmin), Math.floor(Math.random() * (ymax - ymin + 1) + ymin)]));
        features[i].set('id', i);
    }
    clusterSource.getSource().clear();
    clusterSource.getSource().addFeatures(features);
}
addFeatures(2000);

Determine the style of drawing the spot based on the length of the feature.

function getStyle(feature) {
    var styleCache = {};
    var size = feature.get('features').length;
    var style = styleCache[size];
    if (!style) {
        var color = size > 25 ? "192,0,0" : size > 8 ? "255,128,0" : "0,128,0";
        var radius = Math.max(8, Math.min(size * 0.75, 20));
        var dash = 2 * Math.PI * radius / 6;
        dash = [0, dash, dash, dash, dash, dash, dash];
        style = styleCache[size] = [new ol.style.Style({
            image: new ol.style.Circle({
                radius: radius,
                stroke: new ol.style.Stroke({
                    color: "rgba(" + color + ",0.5)",
                    width: 15,
                    lineDash: dash,
                    lineCap: "butt"
                }),
                fill: new ol.style.Fill({
                    color: "rgba(" + color + ",1)"
                })
            }),
            text: new ol.style.Text({
                text: size.toString(),
                fill: new ol.style.Fill({
                    color: '#fff'
                })
            })
        })];
    }
    return style;
}See full example code »
                

Enjoy the result.

Animated feature map

An example of an animation of dynamic blinking points based on OpenLayers.

Example code:

                // Add random features
function addRandomFeature() {
    var xmax = 130, xmin = 80, ymax = 50, ymin = 20;
    var feature = new ol.Feature(new ol.geom.Point([Math.floor(Math.random() * (xmax - xmin + 1) + xmin), Math.floor(Math.random() * (ymax - ymin + 1) + ymin)]));
    source.addFeature(feature);
}
// Animate effect
function flash(feature) {
    var start = new Date().getTime();
    var listenerKey;
    function animate(event) {
        // Animation duration
        var duration = 3000;
        var vectorContext = event.vectorContext;
        var frameState = event.frameState;
        var flashGeom = feature.getGeometry().clone();
        var elapsed = frameState.time - start;
        var elapsedRatio = elapsed / duration;
        var radius = ol.easing.easeOut(elapsedRatio) * 25 + 5;
        var opacity = ol.easing.easeOut(1 - elapsedRatio);
        var style = new ol.style.Style({
            image: new ol.style.Circle({
                radius: radius,
                snapToPixel: false,
                stroke: new ol.style.Stroke({
                    color: 'rgba(255, 0, 0, ' + opacity + ')',
                    width: 0.25 + opacity
                })
            })
        });
        vectorContext.setStyle(style);
        vectorContext.drawGeometry(flashGeom);
        if (elapsed > duration) {
            ol.Observable.unByKey(listenerKey);
            return;
        }
        map.render();
    }
listenerKey = map.on('postcompose', animate);
}
// Bind the animation to the event that adds a feature
var source = new ol.source.Vector({
    wrapX: false
});
source.on('addfeature', function (e) {
    flash(e.feature);
});
var vector = new ol.layer.Vector({
    source: source
});
map.addLayer(vector);
// Constantly add animation elements to the map through timers
window.setInterval(addRandomFeature, 1000);See full example code »
                

Enjoy the result.

GraphicLayer

GraphicLayer mainly for point rendering of large data volumes on the web front-end.

This example needs to import

                            PapaParse (https://github.com/mholt/PapaParse)
                          

Create graphicLayer, Randomly draw 100,000 circles on the map.

                        // Create Greaphiclayer feature objects
var graphics = new ol.Graphic(new ol.geom.Point([-74.0095,40.6184]));
map.once('postrender', function () {
    var graphicLayer = new ol.layer.Image({
        source: new ol.source.Graphic({
            graphics: graphics,
            render: "canvas",
            map: map
        });
    });
    map.addLayer(graphicLayer);
});See full example code »
                    

Enjoy the result.

ECharts

ECharts is an open source visualization library based on JavaScript. It runs smoothly on PCs and mobile devices. It is compatible with most browsers (IE8/9/10/11, Chrome, Firefox, Safari, etc.). Echarts relies on ZRender, a lightweight vector graphics library that provides intuitive, interactive rich, highly customizable data visualization charts.

ECharts provides general line charts, histograms, scatter plots, pie charts, K-line charts, box plots for statistics, maps for geographic data visualization, heat maps, line graphs, for relational data visualization. Diagrams, treemaps, sunbursts, parallel coordinates for multidimensional visualization, funnel plots for BI, dashboards, and support for mashups between graphs and graphs.

This example needs to import

                            Echarts (https://echarts.apache.org/index.html)
                        

SuperMap iClient for OpenLayers provides ol3Echarts plugin to support ECharts' visualization effect. Let's take the special effect map of Beijing bus route as an example.

Create echartslayer, and add it to the map:

                    var echartslayer = new ol3Echarts();
echartslayer.appendTo(map);
                

Configuring the echartslayer properties and pass in the layer for rendering:

                // BusLines is layer data
var echartsOption = {
    series: [{
        type: 'lines',
        polyline: true,
        data: busLines,
        silent: true,
        lineStyle: {
            normal: {
                opacity: 0.2,
                width: 1
            }
        },
        progressiveThreshold: 500,
        progressive: 200,
        zlevel: 2
    },
    {
        type: 'lines',
        polyline: true,
        data: busLines,
        lineStyle: {
            normal: {
                width: 0
            }
        },
        effect: {
            constantSpeed: 20,
            show: true,
            trailLength: 0.1,
            symbolSize: 1.5
        },
        zlevel: 1
    }]
};
// Pass in the chart configuration object and render
echartslayer.setChartOptions(echartsOption);See full example code »
                

Enjoy the result.

MapV

MapV is an open source geographic data visualization library that can be used to display a large amount of geographic data, point, line, and surface data. Each type of data also has different display types, such as direct dot, heat map, grid, and aggregation.

MapV can display a large number of point data, which can be in the form of heat map, grid, honeycomb, point aggregation, color interval, radius, and so on. MapV can display a large number of line data, such as ordinary line drawing, highlighting overlay, heat line data display, etc., as well as various animation effects, suitable for scenes with a large number of tracks. A large number of custom surface data can also be displayed, which is displayed by color interval. The administrative area is also one of the application scenarios and can be used directly.

This example needs to import

MapV (https://mapv.baidu.com/)
                                                    

SuperMap iClient for OpenLayers provides ol.source.Mapv to support visualization.

                    new ol.source.Mapv(options)
                

Taking the MapV strong boundary map as an example to visualize the data.

Configuring style parameters object.

                // DataSet is an object that holds the json data object
var dataSet = new mapv.DataSet(data);
// Configure line layer attributes
var mapvLineOptions = {
    strokeStyle: 'rgba(55, 50, 250, 0.3)',
    // Color overlay mode
    globalCompositeOperation: 'lighter',
    shadowColor: 'rgba(55, 50, 250, 0.5)',
    // Projection blur series
    shadowBlur: 10,
    lineWidth: 1.0,
    // The way to draw points, line and polygon
    draw: 'simple'
};
var lineOptions = {
    map: map, dataSet: dataSet, mapvOptions: mapvLineOptions
};
map.addLayer(new ol.layer.Image({
    source: new ol.source.Mapv(lineOptions)
}));

var dataSet = new mapv.DataSet(timeData);
// Configure animated layer attributes
var mapvTimeOptions = {
    fillStyle: 'rgba(255, 250, 250, 0.9)',
    globalCompositeOperation: 'lighter',
    size: 1.5,
    animation: {
        // Show animation by time
        type: 'time',
        // Animation time range
        stepsRange: {
            start: 0,
            end: 100
        },
        // Trailing size of time animation
        trails: 1,
        // Single animation time
        duration: 5
    },
    draw: 'simple'
};
var timeOptions = {
    map: map,
    dataSet: dataSet,
    mapvOptions: mapvTimeOptions,
    attributions: new ol.Attribution({
        html: ''
    })
};
// Add MapV layer to the map
map.addLayer(new ol.layer.Image({
    source: new ol.source.Mapv(timeOptions)
}));See full example code »
                

Enjoy the result.

OSM Buildings

OSM Buildings is a visual library for building and displaying 2.5D architectural effects on 2D maps.

OSM Buildings supports GeoJSON format.

There are two ways to import OSMBuildings.js plugin.

1. Download OSMBuildings.js

Download OSMBuildings.js plugin from GitHub.

https://github.com/kekscom/osmbuildings
                

Include the JavaScript file in the <head> of your HTML file.

<script src="OSMBuildings.js"></script>
                                    

2. Import through CDN

<script src="https://cdn.osmbuildings.org/3.2.10/OSMBuildings.js"></script>
                                    

Core code.

                var data;
$.get('../data/buildings.json', function (geojson) {
    data = geojson;
    // Instantiate the OSMBuildings class, chained instance object methods
    new OSMBuildings(map)
        .date(new Date(2017, 5, 15, 17, 30))
        .set(geojson)
        .click(bindPopup);
});See full example code »
                

Enjoy the result.