SuperMap iClient for MapboxGL

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

Preparing your page

Get MapboxGL v1 and SuperMap iClient for MapboxGL

MapboxGL v1 and SuperMap iClient for MapboxGL are needed for development. Among them, MapboxGL v1 includes CSS files and JS files. You can get these documents in the following way:

MapboxGL v1

SuperMap iClient for MapboxGL

Import

Import files

The following is detailed account of how to import MapboxGL v1 files online via CDN, and how to import SuperMap iClient for MapboxGL through online sites.

Create a new HTML file, import MapboxGL v1 CSS file and JS file in < head> tag, and fill in BootCDN's hosting address, as follows:

      <!DOCTYPE html>
     <html>
        <head>
            <meta charset="UTF-8">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.13.2/mapbox-gl.css" rel="stylesheet">
            <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.13.2/mapbox-gl.js"></script>
        </head>
     </html>
  

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

      <!DOCTYPE html>
      <html>
          <head>
            <meta charset="UTF-8">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.13.2/mapbox-gl.css" rel="stylesheet" />
            <link href="https://iclient.supermap.io/dist/mapboxgl/iclient-mapboxgl.min.css" rel="stylesheet" />
            <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.13.2/mapbox-gl.js"></script>
            <script type="text/javascript" src="https://iclient.supermap.io/dist/mapboxgl/iclient-mapboxgl.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 MapboxGL by entering the following command on the command line:

 npm install @supermapgis/iclient-mapboxgl
      

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

Import the CSS files

Create a new HTML file and import the MapboxGL v1 CSS file and the iclient-mapboxgl CSS file into the <head> tag as follows:

                                                <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.13.2/mapbox-gl.css" rel="stylesheet" />

<link href="https://iclient.supermap.io/dist/mapboxgl/iclient-mapboxgl.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-mapboxgl"
            }
        ]
    ]
}
                              

Next, if you need QueryByBoundsParameters, QueryService, edit:

 import mapboxgl from 'mapbox-gl';
import {QueryByBoundsParameters, QueryService} from '@supermapgis/iclient-mapboxgl';

var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = new mapboxgl.Map({
    container: 'map',
    style: 'https://iserver.supermap.io/iserver/services/map-mvt-China/rest/maps/China/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true',
    center: [0, 0],
    zoom: 2
});

map.on('load', function () {
    var param = new QueryByBoundsParameters(...);
    new QueryService(url).queryByBounds(param).then(function (serviceResult) {
        map.addLayer(...);
    });
});
      

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

  Import all modules

     import mapboxgl from 'mapbox-gl';
import '@supermapgis/iclient-mapboxgl';

var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = new mapboxgl.Map({
    container: 'map',
    style: 'https://iserver.supermap.io/iserver/services/map-mvt-China/rest/maps/China/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true',
    center: [0, 0],
    zoom: 2
});

map.on('load', function () {
    var param = new mapboxgl.supermap.QueryByBoundsParameters(...);
    new mapboxgl.supermap.QueryService(url).queryByBounds(param).then(function (serviceResult) {
        map.addLayer(...);
    });
});
      

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.

  Import partial modules

     var mapboxgl = require('mapboxgl');
var QueryByBoundsParameters = require('@supermapgis/iclient-mapboxgl').QueryByBoundsParameters;
var QueryService = require('@supermapgis/iclient-mapboxgl').QueryService;

var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = new mapboxgl.Map({
    container: 'map',
    style: 'https://iserver.supermap.io/iserver/services/map-mvt-China/rest/maps/China/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true',
    center: [0, 0],
    zoom: 2
});

map.on('load', function () {
    var param = new QueryByBoundsParameters(...);
    new QueryService(url).queryByBounds(param).then(function (serviceResult) {
        map.addLayer(...);
    });
});

      

  Import all modules

     var mapboxgl = require('mapboxgl');
require('@supermapgis/iclient-mapboxgl');

var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = new mapboxgl.Map({
    container: 'map',
    style: 'https://iserver.supermap.io/iserver/services/map-mvt-China/rest/maps/China/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true',
    center: [0, 0],
    zoom: 2
});

map.on('load', function () {
    var param = new mapboxgl.supermap.QueryByBoundsParameters(...);
    new mapboxgl.superamp.QueryService(url).queryByBounds(param).then(function (serviceResult) {
        map.addLayer(...);
    });
});
      

AMD

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

  Import all modules

                                            require(['js/mapbox-gl.js'], function(mapboxgl) {
    window.mapboxgl = mapboxgl;
    require(['js/iclient-mapboxgl.js'], function() {
        var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
        var map = new mapboxgl.Map({
            container: 'map',
            style: 'https://iserver.supermap.io/iserver/services/map-mvt-China/rest/maps/China/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true',
            center: [0, 0],
            zoom: 2
        });

      map.on('load', function() {
        var param = new mapboxgl.supermap.QueryByBoundsParameters(...);
        new mapboxgl.supermap.QueryService(url).queryByBounds(param).then(function (serviceResult) {
            map.addLayer(...);
        });
    });
});
                                        

CMD

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

  Import all modules

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

    var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
    var map = new mapboxgl.Map({
        container: 'map',
        style: 'https://iserver.supermap.io/iserver/services/map-mvt-China/rest/maps/China/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true',
        center: [0, 0],
        zoom: 2
    });

    map.on('load', function() {
        var param = new mapboxgl.supermap.QueryByBoundsParameters(...);
        new mapboxgl.supermap.QueryService(url).queryByBounds(param).then(function (serviceResult) {
            map.addLayer(...);
        });
    });
});
                                            

Package configuration

Because iClient uses ES6, to be compatible with browsers that do not support ES6 syntax, some configuration, including syntax conversion, needs to be done during the packaging process.

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, a new HTML page has been created, and continue to add code to create maps in the page, as follows:

                         <!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <link href="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.13.2/mapbox-gl.css" rel="stylesheet">
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.13.2/mapbox-gl.js"></script>
        <script type="text/javascript" src="https://iclient.supermap.io/dist/mapboxgl/iclient-mapboxgl.js"></script>
    </head>
    <body>
        // The div displayed by map
         <div id="map" style="position:absolute;left:0px;right:0px;width:800px;height:500px;"></div>
    </body>
</html>
                     

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

  var map = new mapboxgl.Map({
var map = new mapboxgl.Map({
    container: 'map',
    style: {
        "version": 8,
        "sources": {
            "raster-tiles": {
                "attribution": attribution,
                "type": "raster",
                "tiles": ['https://iserver.supermap.io/iserver/services/map-china400/rest/maps/China/zxyTileImage.png?z={z}&x={x}&y={y}'],
                "tileSize": 256
            }
        },
        "layers": [{
            "id": "simple-tiles",
            "type": "raster",
            "source": "raster-tiles",
            "minzoom": 0,
            "maxzoom": 22
        }]
    },
    center: [120.143, 30.236], // Starting position
    zoom: 3 // Starting zoom
});See full example code »
                     

Enjoy the result.

Adding controls

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

Control Class name Introduction
Navigation mapboxgl.NavigationControl The default is in the top left corner of the map
Scale mapboxgl.ScaleControl The default is at the bottom left corner of the map
Fullscreen mapboxgl.FullscreenControl The default is in the top left corner of the map
Locate mapboxgl.GeolocateControl The default is in the top left corner of the map
Copyright mapboxgl.AttributionControl The default is in the lower right corner of the map
Swipe mapboxgl.Compare Swipe appears in the center of the map by default

When adding a control, you should initialize the map first, and then add the control to the map via the addControl() method, for example:

Navigation control

 // Add Control
 map.addControl(new mapboxgl.NavigationControl(), 'top-left');See full example code »
                        

Enjoy the result.

Scale control

 map.addControl(new mapboxgl.ScaleControl({}));See full example code »
                        

Enjoy the result.

Using vector tiles

Vector tiles 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

 var map = new mapboxgl.Map({
    container: 'map', // Container id
    style: 'https://iserver.supermap.io/iserver/services/map-mvt-China/rest/maps/China/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true',
    center: [120.143, 30.236], // Starting position
    zoom: 0,
    attributionControl: false
});See full example code »
                        

Enjoy the result.

Drawing symbols and graphics

Basic drawing

For the MapboxGL v1 itself does not support the drawing of point, line and polygon, the plugin mapbox-gl-draw.js needs to be imported.

                        https://github.com/mapbox/mapbox-gl-draw
                      

Online introduction can import the required plugins via the CDN into the <script> tag:

                 <script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/mapbox-gl-draw.js"></script>
             

When imported the plugin, the point, line and polygon drawing function is implemented by the following code:

  // Mapbox draw control
 var Draw = new MapboxDraw();
 map.addControl(Draw,'top-left')See full example code »
     

Enjoy the result.

Area and distance measurement

SuperMap iClient for MapboxGL supports area and distance measurement.

The following examples need to import

                        mapbox-gl-draw (https://github.com/mapbox/mapbox-gl-draw)
                      

Distance measurement

Here are the steps to create distance measurement function:

1.Construct service parameter 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, with the code as follows:

             // Set the parameters for measurement service
var measureParam = new mapboxgl.supermap.MeasureParameters();
// Set the vector object ({line} or {Polygon}) to measure, and geometry can obtain via initializatio
measureParam.geometry= geometry;
measureParam.unit = mapboxgl.supermap.Unit.METER;
             

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:

                 var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
// Initialize the service class, set the key parameters for service request
var measureService = new mapboxgl.supermap.MeasureService(url);
// Submit service request, pass the service query parameters, get the returned results and process them according to user needs
measureService.measureDistance(measureParam).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:

                 // Set the measurement bounds
var polygon = {
    "type": "Polygon",
    "coordinates": [[[24, 100], [40, 100], [40, 120], [24, 120], [24, 100]]]
};
// Instantiate the measurement constructor of the incoming polygon parameter
var areaMeasureParam = new mapboxgl.supermap.MeasureParameters(polygon);
 

2.Call the measurement function

Call the measurement function and get the return result, the code is as follows:

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

Enjoy the result.

Feature query

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

  • Query by specifying ID
  • Query by specifying SQL 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.

Using the interface mapboxgl.supermap.FeatureService to query geospatial features with ID 234 in the dataset "World:Countries".

         // Parameters of dataset ID query service
var idsParam = new mapboxgl.supermap.GetFeaturesByIDsParameters({
    IDs: [234],
    datasetNames: ["World:Countries"]
});
// Construct specified ID query
var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
new mapboxgl.supermap.FeatureService(url).getFeaturesByIDs(idsParam).then(function (serviceResult) {
    // Get the results returned by the server
    var featuers = serviceResult.result.features;
});See full example code »
         

Enjoy the result.

Query by specifing SQL conditions

Specify SQL query queries geographic vector features satisfying a specified SQL conditions in a dataset and display the results on the client. This example queries geographic features with specified SMID in the World dataset.

Use the interface mapboxgl.supermap.FeatureService to query the vector elements of "SMID=234" in the dataset "World:Countries".

              // Specify service parameters
var sqlParam = new mapboxgl.supermap.GetFeaturesBySQLParameters({
    queryParameter: {
        name: "Countries@World",
        attributeFilter: "SMID = 234"
    },
    datasetNames: ["World:Countries"]
});
// Construct SQL query
var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
new mapboxgl.supermap.FeatureService(url).getFeaturesBySQL(sqlParam).then(function (serviceResult) {
    // Get the results returned by the server
    var featuers = serviceResult.result.features;
});See full example code »
     

Enjoy the result.

Query by specifying rectangle bounds

Rectangle bounds query is to find vector feature that fits the rectangle bounds in specified dataset collection and displays results in the client. This example is: Querying features in the World Data Service for a specified scope of rectangles.

Use the interface mapboxgl.supermap.FeatureService to find the vector features in the dataset "World:Capitals" that match the scope of this rectangle.

          var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
// Specify rectangle bounds query processing
var sw = new mapboxgl.LngLat(-20, -20);
var ne = new mapboxgl.LngLat(20, 20);
var lngLatBounds = new mapboxgl.LngLatBounds(sw, ne);

// Set the rectangle bounds query parameters
var boundsParam = new mapboxgl.supermap.GetFeaturesByBoundsParameters({
    datasetNames: ["World:Capitals"],
    bounds: lngLatBounds
});
// Construct rectangle bounds query
new mapboxgl.supermap.FeatureService(url).getFeaturesByBounds(boundsParam).then(function (serviceResult) {
    // Get the results returned by the server
    var featuers = serviceResult.result.features;
});See full example code »
     

Enjoy the result.

Query by specifying arbitrary geometric range

Geometric range query is to find vector features in the specified dataset collection that match the geometric scope and displays the result in the client. This example is: Querying features of arbitrary geometric range in the World Data Service.

The interface mapboxgl.supermap.FeatureService uses intersected spatial query patterns in the "World:Countries" dataset to query vector elements that conform to the geometric range.

         var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
// Set the geometric query range
var queryPolygonGeometry = {
    "type": "Polygon",
    "coordinates": [[[0, 0], [-10, 30], [-30, 0], [0, 0]]]
};
// Set parameters for arbitrary geometry range query
var geometryParam = new mapboxgl.supermap.GetFeaturesByGeometryParameters({
    datasetNames: ["World:Countries"],
    geometry: queryPolygonGeometry,
    spatialQueryMode: "INTERSECT" // Intersect space query mode
});
// Construct arbitrary geometric range query
new mapboxgl.supermap .FeatureService(url).getFeaturesByGeometry(geometryParam).then(function (serviceResult) {
    // Get the results returned by the server
    var featuers = 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.

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

         var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
// Add center point of querying
var point = new mapboxgl.LngLat(104, 30);
// Set the parameters of distance query
var param = new mapboxgl.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 the degree
    geometry: point
});
// Construct distance query
new mapboxgl.supermap.QueryService(url).queryByDistance(param).then(function (serviceResult) {
    // Get the results returned by the server
    var featuers = 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 interface mapboxgl.supermap.FeatureService to find the vector elements whose buffer range is 10 degrees (map coordinate units) in the dataset "World:Capitals".

         var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
// Set the range of buffer query
var queryBufferGeometry = {
    "type": "Polygon",
    "coordinates": [[[-20, 20], [-20, -20], [20, -20], [20, 20], [-20, 20]]]
};
// Set the parameters for buffer query
var bufferParam = new mapboxgl.supermap.GetFeaturesByBufferParameters({
    datasetNames: ["World:Capitals"],
    bufferDistance: 10, // The unit of bufferDistance is the same as the coordinate system, their units both are degree
    geometry:queryBufferGeometry
});
// Construct buffer query, send a request to the server, and get the returned result
new mapboxgl.supermap .FeatureService(url).getFeaturesByBuffer(bufferParam).then(function (serviceResult) {
    // 获取服务器返回的结果
    var featuers = 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 interface mapboxgl.supermap.GridCellInfosService to 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.latlng.lng;
    var y = evt.latlng.lat;
    // Set the parameter information of the raster query
    var getGridCellInfosParam = new mapboxgl.supermap.GetGridCellInfosParameters({
        dataSourceName: "World",
        datasetName:"WorldEarth",
        X: x,
        Y: y
    });
    // Construct raster query
    new mapboxgl.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 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 the interface mapboxgl.supermap.FieldService 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 dataURL = "https://iserver.supermap.io/iserver/services/data-world/rest/data"
 // Set parameters for field query
var param = new mapboxgl.supermap.FieldParameters({
    datasource: "World",
    dataset: "continent_T"
});
var fieldName = 'SmID';
// Construct field query
new mapboxgl.supermap.FieldService(dataURL).getFields(param).then(function (serviceResult) {
    fieldStatistic(fieldName);
});
// Query specified field
function fieldStatistic(fieldName) {
    // Set the parameters of querying specified field
    var param = new mapboxgl.supermap.FieldStatisticsParameters({
        datasource: currentData.dataSourceName,
        dataset: currentData.dataSetName,
        fieldName: fieldName,
        statisticMode: [
            mapboxgl.supermap.StatisticMode.MAX,
            mapboxgl.supermap.StatisticMode.MIN,
            mapboxgl.supermap.StatisticMode.SUM,
            mapboxgl.supermap.StatisticMode.AVERAGE,
            mapboxgl.supermap.StatisticMode.STDDEVIATION,
            mapboxgl.supermap.StatisticMode.VARIANCE
        ]
    });
    // Send a request to the server and get the data
    new mapboxgl.supermap.FieldService(dataURL).getFieldStatisticsInfo(param, function (serviceResult) {
        // Get the returned data
        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.

Use the interface mapboxgl.supermap.FeatureService to add feature information to the dataset "Capitals".

        // Instantiate feature editing service
var url="https://iserver.supermap.io/iserver/services/data-world/rest/data";
var xmax = 120, xmin = 100, ymax = 50, ymin = 20;
var addPoint = [Math.floor(Math.random() * (xmax - xmin + 1) + xmin), Math.floor(Math.random() * (ymax - ymin + 1) + ymin)];
var pointFeature = {
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": addPoint
    },
    "properties": {POP: 1, CAPITAL: 'test'}
};
var featureService = new mapboxgl.supermap.FeatureService(url);
// Set the parameters of feature editing field
var addFeatureParams = new mapboxgl.supermap.EditFeaturesParameters({
    dataSourceName: "World",
    dataSetName: "Capitals",
    features: pointFeature,
    editType: "add",
    returnContent: true
});
// Using the feature editing service to send requests to the server and get data
featureService.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 concentrates on representing one theme is called a thematic map. In SuperMap, the thematic map is a symbolic display of the map layer which graphically represents 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 maps 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 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 theme map according to the parameters, returns the map to the client, and displays it by the client.

Taking the dot density thematic map 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.

                            // Get the thematic map service, url is the map access service
var themeService = new mapboxgl.supermap.ThemeService(url);
// Instantiate a dot density thematic map object and make corresponding settings for it.
var themeDotDensity = new mapboxgl.supermap.ThemeDotDensity({
    dotExpression:"Pop_1994",
    value: 5000000,
    style: new mapboxgl.supermap.ServerStyle({
        markerSize: 3,
        markerSymbolID: 12
    });
});
// Set the thematic map parameter class, which stores the parameters needed to create the theme, including the data source, dataset name, and thematic map object.
themeParameters =new mapboxgl.supermap.ThemeParameters({
    themes: [themeDotDensity],
    // To build thematic map dataset array, must set
    datasetNames: ["Countries"],
    // To build data source array that the thematic map dataset located at, must set
    dataSourceNames: ["World"] 
});
// Submit service request, pass the service querying parameters, get the thematic map information and process according to user needs
themeService.getThemeInfo(themeParameters).then(function (serviceResult) {
    // Get the results returned by the server
    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 MapboxGL include:

  • Unique thematic map
  • Range thematic map
  • Graduated symbols thematic map
  • Label thematic map
  • Chart thematic map
Unique thematic map

Projects the factors with the same theme value as a category, sets a rendering style for each category, such as color or symbol, the factors with the same theme value are in the same rendering style, to distinguish between different categories.

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

     // Build unique value thematic map layer
var themeLayer = new mapboxgl.supermap.UniqueThemeLayer("ThemeLayer", {
    // Turn on hover highlight
    isHoverAble: true
});
map.addlayer(themeLayer);
// Basic style of layer
themeLayer.style = new mapboxgl.supermap.ThemeStyle({
    shadowBlur: 3,
    shadowColor: "#000000",
    shadowOffsetX: 1,
    shadowOffsetY: 1,
    fillColor: "#FFFFFF"
});
// Hover highlight style
themeLayer.highlightStyle = new mapboxgl.supermap.ThemeStyle({
    stroke: true,
    strokeWidth: 2,
    strokeColor: 'blue',
    fillColor: "#00F5FF",
    fillOpacity: 0.2
});
// Attribute field name for Unique thematic map
themeLayer.themeField = "LANDTYPE";
                        

The code of Unique thematic map type and color configuration is as follows:

     // The style set of Unique thematic map
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 MapboxGL implements the range thematic map by the following code:

     // Define rangeThemeLayer range thematic map layer
var themeLayer = new mapboxgl.rangeThemeLayer("ThemeLayer", {
    // Turn on hover highlight
            isHoverAble: true,
            opacity: 0.8
        }).addTo(map);
themeLayer.style = new mapboxgl.supermap.ThemeStyle({
    shadowBlur: 16,
    shadowColor: "#000000",
    fillColor: "#FFFFFF"
});
// Hover highlight style
themeLayer.highlightStyle = new mapboxgl.supermap.ThemeStyle({
    stroke: true,
    strokeWidth: 4,
    strokeColor: 'blue',
    fillColor: "#00EEEE",
    fillOpacity: 0.8
});
// Attribute field name for Unique thematic map
themeLayer.themeField = "POP_DENSITY99";
// Style array, setting the corresponding style of the value
themeLayer.styleGroups = [{
        start: 0,
        end: 0.02,
        style: {
            color: '#FDE2CA'
        }
    }, {
        start: 0.02,
        end: 0.04,
        style: {
            color: '#FACE9C'
        }
    }
}];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 MapboxGL implements the graduated symbols thematic map by the following code:

     // Build a graduated symbols thematic map layer
var themeLayer = new mapboxgl.rankSymbolThemeLayer("RankSymbolLayer", mapboxgl.supermap.ChartType.CIRCLE);
// Specify the attribute fields for the thematic map creation. See the feature.attrs.CON2009 in addThemeLayer() below
themeLayer.themeField = "CON2009";
// The parameters of configuring chart
themeLayer.symbolSetting = {
    // The range of values that the graph is allowed to display. Data outside this range will not be graphed, required
    codomain: [0, 40000],
    // 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}
};
map.addLayer(themeLayer);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 MapboxGL used to implement the label thematic map is as follows:

     // Build a label thematic map layer
var themeLayer = new mapboxgl.labelThemeLayer("LabelThemeLayer");
themeLayer.style = new mapboxgl.supermap.ThemeStyle({
    labelRect: true,
    fontColor: "#000000",
    fontWeight: "bolder",
    fontSize: "18px",
    fill: true,
    fillColor: "#FFFFFF",
    fillOpacity: 1,
    stroke: false,
    strokeColor: "#8B7B8B"
});
map.addLayer(themeLayer);
// Attribute field name for the thematic map
themeLayer.themeField = "aqi";
// Style arrays, setting the corresponding style of specified value
themeLayer.styleGroups = [
    {
        start: 0,
        end: 51,
        style: {
            fillColor: "#6ACD06",
            fontSize: "17px"
        }
    }, {
        start: 51,
        end: 101,
        style: {
            fillColor: "#FBD12A",
            fontSize: "19px"
        }
    }
];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 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 MapboxGL 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: ["2009", "12010", "2011", "2012", "2013"],   //  The Content of X axis label
    backgroundRadius: [5, 5, 5, 5],
    backgroundStyle: {      // Parameters of fillet in background frame
        fillColor: "#d1eeee",
        shadowBlur: 12,
        shadowColor: "#d1eeee"
    }
};
// Graph 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
    },
};
// Graph 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: ["40 thousand", "30 thousand", "20 thousand", "10 thousand", "0"],         // The Content of Y axis label
    axisXLabels: ["2009", "12010", "2011", "2012", "2013"],         // The Content of X axis label
    backgroundStyle: {fillColor: "#CCE8CF"},        // The style of background
    backgroundRadius: [5, 5, 5, 5],        // Parameters of background frame fillet
};
// Set the option parameters of graphThemeLayer
var themeLayerOptions = {
    map: map,
    attributions: " ",
    themeFields: ["CON2009", "CON2010", "CON2011", "CON2012", "CON2013"],
    opacity: 0.9,
    chartsSetting: {},
};
// Create a statistic thematic map layer
var themeLayer = new mapboxgl.graphThemeLayer("BarLayer", "Bar", themeLayerOptions);
map.addLayer(themeLayer);See full example code »
 

Enjoy the result.

3D thematic map

The thematic map is based on a common map and focuses on a map of one or several natural or socio-economic phenomena in the map area. The thematic elements that are the subject of the diagram are detailed and the geographic basis of the content varies from topic to topic.

SuperMap iClient for MapboxGL supports for 3D thematic map

                                mapboxgl.supermap.RangeTheme3DLayer("range3DThemeLayer", options)
                            

The following takes the population density of the Beijing-Tianjin region as an example to display the data in three dimensions.

Specify the configuration items and data for the layer:

                            var themeField = "POP_DENSITY99", themeLayer;
buildThemeLayer();

function buildThemeLayer() {
    var getFeatureBySQLParams = new mapboxgl.supermap.GetFeaturesBySQLParameters({
        queryParameter: new mapboxgl.supermap.FilterParameter({
            name: "Jingjin",
            attributeFilter: "SMID > -1"
        }),
        toIndex: 500,
        datasetNames: ["Jingjin:BaseMap_R"]
});

    new mapboxgl.supermap.FeatureService(dataUrl, {
        eventListeners: {
            processCompleted: function (serviceResult) {
                if (serviceResult.error) {
                    alert("error:" + JSON.stringify(serviceResult.error));
                    return;
                }
                var result = serviceResult.result;
                if (result.features) {
                    createThemeLayer(result.features);
                }
            }
        },
        format: mapboxgl.supermap.DataFormat.GEOJSON,
    }).getFeaturesBySQL(getFeatureBySQLParams);
}

// Create a thematic map layer
function createThemeLayer(data) {
    popup = new mapboxgl.Popup({closeOnClick: true}).addTo(map);
    themeLayer = new mapboxgl.supermap.RangeTheme3DLayer("range3DThemeLayer", {
        heightField: themeField,
        themeField: themeField,
        parseNumber: true,
        enableHighlight: true,

        heightStops: [
            [0.01, 1000], [0.1, 5000], [0.2, 6000]
        ],
        colorStops: [
            [0.01, "#FDE2CA"], [0.02, "#FACE9C"], [0.04, "#F09C42"], [0.06, "#D0770B"], [0.1, "#945305"], [0.2, "#714902"]
        ],

        // Display legend
        showLegend: true,
        legendTitle: resources.text_densityOfPopulation,
        legendOrientation: 'vertical'
    });
    themeLayer.setHighlightStyleOptions({
        color: "#058e94", callback: highlightCallback
    }).setData(data).addTo(map);
    map.easeTo({
        pitch: 60,
        bearing: 0
    })
    type: 'time',
    stepsRange: {
        start: 0,
        end: 100
    },
    trails: 1,
    duration: 5
    draw: 'simple'
};

var mapVAnimationLinelayer = new mapboxgl.supermap.MapvLayer("", dataSet, options);

map.addLayer(mapVAnimationLinelayer);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 MapboxGL include:

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

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 dsBufferAnalystParams = new mapboxgl.supermap.DatasetBufferAnalystParameters({
    // The dataset name in the datasource used for buffer analysis
    dataset: "RoadLine2@Changchun",
    // Set the filter condition for feature set in the dataset
    filterQueryParameter: new mapboxgl.supermap.FilterParameter({
        // Attribute filter condition
        attributeFilter: "NAME='Tuanjie Road'"
    }),
    // Set buffer analysis common parameters
    bufferSetting: new mapboxgl.supermap.BufferSetting({
        // Set end type, including FLAT and ROUND
        endType: mapboxgl.supermap.BufferEndType.ROUND,
        // Left radius
        leftDistance: {value: 10},
        // Right radius
        rightDistance: {value: 10},
        // Set the number of line segments for round buffer
        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-sample/restjsr/spatialanalys"
// Define buffer analysis service
var bufferServiceByDatasets =new mapboxgl.supermap.SpatialAnalystService(serviceUrl);
// Send the request to the server and display the results returned from the server on the map
bufferServiceByDatasets.bufferAnalysis(dsBufferAnalystParams).then(function (serviceResult){
    // Get the results returned from the server
    var result = serviceResult.result;
});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-sample/restjsr/spatialanalyst";
// Set the parameters for the Thiessen polygon analysis
var dsThiessenAnalystParameters = new mapboxgl.supermap.DatasetThiessenAnalystParameters({
    dataset: "Town_P@Jingjin"
});
// Define Thiessen polygon analysis
new mapboxgl.supermap.SpatialAnalystService(serviceUrl).thiessenAnalysis(dsThiessenAnalystParameters).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 dsOverlayAnalyParams = new mapboxgl.supermap.DatasetOverlayAnalystParameters({
    // The name of the source dataset of overlay analysis
    sourceDataset: "BaseMap_R@Jingjin",
    // The name of the operate dataset of overlay analysis
    operateDataset: "Neighbor_R@Jingjin",
    // Tolerance
    tolerance: 0,
    // The type of overlay analysis
    operation: mapboxgl.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.

                                        var serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst";
// Define overlay analysis service
var overlayAnalystService =new mapboxgl.supermap.SpatialAnalystService(serviceUrl);
// Send the request to the server and display the results returned from the server on the map
overlayAnalystService.overlayAnalysis(dsOverlayAnalyParams).then(function (serviceResult) {
    // Get the returned features data
    var features = serviceResult.result.regions;
});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 mapboxgl.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 mapboxgl.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 = {
    "type": "Feature",
    "geometry": {
        "type": "Polygon",
        "coordinates": [[
            [0, 4010338],
            [1063524, 4010338],
            [1063524, 3150322],
            [0, 3150322]
        ]]
    }
};
// Set surface analysis parameters
var extractParams = new mapboxgl.supermap.SurfaceAnalystParametersSetting({
    datumValue: 0, // The datum value in surface analysis
    interval: 2, // The interval value
    resampleTolerance: 0, // The resample tolerance
    smoothMethod: mapboxgl.supermap.SmoothMethod.BSPLINE, // The method used for smoothing
    smoothness: 3, // The smoothness of contour lines
    clipRegion: region // The clip object
});
// The surface analysis parameters
var surfaceAnalystParams = new mapboxgl.supermap.DatasetSurfaceAnalystParameters({
    extractParameter: extractParams, // The surface analysis parameters
    dataset: "SamplesP@Interpolation", // The name of the source dataset in overlay analysis
    resolution: 3000, // The resoluton of intermediate results
    zValueFieldName: "AVG_TMP" // The name of the field used for extraction
});
 

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.

                                        var serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst" ;
// Initialize surface analysis service instance
var surfaceAnalystService =new mapboxgl.supermap.SpatialAnalystService(serviceUrl);
// Send the request to the server and process the resullts
surfaceAnalystService.surfaceAnalysis(surfaceAnalystParams).then(function (serviceResult) {
    // Get the returned features data
    var features = serviceResult.result.regions;
});See full example code »
 

Enjoy the result.

Route calculate measure

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.

      // In order to construct routeLine  of sourceRoute
var piontLists = [
    [116.2143386597, 39.8959419733, 0],
    [116.217501999125, 39.896670999665, 282.3879789906],
    [116.220156000875, 39.896820999605, 509.9746364534],
    [116.228716999, 39.8968419995966, 1242.1340098965],
    [116.25000000025, 39.8968619995886, 3062.3045713007],
    [116.27412300025, 39.8967689996258, 5125.3836697258],
    [116.310443000875, 39.8971139994878, 8231.7823666408],
    [116.344168500812, 39.8976724992644, 11116.7053546891]
];

var LineGeometryData = {
    "type": "Feature",
    "geometry": {
        "type": "LineString",
        "coordinates": piontLists
    }

var routeObj = LineGeometryData.geometry.coordinates;
var routeLine = LineGeometryData;

var point = [routeObj[4][0], routeObj[4][1]];
var pointGeometryData = {
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": point
    }
};
// Create routeCalculateMeasureService
    var serviceUrl ="https://iserver.supermap.io/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst";
    var routeCalculateMeasureService =new mapboxgl.supermap.SpatialAnalystService(serviceUrl);
    // Set parameters
    var routeCalculateMeasureParameters = new mapboxgl.supermap.RouteCalculateMeasureParameters({
        "sourceRoute": routeLine, // Route Type
        "point": pointGeometryData,// Query point
        "tolerance": 0.0001,
        "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

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 6753 meters 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.

     // In order to construct routeLine of sourceRoute
var piontLists = [
    [116.2143386597, 39.8959419733, 0],
    [116.217501999125, 39.896670999665, 282.3879789906],
    [116.220156000875, 39.896820999605, 511.787745072744],
    [116.228716999, 39.8968419995966, 1253.201708792909],
    [116.25000000025, 39.8968619995886, 3103.167523778722],
    [116.27412300025, 39.8967689996258, 5201.062444476062],
    [116.310443000875, 39.8971139994878, 8360.617856315024],
    [116.344168500812, 39.8976724992644, 11294.738396325054]
];

var LineGeometryData = {
    "type": "Feature",
    "geometry": {
        "type": "LineString",
        "coordinates": piontLists
    }
};

var routeLine = LineGeometryData;
// Construct Route Locator Point service
var serviceUrl ="https://iserver.supermap.io/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst";
var routeLocatorService =new mapboxgl.supermap.SpatialAnalystService(serviceUrl);
// Set Route Locator Point parameters
var routeLocatorParams_point = new mapboxgl.supermap.RouteLocatorParameters({
    "sourceRoute": routeLine, // The route object
    "type": "POINT", // Type, point or line
    "measure": 6753, // M value
    "offset": 0, // Offset
    "isIgnoreGap": true //  Whether to ignore distance between child object
});
// Send the request to the server and display the results on the client side after handling
routeLocatorService.routeLocate(routeLocatorParams_point).then(function (serviceResult) {
    // Get the results returned from the server
    var result = routeCalculateServiceResult.result;
});
See full example code »
 

Enjoy the result.

Route locator line

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 1123 meters to 4489 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:

             // In order to construct routeLine of sourceRoute
 var piontLists = [
    [116.2143386597, 39.8959419733, 0],
    [116.217501999125, 39.896670999665, 282.3879789906],
    [116.220156000875, 39.896820999605, 511.787745072744],
    [116.228716999, 39.8968419995966, 1253.201708792909],
    [116.25000000025, 39.8968619995886, 3103.167523778722],
    [116.27412300025, 39.8967689996258, 5201.062444476062],
    [116.310443000875, 39.8971139994878, 8360.617856315024],
    [116.344168500812, 39.8976724992644, 11294.738396325054]
];

var LineGeometryData = {
    "type": "Feature",
    "geometry": {
        "type": "LineString",
        "coordinates": piontLists
    }
 };

var routeLine = LineGeometryData;
// Set Route Locator Line parameters
var routeLocatorParams_line = new mapboxgl.supermap.RouteLocatorParameters({
    "sourceRoute": routeLine, // The route object
    "type": "LINE", // Type, point or line
    "startMeasure": 1123, //The from value of the line
    "endMeasure": 4489, // he to value of the line
    "isIgnoreGap": true // Whether to ignore distance between child objects
});
// Create spatial analysis service
var serviceUrl ="https://iserver.supermap.io/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst";
var routeLocatorService =new mapboxgl.supermap.SpatialAnalystService(serviceUrl);
// Send the request to the server and display the results on the client side after handling
routeLocatorService.routeLocate(routeLocatorParams_line).then(function (serviceResult) {
    // Get the results returned from the server
    var result = routeCalculateServiceResult.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 mathExpressionAnalysisService =new mapboxgl.supermap.SpatialAnalystService(serviceUrl);
// Define the grid algebraic operation server parameters
var mathExpressionAnalysisParameters = new mapboxgl.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
mathExpressionAnalysisService.mathExpressionAnalysis(mathExpressionAnalysisParameters).then(function (serviceResult) {
    //Get the data returned by the server
    var 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 mapboxgl.supermap.TerrainSlopeCalculationParameters({
    dataset: "JingjinTerrain@Jingjin",
    zFactor:0.00001, // Elevation scaling factor
    slopeType:"DEGREE", // The unit type of slope result 
    terrainAnalystSetting: new mapboxgl.supermap.terrainAnalystSetting({
        boundsType: mapboxgl.supermap.BoundsType.UNION, // The range type of Analysis result dataset
        cellSizeType: mapboxgl.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 mapboxgl.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 mapboxgl.supermap.TerrainAspectCalculationParameters({
    dataset: "JingjinTerrain@Jingjin",
    // Basic environment settings of terrain analysis
    terrainAnalystSetting: new mapboxgl.supermap.terrainAnalystSetting({
        boundsType: mapboxgl.supermap.BoundsType.UNION,// The range type of Analysis result dataset
        cellSizeType: mapboxgl.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 mapboxgl.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.

                                // Set terrain curvature calculation service parameters
var terrainCurvatureCalculationParameters = new mapboxgl.supermap.TerrainCurvatureCalculationParameters({
    dataset: "JingjinTerrain@Jingjin",
    zFactor: 1.0,
    averageCurvatureName: "CurvatureA",
    deleteExistResultDataset: true
});
// Construct terrain curvature calculation service instance
var terrainCurvatureCalculationService =new mapboxgl.supermap.SpatialAnalystService(serviceUrl);
// Initiate terrain curvature calculation request to the iServer
var terrainCurvatureCalculationService.terrainCurvatureCalculate(terrainCurvatureCalculationParameters).then(function (serviceResult) {
   // Get the results returned from the server
    var 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 mapboxgl.supermap.TerrainCutFillCalculationParameters({
    dataset: "JingjinTerrain@Jingjin",
    cutFillType:"REGION3D",
    // Create three-dimensional surface object as the cut and fill calculation object
    region3D: new mapboxgl.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 mapboxgl.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.

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.

                                    paths.points = [26, 180];
 // Traffic transfer query parameters
var params = new mapboxgl.supermap.TransferSolutionParameters({
    var params = new mapboxgl.supermap.TransferSolutionParameters({
        // Maximum number of transfer guides
        solutionCount: 6,
        // Traffic transfer strategy type
        transferTactic: LESS_TIME,
        // Consumption weight ratio of walking and bus
        walkingRatio: 10,
        // Starting point coordinates
        points: paths.points
    })
});
var serviceUrl = "https://iserver.supermap.io/iserver/services/traffictransferanalyst-sample/restjsr/traffictransferanalyst/Traffic-Changchun";
// Send a request to server and get the result
new mapboxgl.supermap.TrafficTransferAnalystService(serviceUrl)
        .analysisTransferSolution(params).then(function (serviceResult) {
            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).

 // Set the query parameters
var params = new mapboxgl.supermap.TransferPathParameters({
    // Starting point coordinates
    points: paths["points"],
    // Transfer route, including route ID, start and end points, etc.
    transferLines: transLines
});
// Send a request to server and get the result
   new mapboxgl.supermap.TrafficTransferAnalystService(serviceUrl)
        .analysisTransferPath(params).then(function (serviceResult) {
            var transGuide = serviceResult.result;
        });
     

Network analysis

SuperMap iClient for MapboxGL 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.

                        // Add centers
var marker = new mapboxgl.Marker()
    .setLngLat([5605, -3375])
    .addTo(map);
// Network analysis result parameter
var resultSetting = new mapboxgl.supermap.TransportationAnalystResultSetting({
    // Whether to include arc feature collections in the analysis results
    returnEdgeFeatures: true,
    // Whether the returned arc feature collection contains collection object information
    returnEdgeGeometry: true,
    // Whether the returned result contains the set of arc IDs
    returnEdgeIDs: true,
    // Whether the returned analysis result always contains a node feature set
    returnNodeFeatures: true,
    // Whether the returned node feature collection contains the collection object information
    returnNodeGeometry: true,
    // Whether the returned analysis result contains the passed node ID set
    returnNodeIDs: true,
    // Whether the travel guide set is included in the returned analysis result
    returnPathGuides: true,
    // Whether the returned object contains a set of route objects
    returnRoutes: true
});
// Network analysis common parameters
var analystParameter = new mapboxgl.supermap.TransportationAnalystParameter({
    // The analysis result content
    resultSetting: resultSetting,
    // The name of the resistance field
    weightFieldName: "length"
});
// Service area analysis parameter
var findServiceAreasParams = new mapboxgl.supermap.FindServiceAreasParameters({
    // Service site array
    centers: [marker.getLatLng()],
    // Whether to specify the node of the path analysis by the node ID
    isAnalyzeById: false,
    // Traffic network analysis common parameters
    parameter: analystParameter,
    // Resistance radius of service provided by each service site
    weights: weightsArray
});
                        

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
var serviceUrl = "https://iserver.supermap.io/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun";
// Create a service area analysis service instance
var service = new mapboxgl.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and get the returned result
service.findServiceAreas(findServiceAreasParams).then(function (serviceResult) {
    var result = serviceResult.result;
});
                        

Closest facility analysis

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 take 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.

                            var resultSetting = new mapboxgl.supermap.TransportationAnalystResultSetting({
    // Whether to include arc feature collections in the analysis results
    returnEdgeFeatures: true,
    // Whether the returned arc feature collection contains collection object information
    returnEdgeGeometry: true,
    // Whether the returned result contains the set of arc IDs
    returnEdgeIDs: true,
    // Whether the returned analysis result always contains a node feature set
    returnNodeFeatures: true,
    // Whether the returned node feature collection contains the collection object information
    returnNodeGeometry: true,
    // Whether the returned analysis result contains the passed node ID set
    returnNodeIDs: true,
    // Whether the travel guide set is included in the returned analysis result
    returnPathGuides: true,
    // Whether the returned object contains a set of route objects
    returnRoutes: true
});
// Set traffic network analysis common parameters
var analystParameter = new mapboxgl.supermap.TransportationAnalystParameter({
    // The analysis result content
    resultSetting: resultSetting,
    turnWeightField: "TurnCost",
    // The name of the resistance field
    weightFieldName: "length"
});
var findClosetFacilitiesParams = new mapboxgl.supermap.FindClosestFacilitiesParameters({
    // Incident, generally for event locations that require service facility services
    event: new mapboxgl.LngLat(-3700, 5000),
    // Number of facilities to find
    expectFacilityCount: 1,
    // Facility collection, generally the location of the service facility providing the service
    facilities: [new mapboxgl.LngLat( 2500,-3500), new mapboxgl.LngLat(5500,-2500), new mapboxgl.LngLat(7000,-4000)],
    // Whether the event point and facility point are specified by the node ID number
    isAnalyzeById: false,
    // Network common parameter
    parameter: analystParameter
});
                        

Defines closest facility analysis object, which is used to pass the latest facility lookup analysis service parameters set by the client to the server, and receives the latest facility analysis result 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 Closest facilities analysis service instance
var serviceUrl = "https://iserver.supermap.io/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun";
var findClosetFacilitiesService = new mapboxgl.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and get the returned result
findClosetFacilitiesService.findClosestFacilities(findClosetFacilitiesParams).then(function (serviceResult) {
    var result = serviceResult.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 = mapboxgl.supermap.SupplyCenterType.FIXEDCENTER;
var supplyCenterType_NULL = mapboxgl.supermap.SupplyCenterType.NULL;
var supplyCenterType_OPTIONALCENTER = mapboxgl.supermap.SupplyCenterType.OPTIONALCENTER;
// Taking one center point as an example
var supplyCenters = [new mapboxgl.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
findLocationParameter = new mapboxgl.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
var serviceUrl = "https://iserver.supermap.io/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun";
var findLocationService = new mapboxgl.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and get the returned result
findLocationService.findLocation(findLocationParams).then(function (serviceResult) {
    var result = serviceResult.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.

                            var resultSetting = new mapboxgl.supermap.TransportationAnalystResultSetting({
    // Whether to include arc feature collections in the analysis results
    returnEdgeFeatures: true,
    // Whether the returned arc feature collection contains collection object information
    returnEdgeGeometry: true,
    // Whether the returned result contains the set of arc IDs
    returnEdgeIDs: true,
    // Whether the returned analysis result always contains a node feature set
    returnNodeFeatures: true,
    // Whether the returned node feature collection contains the collection object information
    returnNodeGeometry: true,
    // Whether the returned analysis result contains the passed node ID set
    returnNodeIDs: true,
    // Whether the travel guide set is included in the returned analysis result
    returnPathGuides: true,
    // Whether the returned object contains a set of route objects
    returnRoutes: true
 });
// Network analysis common parameters
var analystParameter = new mapboxgl.supermap.TransportationAnalystParameter({
    // The analysis result content
    resultSetting: resultSetting,
    // The name of the resistance field
    weightFieldName: "length"
});
// Multi-traveler analysis parameters
var findMTSPPathsParams = new mapboxgl.supermap.FindMTSPPathsParameters({
    // Distribution center collection
    centers: [new mapboxgl.LngLat(6000, -5500), new mapboxgl.LngLat( 5500, -2500), new mapboxgl.LngLat(2500, -3500)],
    // Whether to specify the distribution center point and the delivery destination point by the node ID number
    isAnalyzeById: false,
    // Delivery target set
    nodes: [new mapboxgl.LngLat(5000, -5000), new mapboxgl.LngLat(8000, -2800)],
    // Whether the delivery mode is the minimum cost of total cost
    hasLeastTotalCost: true,
    // Network analysis common parameters
    parameter: analystParameter
});
                        

Submit 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 multi-traveler service instance
var serviceUrl = "https://iserver.supermap.io/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun";
var findMTSPPathsService = new mapboxgl.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and process the returned result
findMTSPPathsService.findMTSPPaths(findMTSPPathsParams).then(function (serviceResult) {
    var result = serviceResult.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.

                            var resultSetting = new mapboxgl.supermap.TransportationAnalystResultSetting({
    // Whether to include arc feature collections in the analysis results
    returnEdgeFeatures: true,
    // Whether the returned arc feature collection contains collection object information
    returnEdgeGeometry: true,
    // Whether the returned result contains a set of arc IDs
    returnEdgeIDs: true,
    // Whether the returned analysis result always contains a node feature set
    returnNodeFeatures: true,
    // Whether the returned node feature collection contains the collection object information
    returnNodeGeometry: true,
    // Whether the returned analysis result contains the passed node ID set
    returnNodeIDs: true,
    // Whether the travel guide set is included in the returned analysis result
    returnPathGuides: true,
    // Whether the returned object contains a set of route objects
    returnRoutes: true
});
// Network analysis common parameters
var analystParameter = new mapboxgl.supermap.TransportationAnalystParameter({
    // The analysis result content
    resultSetting: resultSetting,
    // The name of the resistance field
    weightFieldName: "length"
});
// Best path analysis parameters
var findPathParams = new mapboxgl.supermap.FindPathParameters({
    // Whether to specify the node of the path analysis by the node ID
    isAnalyzeById: false,
    // An array of nodes or facilities which the best path analysis passes through
    nodes: [new mapboxgl.LngLat( 4000, -3000), new mapboxgl.LngLat(5500, -2500), new mapboxgl.LngLat(6900, -4000)],
    // Whether to perform the best path analysis according to the minimum number of arcs
    hasLeastEdgeCount: false,
    // Network analysis common parameters
    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
var serviceUrl = "https://iserver.supermap.io/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun";
// Send a request to the server and process the returned result, then show on the client
findPathService.findPath(findPathParams).then(function (serviceResult) {
// Get the result from server
    var result = serviceResult.result;
});
                        

Conneted 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 mapboxgl.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 mapboxgl.supermap.NetworkAnalystService(serviceUrl);
connectedEdgesAnalystService.connectedEdgesAnalyst(connectedEdgesAnalystParameters).then(function (serviceResult) {
    // Get the result from server
    var result = serviceResult.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 mapboxgl.supermap.TraceAnalystParameters({
    edgeID:101,
    traceType:0,// 0 denotes traceUp and 1 denotes downstream 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 mapboxgl.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;
}); 
                    

Address match

SuperMap iClient for MapboxGL 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 or the location at 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 mapboxgl.supermap.GeoCodingParameter({
    address: "超图软件",
    fromIndex:0, // Start index value of the returned object
    toIndex:10, // End index value of the returned object
    filters: "北京市,朝阳区",
    prjCoordSys:{epsgcode26},
    maxReturn:3 // Maximum number of returned results
});
// Create address match service
var addressUrl = "https://iserver.supermap.io/iserver/services/addressmatch-Address/restjsr/v1/address";
var addressMatchService =new mapboxgl.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 mapboxgl.supermap.GeoDecodingParameter({
    x: 116.3518541194,
    y: 40.00097839595,
    fromIndex: 0, // Start index value of the returned object
    toIndex: 10, // End index value of the returned object
    filters: "",
    prjCoordSys: {epsgcode26},
    maxReturn: 3,
    geoDecodingRadius: 1000
});
// Create address match service
var addressUrl = "https://iserver.supermap.io/iserver/services/addressmatch-Address/restjsr/v1/address",
addressMatchService = new mapboxgl.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 MapboxGL 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 clip analysis
  • Summary attributes analysis
  • Topology validator analysis

Density analysis

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

  • Simple dot 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 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 mapboxgl.supermap.KernelDensityJobParameter({
    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 dot 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,
    query: [-74.050,40.650,-73.850,40.850], // Range
    radius: 300,
    meshSizeUnit: mapboxgl.supermap.AnalystSizeUnit.METER,
    radiusUnit: mapboxgl.supermap.AnalystSizeUnit.METER,
    areaUnit: mapboxgl.supermap.AnalystAreaUnit.SQUAREMILE,
});
                    

Send a request to the server for density anlysis and get the returned result.

                        // Create a density service instance
var processingUrl ="https://iserver.supermap.io/iserver/services/spatialprocessing/rest/v1/jobs";
var processingService = new mapboxgl.supermap.ProcessingService(processingUrl);
// Send a request to the server for density anlysis and get the returned result
processingService.addKernelDensityJob(kernelDensityJobParams).then(function (serviceResult) {
    // Get the result from 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 mapboxgl.supermap.SummaryMeshJobParameter({
    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: mapboxgl.supermap.StatisticAnalystMode.MAX, // Statistical mode. Must be consistent with the number of weight fields
    type: mapboxgl.supermap.SummaryType.SUMMARYMESH,
    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 processingUrl ="https://iserver.supermap.io/iserver/services/spatialprocessing/rest/v1/jobs";
var processingService = new mapboxgl.supermap.ProcessingService(processingUrl);
// Send a request to the server for density anlysis and get the returned result
processingService.addSummaryMeshJob(summaryMeshJobParam).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 query object dataset, the space query with the queryed dataset is done by default with the object with the smallest SmID.

This example needs to import

                        mapbox-gl-draw (https://github.com/mapbox/mapbox-gl-draw)
                      

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 mapboxgl.supermap.SingleObjectQueryJobsParameter({
    datasetName: 'ProcessingData_processing_newyorkZone_R',
    datasetQuery: 'ProcessingData_processing_singleRegion_R', // The name of the dataset where the query object is located
    mode:'INTERSECT'
});
                        

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 processingUrl ="https://iserver.supermap.io/iserver/services/spatialprocessing/rest/v1/jobs";
var processingService = new mapboxgl.supermap.ProcessingService(processingUrl);
// Send a request to the server for single object spatial query anlysis and get the returned result
processingService.addQueryJob(singleObjectQueryJobsParam).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.

                        var summaryRegionJobParam = new mapboxgl.supermap.SummaryRegionJobParameter({
    datasetName: 'ProcessingData_processing_newyorkZone_R',
    // Summary polygon dataset, used in polygon summary
    regionDataset: 'regionDataset',
    // Symmary type, includes mesh summary and polygon summary
    type: mapboxgl.supermap.SummaryType.SUMMARYMESH,
    // 0 represents quadrilateral mesh, and 1 represents hexagonal mesh
    meshType:0,
    query: [-74.050,40.650,-73.850,40.850], // Range
    standardSummaryFields: true,
    // The mode of statistics by standard attribute fields
    standardStatisticModes: mapboxgl.supermap.StatisticAnalystMode.MAX,
    // The name of statistics by standard attribute fields
    standardFields: "LocationID",
    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: mapboxgl.supermap.AnalystSizeUnit.METER, // The unit of mesh size
    sumShape:true // Whether to count the length or area
});
                    

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

                        // Create regional summary anlysis instance
var processingUrl ="https://iserver.supermap.io/iserver/services/spatialprocessing/rest/v1/jobs";
var processingService = new mapboxgl.supermap.ProcessingService(processingUrl);
// Send a request to the server for single object spatial query anlysis and get the returned result
processingService.addSummaryRegionJob(summaryRegionJobParam).then(function (serviceResult){
    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.

This example needs to import

                        mapbox-gl-draw (https://github.com/mapbox/mapbox-gl-draw)
                      

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.

                            var vectorClipJobsParam = new mapboxgl.supermap.VectorClipJobsParameter({
    datasetName: 'ProcessingData_newyork_taxi_2013-01_14k', // Source dataset
    datasetOverlay: 'ProcessingData_processing_singleRegion_R', // Clip dataset
    mode:mapboxgl.supermap.ClipAnalystMode.CLIP // Clip 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 processingUrl ="https://iserver.supermap.io/iserver/services/spatialprocessing/rest/v1/jobs";
var processingService = new mapboxgl.supermap.ProcessingService(processingUrl);
// Send a request to the server for single object spatial query anlysis and get the returned result, and show on the map
processingService.addVectorClipJob(vectorClipJobsParam).then(function (serviceResult){
    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 mapboxgl.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 mapboxgl.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, including topology validator dataset, topology rule and tolerance.

                                    // Topology validator analysis parameters
var topologyValidatorJobsParameter = new mapboxgl.supermap.TopologyValidatorJobsParameter({
    datasetName: 'samples_processing_newyorkZone_R',
    datasetTopology: 'samples_processing_newyorkResidential_R',// The name of the dataset where the validate object is located
    rule: mapboxgl.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 mapboxgl.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.

                    // Create a map
var map,urlQuery ="https://iserver.supermap.io/iserver/services/map-china400/rest/maps/China_4326",
urlDataFlow ="https://iserver.supermap.io/iserver/services/dataflowTest/dataflow";
var popup = new mapboxgl.Popup();
map.on('load', function () {
    var options = {
        ws: urlDataFlow
    };
    var dataFlowSubscribe = new mapboxgl.supermap.DataFlowService(options.ws, {
        geometry: options.geometry,
        prjCoordSys: options.prjCoordSys,
        excludeField: options.excludeField
    }).initSubscribe();
    dataFlowSubscribe.on('messageSuccessed', function (msg) {
        popup.remove();
        addLayer(msg);
    });
    query();
});

// 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
function query() {
       var param = new mapboxgl.supermap.QueryBySQLParameters({
       queryParams: {
            name: "Main_Road_L@China#1",
            attributeFilter: "SMID = 1755"
       }
    });
    queryService = new mapboxgl.supermap.QueryService(urlQuery).queryBySQL(param).then(function (serviceResult) {
        featureResult = serviceResult;
        dataFlowBroadcast = new mapboxgl.supermap.DataFlowService(urlDataFlow).initBroadcast();
        dataFlowBroadcast.on('broadcastSocketConnected', function (e) {
            timer = window.setInterval("broadcast()", 2000);
        });
    });
}
var count = 200;

function broadcast() {

    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()
        }
    };
    dataFlowBroadcast.broadcast(feature);
    count += 3;
}

function addLayer(msg) {
    if (!msg.featureResult) {
        return;
    }
    var feature = msg.featureResult;
    var coord = feature.geometry.coordinates;
    var data = {
        geometry: {
            type: 'Point',
            coordinates: coord,
        },
        type: "Feature"
    };

    if (!map.getSource('location')) {
        map.addSource('location', {
            'type': 'geojson',
            'data': data
        });
        map.addLayer({
            "id": "point",
            "type": "circle",
            "paint": {
                "circle-radius": 6,
                "circle-color": 'red',
            },
            "source": 'location'
        });
    }
}See full example code »
            

Enjoy the result.

Data visualization

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

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 MapboxGL:

  • 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.

        // Set the number and radius of hot spots
heatMapLayer = new mapboxgl.supermap.HeatMapLayer(
    "heatMap",
    {
        "map": map,
        "id": "heatmap",
        "radius": 45,
        // Specify featureWeight value is used to create a heat map for the heat weight value:
        "featureWeight": "value",
    }
);

// Construct heat map center
function createHeatPoints() {
    clearHeatPoints();
    var heatPoints = [];
    var num = 200;
    var radius = 50;
    var unit = "px";
    heatMapLayer.useGeoUnit = true;
}
heatMapLayer.radius = radius;

var features = [];

for (var i = 0; i < num; i++) {

    features[i] =
    {
        "type": "feature",
        "geometry": {
            "type": "Point",
            "coordinates": [
                Math.random() * 360 - 180,
                Math.random() * 160 - 80]
        },
        "properties": {
            "value": Math.random() * 9,
        }
    };
}

var heatPoints = {
    "type": "FeatureCollection",
    "features": features
};

heatMapLayer.addFeatures(heatPoints);
map.addLayer(heatMapLayer);See full example code »
                

Enjoy the result.

GraphicLayer

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

This example needs to import

                        Papaparse (https://github.com/mholt/PapaParse)
deck.gl (https://github.com/visgl/deck.gl)
dat-gui (https://github.com/dataarts/dat.gui)
                      

Let's take the New York taxi pick-up point as an example for visual display.

Import papaparse.min.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.3.2/papaparse.min.js"></script>
                    $.get('../data/nyc-taxi.csv', function (csvstr) {
    // Read the data in the file
    var result = Papa.parse(csvstr, {skipEmptyLines: true, header: true});
    addLayer(result.data);
});
// Define style-related properties
function addLayer(points) {
    var graphics = [];
    for (var i = 0; i < points.length; i++) {

        var lngLat = {
            lng: parseFloat(points[i].lng),
            lat: parseFloat(points[i].lat)
        };

        graphics.push(new mapboxgl.supermap.Graphic(lngLat));
    }

    var graphicStyle = {
        color: [0, 255, 128],
        radius: 10
    };
    // Draw an object and add it to the layer
    graphicLayer = new mapboxgl.supermap.GraphicLayer("graphic", {
        graphics: graphics,
        radius: graphicStyle.radius,
        color: graphicStyle.color,
        highlightColor: [255, 0, 0, 255],
    });
    // Render the drawn points to the 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://github.com/apache/echarts)
echartsLayer(https://github.com/lzxue/echartsLayer)
                      

Taking the special effect map of Changchun bus route as an example, the data of the bus route is visualized:

                    var uploadedDataURL = "../data/changchunBus.json";
$.get(uploadedDataURL, function (data) {
    option = {
        animation: false,
        GLMap: {
            roam: true
        },
        coordinateSystem: 'GLMap',
        geo: {
            map: 'GLMap',
        },

        series: [{
            type: 'lines',
            polyline: true,
            data: data,
            silent: true,
            lineStyle: {
                normal: {
                    opacity: 0.2,
                    width: 1
                }
            },
            progressiveThreshold: 500,
            progressive: 100,
        }, {

            type: 'lines',
            coordinateSystem: 'GLMap',
            polyline: true,
            data: data,
            lineStyle: {
                normal: {
                    width: 0.2
                }
            },
            effect: {
                constantSpeed: 40,
                show: true,
                trailLength: 0.02,
                symbolSize: 2
            },
        }]
    };
    var echartslayer = new EchartsLayer(map);
    echartslayer.chart.setOption(option);

});See full example code »
                

Enjoy the result.

EChartsGL

ECharts GL is a WebGL extension of ECharts, which provides 3D scatter plots, flying lines, histograms, surface maps, and other 3D visualization methods. And by adding scatterGL, the graphGL series types are used for two-dimensional scatter plots, accelerated drawing and layout of diagrams.

This example needs to import

                        ECharts (https://github.com/apache/echarts)
echartsLayer(https://github.com/lzxue/echartsLayer)
ECharts-GL (https://github.com/ecomfe/echarts-gl)
                      

The following is an example of global wind energy, which visualizes wind energy data:

                    map.on('load', function () {
    $.getJSON('../data/globalWindData.json', function (windData) {
        var data = [];
        var p = 0;
        var maxMag = 0;
        var minMag = Infinity;
        for (var j = 0; j < windData.ny; j++) {
            for (var i = 0; i < windData.nx; i++, p++) {
                var vx = windData.data[p][0];
                var vy = windData.data[p][1];
                var mag = Math.sqrt(vx * vx + vy * vy);
                // Data is a one-dimensional array
                // [ [Longitude, dimension, value of vector longitude direction, value of vector dimension direction] ]
                data.push([
                    i / windData.nx * 360 - 180,
                    j / windData.ny * 180 - 90,
                    vx,
                    vy,
                    mag
                ]);
                maxMag = Math.max(mag, maxMag);
                minMag = Math.min(mag, minMag);
            }
        }

        var echartslayer = new EchartsLayer(map);
        echartslayer.chart.setOption({
            GLMap: {
                roam: true,
            },
            geo: {
                map: "GLMap"
            },
            visualMap: {
                left: 'right',
                min: minMag,
                max: maxMag,
                dimension: 4,
                inRange: {
                    color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
                },
                realtime: false,
                calculable: true,
                textStyle: {
                    color: '#fff'
                }
            },
            series: [{
                type: 'flowGL',
                coordinateSystem: 'GLMap',
                data: data,
                particleDensity: 512,
                particleSpeed: 2,
                particleSize: 1,
                gridWidth: windData.nx,
                gridHeight: windData.ny,
                itemStyle: {
                    opacity: 0.7
                }
            }]
        });
    });
});See full example code »
                

Enjoy the result.

DeckGL

DeckGL is a WebGL-based large data volume visualization framework developed and open sourced by Uber.

It features different types of visual layers, high performance for GPU rendering, React and Mapbox GL integration, combined with geographic information data (GPS) features.

This example needs to import

                            deck.gl (https://github.com/visgl/deck.gl)
                          

The following example shows the honeycomb layer display of the data.

                    $.get('../data/deck.gl/sf-bike-parking.json', function (features) {
    addLayer(features);
});
function addLayer(features) {
    deckglLayer = new mapboxgl.supermap.DeckglLayer("hexagon-layer", {
        data: features,
        props: {
            extruded: true, // Whether to stretch the feature, the default is false
            radius: 200, // Hexagonal radius value, the default is 1000
            elevationScale: 4, // Elevation multiplier
            coverage: 0.8 // The hexagonal radius multiplier, between 0 and 1
        },
        callback: {
            getPosition: d => d.COORDINATES,
        }
    });
    map.addLayer(deckglLayer);
}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://github.com/huiyan-fe/mapv)
                            

SuperMap iClient for MapboxGL supports for using MapV visualization layer

                        mapboxgl.supermap.MapvLayer(dataSet, options)
                    

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

Specify configuration items and data for the chart.

                    var randomCount = 500;
var node_data = {
    "0": {"x": 108.154518, "y": 36.643346},
    "1": {"x": 121.485124, "y": 31.235317},
};
var edge_data = [
    {"source": "1", "target": "0"}
];
var citys = ["北京", "天津", "上海", "重庆", "石家庄", "太原", "呼和浩特", "哈尔滨", "长春", "沈阳", "济南", "南京", "合肥", "杭州", "南昌", "福州", "郑州", "武汉", "长沙", "广州", "南宁", "西安", "银川", "兰州", "西宁", "乌鲁木齐", "成都", "贵阳", "昆明", "拉萨", "海口"];

// Construction data
for (var i = 1; i < randomCount; i++) {
    var cityCenter = mapv.utilCityCenter.getCenterByCityName(citys[parseInt(Math.random() * citys.length)]);
    node_data[i] = {
        x: cityCenter.lng - 5 + Math.random() * 10,
        y: cityCenter.lat - 5 + Math.random() * 10,
    };
    edge_data.push(
        {"source": ~~(i * Math.random()), "target": '0'}
    );
}

var fbundling = mapv.utilForceEdgeBundling()
    .nodes(node_data)
    .edges(edge_data);

var results = fbundling();

var data = [];
var timeData = [];

for (var i = 0; i < results.length; i++) {
    var line = results[i];
    var coordinates = [];
    for (var j = 0; j < line.length; j++) {
        coordinates.push([line[j].x, line[j].y]);
        timeData.push({
            geometry: {
                type: 'Point',
                coordinates: [line[j].x, line[j].y]
            },
            count: 1,
            time: j
        });
    }

    data.push({
        geometry: {
            type: 'LineString',
            coordinates: transformCoords(coordinates)
        }
    });

    function transformCoords(coordinates) {
        var coords = [];
        coordinates.map(function (coordinate) {
            coords.push(coordinate);
        });
        return coords;
    }
}

var dataSet = new mapv.DataSet(data);

var options = {
    strokeStyle: 'rgba(55, 50, 250, 0.3)',
    globalCompositeOperation: 'lighter',
    shadowColor: 'rgba(55, 50, 250, 0.5)',
    shadowBlur: 10,
    lineWidth: 1.0,
    draw: 'simple'
};

var mapVLinelayer = new mapboxgl.supermap.MapvLayer("", dataSet, options);
map.addLayer(mapVLinelayer);

var dataSet = new mapv.DataSet(timeData);

var options = {
    fillStyle: 'rgba(255, 250, 250, 0.9)',
    globalCompositeOperation: 'lighter',
    size: 1.5,
    animation: {
        type: 'time',
        stepsRange: {
            start: 0,
            end: 100
        },
        trails: 1,
        duration: 5
    },
    draw: 'simple'
};

var mapVAnimationLinelayer = new mapboxgl.supermap.MapvLayer("", dataSet, options);
map.addLayer(mapVAnimationLinelayer);See full example code »
             

Enjoy the result.

threejs

Three.js is an open source mainstream 3D drawing JS library (the name Three is the meaning of 3D), the original author is Mr.Doob, the project address is: https://github.com/mrdoob/three.js/. We know that WebGL is a web 3D drawing standard. Just as jQuery simplifies HTML DOM operations, Three.js simplifies WebGL programming.

This example needs to import

                                three.js (https://github.com/mrdoob/three.js)
GLTFLoader (https://github.com/johh/three-gltf-loader)
                              

SuperMap iClient for MapboxGL supports for using three.js visualization layer.

mapboxgl.supermap.ThreeLayer('three')
                         
                        function loaderModels() {
    var loader = new THREE.GLTFLoader();
    // Load gltf format data
    loader.load('./js/airplane/airplane.glb', function (gltf) {
        var scene = gltf.scene;
        scene.rotation.x = -Math.PI / 2;
        scene.rotation.y = Math.PI / 2;
        scene.scale.multiplyScalar(150);

        addThreeLayer(scene);
    });
}

function addThreeLayer(meshes) {
    threeLayer = new mapboxgl.supermap.ThreeLayer('three');
    threeLayer.on("initialized", render);
    threeLayer.addTo(map);

    function render() {
        var renderer = threeLayer.getThreeRenderer(),
            scene = threeLayer.getScene(),
            camera = threeLayer.getCamera();

        this.light = new THREE.PointLight(0xaaaaaa, 0.5);
        this.light.position.copy(camera.position);
        scene.add(this.light);
        scene.add(new THREE.AmbientLight(0xffffff));
        threeLayer.setPosition(meshes, position);
        // Set the flight height
        meshes.translateY(5000);
        scene.add(meshes);

        (function animate() {
            requestAnimationFrame(animate);
            meshes.position.y -= 60;
            var center = map.getCenter().toArray();
            center[1] += 0.00008;
            map.setCenter(center);
            renderer.render(scene, camera);
        })()
    }

    // Uniform illumination, synchronized to camera position
    threeLayer.on("render", function () {
        threeLayer.light.position.copy(threeLayer.renderer.camera.position);
    });
}See full example code »

                    

Enjoy the result.

Web symbol

Web symbols cover SuperMap iDesktop, SuperMap iDesktopX part of the point line polygon symbols, users can quickly add symbols to the map by Web Symbol ID . At the same time, you can also customize the symbols according to the symbol specification. This section mainly introduces the introductory usage of Web symbols, please refer to the API page for detailed interface.

Import

Import files

First, import MapboxGL v1 and SuperMap iClient for MapboxGL .

Then, set the basePath to the absolute or relative path to the resources folder, depending on the following two scenarios.

  • Default resources folder path

    If the resources folder is placed in the same level as the entry HTML file, you do not need to configure the basePath and can just use the default value.

  • Customize the resources folder path

    First, download the SuperMap iClient for MapboxGL package, move the resources folder to any location in the project.

    Then, set basePath to the resources folder absolute or relative to the entry HTML path.

                                    new mapboxgl.supermap.WebSymbol().init({basePath: "./resources/symbols"});
                                    

npm

First, npm install @supermapgis/iclient-mapboxgl .

Then, move the resources folder under the @supermapgis/iclient-mapboxgl installation package to any folder in the project root directory.

Next, set basePath to the absolute or relative root path to the resources folder.

                        new mapboxgl.supermap.WebSymbol().init({basePath: "./resources/symbols"});
                        

Get started wuickly

Symbol Specification

Web symbols are symbol objects consisting of paint , layout (except visibility property) in Mapbox Layers.

Using Web Symbols

First, get Web Symbol ID.

Then, initialize the Web symbol with new mapboxgl.supermap.WebSymbol().init, specify the symbol resource path.

And then, use the interface loadSymbol to load Web symbols.

Next, use the interface addSymbol to add symbols to the map.

Finally, the layer is added using the interface addLayer while the layer sets the Web symbol.

Example code.

                            // Web Symbol ID
const symbolId = "line-962613";
// Configure symbolic resource paths
new mapboxgl.supermap.WebSymbol().init({basePath: "./resources/symbols"});
// Load Web Symbols
map.loadSymbol(symbolId, (error, symbol) => {
    if (error) throw error;

    // Add Web symbols to the map
    map.addSymbol(symbolId, symbol);
    // Set the Web symbol for the specified layer
    map.addLayer({
        "id": "pl@landuse(0_24)",
        "source": "landuse",
        "source-layer": "pl@landuse",
        "type": "line",
        "symbol": symbolId
    });
});See full example code »
                        

Enjoy the result.

Using Custom Web Symbols

First, use the new mapboxgl.supermap.WebSymbol().init to initial Web symbol.

Then, use the interface addSymbol to add symbols to the map.

Next, use the interface addLayer to add the layer and set the Web symbol for the layer.

Example code.

                            // Configure symbolic resource paths
new mapboxgl.supermap.WebSymbol().init({basePath: "./resources/symbols"});                              
// Load symbol                          
map.loadImage("../img/cirecleRed.png", (error, image) => {
    if (error) throw error;

    // Custom symbol image
    const imageId = "cityPoint";
    // Add symbol image to map
    map.addImage(imageId, image); 
    // Custom symbol
    const customPointSymbol = {
        "paint": {
            "icon-translate": [0, 4]
        },
        "layout": {
            "icon-image": imageId,
            "icon-size": 0.1
        }
    };

    const pointSymbolId = "Province_P";
    // Add symbol to map
    map.addSymbol(pointSymbolId, customPointSymbol);
    // Set the point symbol for the specified layer
    map.addLayer({
        "id": "layerId",
        "source": "sourceId",
        "type": "symbol",
        "symbol": symbolId
    });
});

// Custom line symbol
const customLineSymbol = {
    "paint": {
        "line-width": 0.38,
        "line-dasharray": [
            2.5,
            2
        ],
        "line-color": "#AE10FC"
    }
};
const lineSymbolId = "Province_P";
// Add symbol to map
map.addSymbol(lineSymbolId, customLineSymbol);
// Set the line symbol for the specified layer
map.addLayer({
    "id": "Province_L@Population",
    "source": "全国人口密度空间分布图",
    "source-layer": "Province_L@Population",
    "type": "line",
    "symbol": "Province_L"
});

// Custom fill symbol in a data-driven manner
map.addLayer({
    "id": "PopDensity_R@Population",
    "source": "全国人口密度空间分布图",
    "source-layer": "PopDensity_R@Population",
    "type": "fill",
    "symbol": [
    "case",
        ["all", ["<=", ["get", "dMaxZValue"], 70]], "PoPdensity_R_MAX70",
        ["all", [">", ["get", "dMaxZValue"], 70],["<=", ["get", "dMaxZValue"], 140]], "PoPdensity_R_MAX140",
        ["all", [">", ["get", "dMaxZValue"], 210],["<=", ["get", "dMaxZValue"], 280]], "PoPdensity_R_MAX280",
        ["all", [">", ["get", "dMaxZValue"], 350],["<=", ["get", "dMaxZValue"], 420]], "PoPdensity_R_MAX420",
        ["all", [">", ["get", "dMaxZValue"], 490],["<=", ["get", "dMaxZValue"], 560]], "PoPdensity_R_MAX560",
        ["all", [">", ["get", "dMaxZValue"], 640],["<=", ["get", "dMaxZValue"], 700]], "PoPdensity_R_MAX700",
        ["all", [">", ["get", "dMaxZValue"], 770],["<=", ["get", "dMaxZValue"], 1000]], "PoPdensity_R_MAX1000",
        ["all", [">", ["get", "dMaxZValue"], 1000]], "PoPdensity_R_Exceed1000",
        "Country_R"
    ]
});See full example code »                          
                        

Enjoy the result.