SuperMap iClient for Leaflet

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

Preparing your page

Get Leaflet and SuperMap iClient for Leaflet

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

Leaflet

SuperMap iClient for Leaflet

Import

Import files

When you get the file, you only need to import by <script> tags, just like ordinary JavaScript libraries. The following is detailed account of how to import Leaflet files online via CDN, and how to import SuperMap iClient for Leaflet through online sites.

Create a new HTML file, import Leaflet 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/leaflet/1.7.1/leaflet.css" rel="stylesheet">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
</head>
</html>
                                    

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

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

                                            npm install @supermap/iclient-leaflet
                                        

The following is a description of how to use SuperMap iClient for Leaflet in npm projects.

Import the CSS files

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

                                            <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"/>

<link rel="stylesheet" href="https://iclient.supermap.io/dist/leaflet/iclient-leaflet.min.css"/>

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 @supermap/babel-plugin-import:

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

Then edit .babelrc:

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

Next, if you need TiledMapLayer, edit:

                                            import L from 'leaflet';
import {TiledMapLayer} from '@supermap/iclient-leaflet';
var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = L.map('map', {
    crs: L.CRS.EPSG4326,
    center: [0, 0],
    maxZoom: 18,
    zoom: 1
});
var layer = new TiledMapLayer(url)
layer.addTo(map);
                                        

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

  Import all modules

                                            import L from 'leaflet';
import '@supermap/iclient-leaflet';
var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = L.map('map', {
    crs: L.CRS.EPSG4326,
    center: [0, 0],
    maxZoom: 18,
    zoom: 1
});
new L.supermap.TiledMapLayer(url).addTo(map);
                                        

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 L = require('leaflet');
var TiledMapLayer = require('@supermap/iclient-leaflet').TiledMapLayer;

var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = L.map('map', {
    crs: L.CRS.EPSG4326,
    center: [0, 0],
    maxZoom: 18,
    zoom: 1
});
TiledMapLayer(url).addTo(map);
                                        

  Import all modules

                                            var L = require('leaflet');
require('@supermap/iclient-leaflet');

var url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
var map = L.map('map', {
    crs: L.CRS.EPSG4326,
    center: [0, 0],
    maxZoom: 18,
    zoom: 1
});
new L.supermap.TiledMapLayer(url).addTo(map);
                                        

AMD

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

  Import all modules

                                    require(['js/leaflet.js', 'js/iclient-leaflet.js'], function(L) {
    var url = 'https://iserver.supermap.io/iserver/services/map-world/rest/maps/World';
    var map = L.map('map', {
        crs: L.CRS.EPSG4326,
        center: [0, 0],
        maxZoom: 18,
        zoom: 1
});
    new L.supermap.TiledMapLayer(url).addTo(map);
});
                                

CMD

The following example uses the SeaJS library to implement; Download leaflet.js and iclient-leaflet.js through " Get Leaflet and SuperMap iClient for Leaflet " 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('./leaflet.js');
    require('./iclient-leaflet.js');

    var url = 'https://iserver.supermap.io/iserver/services/map-world/rest/maps/World';
    var map = L.map('map', {
        crs: L.CRS.EPSG4326,
        center: [0, 0],
        maxZoom: 18,
        zoom: 1
    });
    new L.supermap.TiledMapLayer(url).addTo(map);
});
                                

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']
        }
    }]
}
                                        

Compatible with IE 8

For better compatible with IE 8, except for leaflet.js, iclient-leaflet.js, you still need to introduce es5-shim.

You can directly download es5-shim.js and es5-sham.js

or refer the online addresss:
https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.9/es5-shim.js
https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.9/es5-sham.js

Add the following code before the <script> tab in the introduced leaflet.js:

                                            <!--[if lte IE 8]>
    <script src="your shim js"></script>
    <script src="your sham js"></script>
<![endif]-->
                See full example code »
                                        

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/leaflet/1.7.1/leaflet.css" rel="stylesheet">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
    <script type="text/javascript" src="https://iclient.supermap.io/dist/leaflet/iclient-leaflet.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 url ="https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
// Initialize map information
var map = L.map('map', {
    crs: L.CRS.EPSG4326,
    center: [0, 0],
    maxZoom: 18,
    zoom: 1
});
// Add layer
new L.supermap.TiledMapLayer(url).addTo(map);See full example code »
                            

Enjoy the result.

Third-party map

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

                                <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title data-i18n="resources.title_tiandituLayer_mecartor"></title>
    <script type="text/javascript" src="../js/include-web.js"></script>
</head>
<body style=" margin: 0;overflow: hidden;background: #fff;width: 100%;height:100%;position: absolute;top: 0;">
    <div id="map" style="margin:0 auto;width: 100%;height: 100%"></div>
    <script type="text/javascript" src="../../dist/include-leaflet.js"></script>
    <script type="text/javascript">
        var map = L.map('map', {
            center: [0, 0],
            zoom: 0,
            crs: L.supermap.CRS.TianDiTu_Mercator
        });
        // Add Tianditu layer
        new L.supermap.TiandituTileLayer({layerType: "img"}).addTo(map);
    </script>
</body>
</html>
查看源码 »
                            

Enjoy the result.

Setting map projection

SuperMap iClient for Leaflet can easily define map projections by the L.supermap.Proj.CRS projection class, and supports setting bounds, origin, scale array, and resolution array. For example:

                            // Define map projections
var crs = L.supermap.Proj.CRS("EPSG:4326", {
    origin: [114.59, 42.31],
    scaleDenominators: [100000, 50000, 25000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 1]
});
var map = L.map('map', {
    crs: crs,
    center: [39.79, 116.85],
    maxZoom: 5,
    zoom: 0
});
new L.supermap.TiledMapLayer(url).addTo(map);See full example code »
                            

For projections that are not supported or user-defined, you need to define key-value pairs through the Proj4js.defs[] static constant. Proj4js is a projection-related JavaScript script library. Please refer to the following website for details: https://trac.osgeo.org/proj4js/

Currently, Proj4js supports following projections:

EPSG:4326 EPSG:4269 EPSG:3875
EPSG:4139 EPSG:4181 EPSG:3785
EPSG:4302 EPSG:21781 EPSG:102113
EPSG:26591 EPSG:26912 EPSG:27200
EPSG:27563 EPSG:41001 EPSG:4272
EPSG:42304 EPSG:102067 EPSG:102757
EPSG:102758 EPSG:900913 EPSG:GOOGLE

A simple projection information is described as follows:

                            Proj4js.defs("EPSG:21418","+proj=tmerc +lat_0=0 +lon_0=105 +k=1 +x_0=18500000 +y_0=0 +ellps=krass +units=m +no_defs "); 
                        

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

For a user-defined projection, you can create the projection by defining EPSGCODE and defs, where defs contains the reference projection parameters including name, projection, conversion to the WGS84 coordinate system (three parameters), major semiaxis, flatterning rate, original latitude, central meridian, standard parallels, east offset, north offset, Unit, etc.

                            Proj4js.defs("EPSG:10010","+title=Beijing1954 +proj=lcc +towgs84=0.0000,0.0000,0.0000 +a=6378245.0000 +rf=298.3 +lat_0=0.00000000 +lon_0=104.000000000 +lat_1=24.000000000 +lat_2=40.000000000 +x_0=0.000 +y_0=0.000 +units=m +no_defs");
                        

Adding controls

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

Control Class name Introduction
Eagle-eye Map L.control.minimap The default is in the lower right corner of the map
Zoom L.control.zoom The default is in the top left corner of the map
Scale L.control.scale The default is at the bottom left corner of the map
Layer switching L.control.layers The default is in the top right corner of the map
Swipe L.control.sideBySide 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 addTo() method, for example:

Zoom control

                            // Add Control
L.control.zoom().addTo(map);See full example code  »
                        

Enjoy the result.

Layer switch control:

                            var url ="https://iserver.supermap.io";
var China = new L.supermap.TiledMapLayer(url + '/iserver/services/map-china400/rest/maps/China',{noWrap:true});
var ChinaDark = new L.supermap.TiledMapLayer(url + '/iserver/services/map-china400/rest/maps/ChinaDark', {noWrap:true});
// Initialize map
var map = L.map('map', {
    center: {lon: 0, lat: 0},
    maxZoom: 18,
    zoom: 2,
    zoomControl: false,
    layers: [China, cities]
});
var baseMaps = { "China": China, "ChinaDark": ChinaDark };
// Add layer switch control
L.control.layers(baseMaps).addTo(map);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, namely new L.supermap.TiledVectorLayer(url, options).

  • url:Map service address
  • options:Layer optional parameter

Vector tiles example: using default style

                            var url="https://iserver.supermap.io/iserver/services/map-china400/rest/maps/China";
//Create a vector tile layer
var vectorLayer = new L.supermap.TiledVectorLayer(url, {
    cacheEnabled: true,
    returnAttributes: true,
    attribution: "Tile Data©SuperMap iServer with©SuperMap iClient"
}).addTo(map);
//Adds click event to the vector tile layer, sets default style
vectorLayer.on('click', function (evt) {
    // Click the vector tile layer to get id & layerName
    var id = evt.layer.properties.id;
    var layerName = evt.layer.layerName;
    // Set the style for vector tile layer
    var selectStyle = {
        fillColor: '#800026',
        fillOpacity: 0.5,
        stroke: true,
        fill: true,
        color: 'red',
        opacity: 1,
        weight: 2
    };
    vectorLayer.setFeatureStyle(id, layerName, selectStyle);
});See full example code »
                        

Enjoy the result.

Drawing symbols and graphics

Basic drawing

For the Leaflet itself does not support the drawing of point, line and polygon, the plugin leaflet.draw.js needs to be imported. The import of plugin includes offline introduction and online introduction.

1. Offline introduction need to download leaflet.draw.js and then introduced by the <script> tag:

  Download leaflet.draw.js from github, download address:

                                https://github.com/Leaflet/Leaflet.draw
                                

  <script> Label import:

                                    <script src="leaflet.draw.js"></script>
                            

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

                                <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.js"></script>
                            

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

                                            // Create a drawing layer
var editableLayers = new L.FeatureGroup();
// Draw the configuration of control parameter
var options = {
    position: 'topleft',
    draw: {
        polyline: {}, // line
        polygon: {}, // polygon
        circle: {}, // circle
        rectangle:{}, // rectangle
        marker: {}, // marker
        remove: {}
    },
    edit: {
        featureGroup: editableLayers,
        remove: true
    }
};
// Create and add a draw control
var drawControl = new L.Control.Draw(options);
map.addControl(drawControl);
// monitor drawing events
map.on(L.Draw.Event.CREATED, function (e) {
    var type = e.layerType, layer = e.layer;
    editableLayers.addLayer(layer);
});See full example code »
                    

Enjoy the result.

Capture drawing

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

The Leaflet itself does not support point, line and polygon capture drawing. It is necessary to import leaflet-geoman plugins.

  1、<link> and <script> Tag import:

                                <link rel="stylesheet" href="https://unpkg.com/@geoman-io/leaflet-geoman-free@latest/dist/leaflet-geoman.css" />
<script src="https://unpkg.com/@geoman-io/leaflet-geoman-free@latest/dist/leaflet-geoman.min.js"></script>

After the plugin is introduced, the point capture drawing function is implemented by the following code:

                                            // Capture drawing control parameter settings
var options = {
    position: 'topleft', // Control position
    drawMarker: true, // Whether marker drawing is optional
    drawPolygon: true, // Whether drawPolygon drwaing is optional
    drawPolyline: true, // Whether drawPolyline drawing is optional
    editPolygon: true, // Whether EditPolygon editing is optional
    deleteLayer: true
};
// Add Capture drawing control
map.pm.addControls(options);See full example code »
                            

Enjoy the result.

Area and distance measurement

SuperMap iClient for Leaflet supports area and distance measurement.

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 L.supermap.MeasureParameters();
// Set the vector object ({line} or {Polygon}) to measure, and geometry can obtain via initialization
measureParam.geometry= geometry;
measureParam.unit = L.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:

                                //Initialize the service class, set the key parameters for service request
var measureService = new L.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){
    //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:

                                //Setting the measurement bounds
var polygon = L.polygon([[24, 100], [40, 100], [40, 120], [24, 120], [24, 100]], {color: "red"});
//Instantiate the measurement constructor of the incoming polygon parameter
var areaMeasureParam = new L.supermap.MeasureParameters(polygon);
                            

2. Call the measurement function

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

                                //Submit a service request, pass the service query parameters, get the returned results and process them according to user needs
new L.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 Leaflet 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
  • Raster information query
  • Field information query

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 L.supermap.FeatureService to query geospatial features with IDs 246 and 247 in the dataset "World:Countries".

                                    // Parameters of dataset ID query service
var idsParam = new L.supermap.GetFeaturesByIDsParameters({
    IDs: [233, 234],
    datasetNames: ["World:Countries"]
});
// Construct specified ID query
var url = "https://iserver.supermap.io/iserver/services/data-world/rest/data";
new L.supermap.FeatureService(url).getFeaturesByIDs(idsParam).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});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 L.supermap.FeatureService to query the vector elements of "SMID=247" in the dataset "World:Countries".

                                         // Specify service parameters
var sqlParam = new L.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 L.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 rectangular 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 L.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 polygon = L.polygon([[-20, 20], [0, 20], [0, 40], [-20, 40], [-20, 20]], {color: 'red'});
// Set the rectangle bounds query parameters
var boundsParam = new L.supermap.GetFeaturesByBoundsParameters({
    datasetNames: ["World:Capitals"],
    bounds: polygon.getBounds()
});
// Construct rectangle bounds query
new L.supermap.FeatureService(url).getFeaturesByBounds(boundsParam).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});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 L.supermap.FeatureService uses intersected spatial query patterns in the "World:Countries" data set to query vector elements that conform to the geometric range.

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

                                    // Add center point of querying
var circleMarker = L.circleMarker([30, 104], {color:'red'});
// Setting the parameters of distance query
var param = new L.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: circleMarker
});
// Construct distance query
new L.supermap.QueryService(url) .queryByDistance(param).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});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 data sets 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 L.supermap.FeatureService to find the vector elements whose buffer range is 10 degrees (map coordinate units) in the data set "World:Capitals".

                                    // Setting the range of buffer query
var polygon = L.polygon([[-20, 20], [0, 20], [0, 40], [-20, 40], [-20, 20]], {color: 'red'});
// Setting the parameters for buffer query
var bufferParam = new L.supermap.GetFeaturesByBufferParameters({
    datasetNames: ["World:Capitals"],
    bufferDistance: 10, // The unit of bufferDistance is the same as the coordinate system, their units both are degree
    geometry:polygon
});
// Construct buffer query, send a request to the server, and get the returned result
new L.supermap.FeatureService(url) .getFeaturesByBuffer(bufferParam).then(function (serviceResult) {
    // Get the results returned by the server
    var result = serviceResult.result;
});See full example code »
                                

Enjoy the result.

Query raster information

Query raster information is find the pixel value information corresponding to a geographical location in the specified data set and display it in the client.

Use the interface L.supermap.GridCellInfosService to to query raster 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 L.supermap.GetGridCellInfosParameters({
        dataSourceName: "World",
        datasetName:"WorldEarth",
        X: x,
        Y: y
    });
    // Construct raster query
    new L.supermap.GridCellInfosService(url).getGridCellInfos(getGridCellInfosParam).then(function(serviceResult) {
        // 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 data set 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 L.supermap.FieldService to query the field information of the field "SmID" in the data set "continent_T".

                                    var dataURL = "https://iserver.supermap.io/iserver/services/data-world/rest/data"
// Set parameters for field query
var param = new L.supermap.FieldParameters({
    datasource: "World",
    dataset: "continent_T"
});
var fieldName = 'SmID';
// Construct field query
new L.supermap.FieldService(dataURL).getFields(param).then(function (serviceResult) {
    fieldStatistic(fieldName);
});
// Query specified field
function fieldStatistic(fieldName) {
    // setting up the parameters of querying specified field
    var param = new L.supermap.FieldStatisticsParameters({
        datasource: currentData.dataSourceName,
        dataset: currentData.dataSetName,
        fieldName: fieldName,
        statisticMode: [
            L.supermap.StatisticMode.MAX,
            L.supermap.StatisticMode.MIN,
            L.supermap.StatisticMode.SUM,
            L.supermap.StatisticMode.AVERAGE,
            L.supermap.StatisticMode.STDDEVIATION,
            L.supermap.StatisticMode.VARIANCE
            ]
        });
    });
    // Send a request to the server and get the data
    new L.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 L.supermap.FeatureService to add feature information to the dataset "Capitals".

            //Instantiated feature editing service
var url="https://iserver.supermap.io/iserver/services/data-world/rest/data";
var featureService = new L.supermap.FeatureService(url);
//Set the parameters of feature editing field
var addFeatureParams = new L.supermap.EditFeaturesParameters({
    dataSourceName: "World",
    dataSetName: "Capitals",
    features: marker,
    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 data set, 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 theme map uses the number or intensity of points to reflect the theme values corresponding to a region or range.

                                var url = https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
// Get the thematic map service, url is the map access service
var themeService = new L.supermap.ThemeService(url);
//Instantiate a dot density thematic map object and make corresponding settings for it.
var themeDotDensity = new L.supermap.ThemeDotDensity({
    dotExpression:"Pop_1994",
    value: 5000000,
    style: new L.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 L.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 »
                                                

Running 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 Leaflet 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 Leaflet build a unique thematic map object:

                                //Build unique value thematic map layer
var themeLayer = new L.supermap.UniqueThemeLayer("ThemeLayer", {
    // Turn on hover highlight
    isHoverAble: true,
    opacity: 0.8,
    alwaysMapCRS: true
}).addTo(map);
// Basic style of layer
themeLayer.style = new L.supermap.ThemeStyle({
    shadowBlur: 3,
    shadowColor: "#000000",
    shadowOffsetX: 1,
    shadowOffsetY: 1,
    fillColor: "#FFFFFF"
});
// hover highlight style
themeLayer.highlightStyle = new L.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 Leaflet implements the range thematic map by the following code:

                                //Define rangeThemeLayer range thematic map layer
var themeLayer = new L.supermap.RangeThemeLayer("ThemeLayer", {
            // Turn on hover highlight
            isHoverAble: true,
            opacity: 0.8,
            alwaysMapCRS: true
        }).addTo(map);
themeLayer.style = new L.supermap.ThemeStyle({
    shadowBlur: 16,
    shadowColor: "#000000",
    fillColor: "#FFFFFF"
});
// hover highlight style
themeLayer.highlightStyle = new L.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 Leaflet implements the graduated symbols thematic map by the following code:

                                //Build a graduated symbols thematic map layer
var themeLayer = new L.supermap.RankSymbolThemeLayer("themeLayer", L.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, it is a required parameter.
    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}
};
themeLayer.addTo(map);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 Leaflet used to implement the label thematic map is as follows:

                                //Build a label thematic map layer
var themeLayer = new L.supermap.LabelThemeLayer("ThemeLayer").addTo(map);
themeLayer.style = new L.supermap.ThemeStyle({
    labelRect: true,
    fontColor: "#000000",
    fontWeight: "bolder",
    fontSize: "18px",
    fill: true,
    fillColor: "#FFFFFF",
    fillOpacity: 1,
    stroke: false,
    strokeColor: "#8B7B8B"
});
//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 theme map can be based on multiple variables, reflecting multiple attributes is the values of multiple thematic variables can be plotted on a statistics graph. Statistical theme 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 Leaflet 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 L.supermap.GraphThemeLayer("BarLayer", "Bar", themeLayerOptions);
map.addLayer(themeLayer);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 Leaflet include:

  • Buffer analysis
  • Thiessen Polygon
  • Overlay analysis
  • Surface analysis
  • Dynamic segmentation
  • Route calculate measure
  • Route locator point
  • Route locator line
  • Interpolation analysis
  • Raster algebraic calculation
  • Terrain calculation
  • Kernel density analysis

Buffer analysis

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

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

Set parameters for buffer analysis, set buffer analysis common parameters

                                //Set parameters for buffer analysis
var dsBufferAnalystParams = new L.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 L.supermap.FilterParameter({
        // Attribute filter condition
        attributeFilter: "NAME='Tuanjie Road'"
    }),
    //Set buffer analysis common parameters
    bufferSetting: new L.supermap.BufferSetting({
        // Set end type, including FLAT and RROUND
        endType: L.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 cient side to the server side and receive the data from returned from the server. When a request has been sent to the server and the server has returned the result successfully, the user can handle the results of buffer analysis from the server.

                                        var serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst"
// Define buffer analysis service
var bufferServiceByDatasets = new L.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-changchun/restjsr/spatialanalyst";
// Set the parameters for the Thiessen polygon analysis
var dThiessenAnalystParameters = new L.supermap.DatasetThiessenAnalystParameters({
    dataset: "Factory@Changchun"
});
// Define Thiessen polygon analysis
new L.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 data sets 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 L.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: L.supermap.OverlayOperationType.UNION
});
                            

Set the overlay analysis service object, which is used to pass parameters specified at the cient 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 L.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.

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 = L.polygon([[4010338,0],[4010338,1063524],[3150322,1063524],[3150322,0]]);
// Set surface analysis parameters
var extractParams = new L.supermap.SurfaceAnalystParametersSetting({
    datumValue: 0, // The datum value in surface analysis
    interval: 2, // The interval value
    resampleTolerance: 0, // The resample tolerance
    smoothMethod: L.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 L.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 cient 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 L.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.

Dynamic Segmentation

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

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

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

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

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

                                var serviceUrl = "https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst"
// Construct dynamic segmentation service
var generateSpatialDataService = new L.supermap.SpatialAnalystService(serviceUrl);
// Send the request to the server and display the results on the client side as thematic map
generateSpatialDataService.generateSpatialData(generateSpatialDataParams).then(function (serviceResult) {
    // Get the returned data
    var result = serviceResult.result;
});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.

                                // Establish route through SQL query
var queryBySQLService = new L.supermap.QueryService(baseUrl);
// Set SQL query parameters
var queryBySQLParams = new L.supermap.QueryBySQLParameters({
    queryParams: [
        new L.supermap.FilterParameter({
            name: "RouteDT_road@Changchun",
            attributeFilter: "RouteID=1690"
        })]
});
// Create SQL query server
queryBySQLService.queryBySQL(queryBySQLParams).then(function (serviceResult) {
    // Get the results of SQL query
    var queryBySQLResult = SQLQueryServiceResult.result.recordsets[0].features;
    // Extract the points that form the route to construct the parameter sourceRoute
    var pointsList = [];
    var routeObj = queryBySQLResult.features[0].geometry.coordinates[0];
    for (var i = 0; i < routeObj.length; i++) {
        pointsList.push([routeObj[i][0], routeObj[i][1],routeObj[i][2]])
    }
    routeLine = L.polyline(pointsList);
    // Create routeCalculateMeasureService
    var serviceUrl ="https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst";
    var routeCalculateMeasureService = new L.supermap.SpatialAnalystService(serviceUrl);
    // Set parameters
    var routeCalculateMeasureParameters = new L.supermap.RouteCalculateMeasureParameters({
            "sourceRoute": routeLine, // Route Type
            "point": L.point(routeObj[7][0], routeObj[7][1]),// Query point
            "tolerance": 10,
            "isIgnoreGap": false
    });
    // Send the request to the server and handle the results returned from the server
    routeCalculateMeasureService.routeCalculateMeasure(routeCalculateMeasureParameters).then(function (routeCaculateServiceResult) {
        // Get the results returned from the server
        var result = routeCaculateServiceResult.result;
    });
});See full example code »
                        

Enjoy the result.

Route locate 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 when we already know the M value from the point to the raod intersection.

Here we will determine the precise coordinates of an accidient position when we already know the M value from the point to the raod intersection is 10 KM on the route with the ID of 1690. The sample data used here is Changchun data, the usage of Route Locator Point interface:

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

                                // Establish route through SQL query
var queryBySQLService = new L.supermap.QueryService(baseUrl);
// Set SQL query service parameters
queryBySQLParams = new L.supermap.QueryBySQLParameters({
    queryParams: [
        new L.supermap.FilterParameter({
            name: "RouteDT_road@Changchun",
            attributeFilter: "RouteID=1690"
        })]
});
// Create query service
queryBySQLService.queryBySQL(queryBySQLParams).then(function (serviceResult) {
    // Extract the points that form the route to construct polyline of sourceRoute
    var pointsList = [];
    var routeObj = serviceResult.result.recordsets[0].features.features[0].geometry.coordinates[0];
    for (var i = 0; i < routeObj.length; i++) {
        pointsList.push([routeObj[i][1], routeObj[i][0], routeObj[i][2]])
    }
    var routeLine = L.polyline(pointsList);
    // Construct Route Locator Point service
    var serviceUrl ="https://iserver.supermap.io/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst";
    var routeLocatorService = new L.supermap.SpatialAnalystService(serviceUrl);
    // Set Route Locator Point parameters
    var routeLocatorParams_point = new L.supermap.RouteLocatorParameters({
        "sourceRoute": routeLine, // The route object
        "type": "POINT", // Type, point or line
        "measure": 200, // 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 = routeCaculateServiceResult.result;
    });
});See full example code »
                            

Enjoy the result.

Route locate 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 if we already know the measure values of the line segment to the road intersection are 10km to 800km.

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

                                        // Create route by SQL query
var queryBySQLService = new L.supermap.QueryService(baseUrl);
// Set SQL query service parameters
var queryBySQLParams = new L.supermap.QueryBySQLParameters({
    queryParams: [
        new L.supermap.FilterParameter({
            name: "RouteDT_road@Changchun",
            attributeFilter: "RouteID=1690"
        })]
    });
// Create SQL query service
queryBySQLService.queryBySQL(queryBySQLParams).then(function (serviceResult) {
    // Extract the points that form the route to construct routeLine of sourceRoute
    var pointsList = [];
    var routeObj = serviceResult.result.recordsets[0].features.features[0].geometry.coordinates[0];
    for (var i = 0; i < routeObj.length; i++) {
        pointsList.push([routeObj[i][1], routeObj[i][0], routeObj[i][2]])
    }
    var routeLine = L.polyline(pointsList);
    // Set Route Locator Line parameters
    var routeLocatorParams_line = new L.supermap.RouteLocatorParameters({
        "sourceRoute": routeLine, // The route object
        "type": "LINE", // Type, point or line
        "startMeasure": 10, // The from value of the line
        "endMeasure": 800, // The 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-changchun/restjsr/spatialanalyst";
    var routeLocatorService = new L.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 = routeCaculateServiceResult.result;
    })
});See full example code »
                                    

Enjoy the result.

Interpolation analysis

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

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

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

Enjoy the result.

Grid algebraic operation

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

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

The interface of grid algebraic operation is used as follows

                                //Create Grid Algebraic Operation server
var mathExpressionAnalysisService = new L.supermap.SpatialAnalystService(serviceUrl);
//Define the Grid Algebraic Operation server parameters
var mathExpressionAnalysisParameters = new L.supermap.MathExpressionAnalysisParameters({
    //Specify dataset, required
    dataset: "JingjinTerrain@Jingjin",
    //The algebraic expression of the raster operation to be executed, required
    expression: "[Jingjin.JingjinTerrain] + 600",
    //The data source that stores the result dataset, which must be set
    targetDatasource: "Jingjin",
    //The name of result dataset
    resultGridName: "MathExpressionAnalysis_Result",
    deleteExistResultDataset: true
});
//Initiating 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 calculation

Terrain calculation is also called terrain curvature calculation. The curvature of the grid data includes mean curvature, profile curvature and plane curvature. Curvature is the second derivative of the surface, or it can be called the slope of the slope. 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.

There are several raster datasets to be set for curvature calculations:

  • Data source: lists all the data sources in the current workspace, and selects the data source where the raster data set for curvature calculation is located;
  • Dataset: Lists all raster datasets in the current data source, and chooses the curvature to compute raster dataset in the list. If a raster dataset is selected in the workspace manager, the dataset is automatically located;
  • 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 calculation process.

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

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

Enjoy the result.

Kernel density analysis

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

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

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

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

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

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

Enjoy the result.

Traffic transfer analysis

The use of traffic transfer analysis is as follows:

  • 1. Define the query function for the start site and end site;
  • 2. 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, includeing 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 L.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 L.supermap.TrafficTransferAnalystService(serviceUrl)
        .analysisTransferSolution(params).then(function (serviceResult) {
            var result = serviceResult.result;
    });See full example code »

                                

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 L.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 L.supermap.TrafficTransferAnalystService(serviceUrl)
        .analysisTransferPath(params).then(function (serviceResult) {
            var transGuide = serviceResult.result;
        });
}See full example code »
                                

Enjoy the result.

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

Network analysis

SuperMap iClient for Leaflet supports:

  • Service area analysis
  • Closest facility analysis
  • Location-allocation analysis
  • Multi-traveler analysis / logistics distribution
  • Best route 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 = L.marker([-3375, 5605]);
// Network analysis result parameter
var resultSetting = new L.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 L.supermap.TransportationAnalystParameter({
// The analysis result content
resultSetting: resultSetting,
// The name of the resistance field
weightFieldName: "length"
});
// Service area analysis parameter
var findServiceAreasParams = new L.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 L.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and get the returned result
service.findServiceAreas(findServiceAreasParams).then(function (serviceResult) {
var result = serviceResult.result;
});See full example code »
                    

Enjoy the 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 L.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 L.supermap.TransportationAnalystParameter({
// The analysis result content
resultSetting: resultSetting,
turnWeightField: "TurnCost",
// The name of the resistance field
weightFieldName: "length"
});
var findClosetFacilitiesParams = new L.supermap.FindClosestFacilitiesParameters({
// Incident, generally for event locations that require service facility services
event: L.latLng(-3700, 5000),
// Number of facilities to find
expectFacilityCount: 1,
// Facility collection, generally the location of the service facility providing the service
facilities: [L.latLng(-3500, 2500), L.latLng(-2500, 5500), L.latLng(-4000, 7000)],
// 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 L.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and get the returned result
findClosetFacilitiesService.findClosestFacilities(findClosetFacilitiesParams).then(function (serviceResult) {
var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Location-allocation analysis

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

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

                        // Set up a resource supply center for facilities
var supplyCenterType_FIXEDCENTER = L.supermap.SupplyCenterType.FIXEDCENTER;
var supplyCenterType_NULL = L.supermap.SupplyCenterType.NULL;
var supplyCenterType_OPTIONALCENTER = L.supermap.SupplyCenterType.OPTIONALCENTER;
// Taking one center point as an example
var supplyCenters = [new L.supermap.SupplyCenter({
maxWeight: 500,             // The maximum cost of the resource supply center. It's a required parameters
nodeID: 139,                // The node ID number of the resource supply center point. It's a required parameters
resourceValue: 100,         // The maximum amount of service or quantity of goods that the resource supply center can provide. It's a required parameters
type: supplyCenterType_OPTIONALCENTER      // The types of resource centers include fixed centers and optional centers
})];
// Set the location-allocation analysis parameters
findLocationParameter = new L.supermap.FindLocationParameters({
// Number of resource supply centers expected to be used for final facility siting. It's a required parameters
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. It's a required parameters
weightName: "length",
// Resource supply center collection. It's a required parameters
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 L.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and get the returned result
findLocationService.findLocation(findLocationParams).then(function (serviceResult) {
var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Multi-traveler analysis / logistics distribution

Multi-traveler analysis, also known as logistics distribution, is to find M distribution center points and N delivery destinations (M, N is an integer greater than zero) in the network data set, 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 L.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 L.supermap.TransportationAnalystParameter({
// The analysis result content
resultSetting: resultSetting,
// The name of the resistance field
weightFieldName: "length"
});
// Multi-traveler analysis parameters
var findMTSPPathsParams = new L.supermap.FindMTSPPathsParameters({
// Distribution center collection
centers: [L.latLng(-5500, 6000), L.latLng(-2500, 5500), L.latLng(-3500, 2500)],
// Whether to specify the distribution center point and the delivery destination point by the node ID number
isAnalyzeById: false,
// Delivery target set
nodes: [L.latLng(-5000, 5000), L.latLng(-2800, 8000)],
// 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 L.supermap.NetworkAnalystService(serviceUrl);
// Send a request to the server and process the returned result
findMTSPPathsService.findMTSPPaths(findMTSPPathsParams).then(function (serviceResult) {
var result = serviceResult.result;
});See full example code »
                    

Enjoy the result.

Best path analysis

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

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

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

                        
var resultSetting = new L.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 L.supermap.TransportationAnalystParameter({
// The analysis result content
resultSetting: resultSetting,
// The name of the resistance field
weightFieldName: "length"
});
// Best path analysis parameters
var findPathParams = new L.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: [L.latLng(-3000, 4000), L.latLng(-2500, 5500), L.latLng(-4000, 6900)],
// 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";
var findPathService = new L.supermap.NetworkAnalystService(serviceUrl);
// 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;
});See full example code »
                    

Enjoy the result.

Client computing

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

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

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

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

  • Point
  • LineString
  • Polygon

This example needs to import

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

Taking Turf grid analysis as an example

                            //Initial turfLayer
var turfLayer = new L.supermap.TurfLayer(gridAnalyst.turfLayerOptions).addTo(map);
//Taking the Grids.squareGrid analysis type as an example for client computing
turfLayer.process("Grids.squareGrid", {
    "bbox": bbox,
    "cellSide": cellSide,
    "units": units,
    "completelyWithin": completelyWithin
});See full example code »
                                        

Enjoy the result.

Address match

SuperMap iClient for Leaflet 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 reverse geocoding. Geocoding is that 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 L.supermap.GeoCodingParameter({
address: "超图软件",
fromIndex:0, // Starting 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 L.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.

Reverse geocoding

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

                        // Reverse geocoding parameters
var geoDecodeParam = new L.supermap.GeoDecodingParameter({
x: 116.3518541194,
y: 40.00097839595,
fromIndex: 0, // Starting 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 ol.supermap.AddressMatchService(addressUrl);
// Send a request to the server for geocoding and get the returned result
addressMatchService.decode(geoDecodeParam).then(function (obj){
// Get the result returned by the server
var featuers = obj.result
});See full example code »
                    

Enjoy the result.

Big data analysis

The SuperMap iClient for Leaflet 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
  • Regional summary analysis
  • Vector cropping 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 caculation 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 data set unit is if the original data set 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 L.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: L.supermap.AnalystSizeUnit.METER,
radiusUnit: L.supermap.AnalystSizeUnit.METER,
areaUnit: L.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 L.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 L.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: L.supermap.StatisticAnalystMode.MAX, // statistical mode. Must be consistent with the number of weight fields
type: L.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 L.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

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 in distribute analysis service from SuperMap iServer refers to a single object in the query object data set to do spatial query on the data set being queried.如果查询对象数据集中有多个对象,则默认用 SmID 最小的对象对被查询数据集做空间查询。

This example needs to import

Leaflet.draw (https://github.com/Leaflet/Leaflet.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 L.supermap.SingleObjectQueryJobsParameter({
datasetName: 'ProcessingData_processing_newyorkZone_R',
datasetQuery: 'ProcessingData_processing_singleRegion_R', // The name of the data set 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 L.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 field.

Here are the basic steps to implement a reginal 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 L.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: L.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: L.supermap.StatisticAnalystMode.MAX,
// The name of statistics by standard attribute fields
standardFields: "LocationID",
weightedFields:false,
// The mode of statistics by weight field
weightedStatisticModes: "",
// The name of statistics by weight field
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: L.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 L.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 protion 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

                            Leaflet.draw (https://github.com/Leaflet/Leaflet.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 L.supermap.VectorClipJobsParameter({
datasetName: 'ProcessingData_newyork_taxi_2013-01_14k', //Source dataset
datasetOverlay: 'ProcessingData_processing_singleRegion_R', // Clip dataset
mode:L.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 L.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.

Data Flow

SuperMap iServer provides data flow service which realzes 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 = L.popup({offset: L.point(0, 0), autoPan: true});
//Create DataFlowLayer for subscribing the data flow Service and show the results on the map.
var dataFlowLayer = new L.supermap.DataFlowLayer(urlDataFlow, {
style: function (feature) {
return {
    fillColor: "red",
    fillOpacity: 1,
    radius: 6,
    weight: 0
};
},
onEachFeature: function (feature, layer) {
popup.setLatLng(L.GeoJSON.coordsToLatLng(feature.geometry.coordinates))
    .setContent(feature.properties.time);
if (!popup.isOpen()) {
    popup.addTo(map);
}
},
});
dataFlowLayer.addTo(map);

//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 L.supermap.QueryBySQLParameters({
queryParams: {
name: "Main_Road_L@China#1",
attributeFilter: "SMID = 1755"
}
});
new L.supermap
.QueryService(urlQuery)
.queryBySQL(param).then(function (serviceResult) {
featureResult = serviceResult;
dataFlowService = new L.supermap.DataFlowService(urlDataFlow).initBroadcast();
dataFlowService.on('broadcastSocketConnected').then(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"},
id: 1,
type: "Feature",
properties: {id: 1, time: new Date()}
};
dataFlowService.broadcast(feature);
count += 3;
}
See full example code »
            

Enjoy the result.

Data visualization

This guide will introduce you how to create data visualization with SuperMap iClient for Leaflet.

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

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

You need to get leaflet-heat.js plugin to create heat maps.There are two ways to import leaflet-heat.js plugin:

1. Download leaflet-heat.js

Download leaflet-heat.js from GitHub.

                    https://github.com/Leaflet/Leaflet.heat

                                                                                                                                        

Include the following code in the <head> of your HTML file.

<script src="leaflet-heat.js"></script>
                                                                    

2. Import via CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.heat/0.2.0/leaflet-heat.js"></script>
                                    

Example code.

                                        // Set the number and radius of hot spots
var heatNumbers = 150, heatRadius = 30;
// Array of coordinate information
var heatPoints = [];
//Traverse to add coordinate information
for (var i = 0; i < heatNumbers; i++) {
heatPoints[i]=[ Math.random() * 0.28 + 39.78, Math.random() * 0.5 + 116.12, Math.random() * 80];
}
//Call the render method and pass in the radius and transparency parameters,then add to the map
resultLayer = L.heatLayer(heatPoints, {
        radius: heatRadius,
        minOpacity: 0.5 }).addTo(map);See full example code »
    

Enjoy the result.

Animation

Leaflet provides the L.Icon.Pulse.js plugin for dynamic flash point effects. Support for Leaflet version 0.7.0 or later, compatible with modern browsers.

There are two ways to import L.Icon.Pulse.js plugin:

1. Download L.Icon.Pulse.js

Download L.Icon.Pulse.js from GitHub.

                    https://github.com/mapshakers/leaflet-icon-pulse

                

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

                    <script src="L.Icon.Pulse.js"></script>
<link rel="stylesheet" href="L.Icon.Pulse.css"/>
                                        

2. Import from

<script src="https://iclient.supermap.io/web/libs/leaflet/plugins/leaflet-icon-pulse/L.Icon.Pulse.js"></script>
<link rel="stylesheet" href="//iclient.supermap.io/libs/leaflet/plugins/leaflet-icon-pulse/L.Icon.Pulse.css"/>

           

Example code.

                //Traverse all feature points in the result array, convert coordinate information, add animation icon
var features = [{type: "Feature", coordinates :: [11395368.55482056, 2707397.005707026], id: 113},
{type: "Feature", coordinates :: [11395368.55482056, 2707397.005707026], id: 120}]
features.map(function (feature) {
var latLng = L.CRS.EPSG3857.unproject(L.point(feature.coordinates));
markers.push(L.marker(latLng,{icon: pulseIcon}));
});
//将动画标识添加到地图上
resultLayer = L.featureGroup(markers).addTo(map);See full example code »

Enjoy the result.

Aggregation

Leaflet.markercluster provides beautiful animated marker clustering functionality for Leaflet, a JS library for interactive maps.

There are two ways to import Leaflet.markercluster plugin:

1. Download Leaflet.markercluster

Download Leaflet.markercluster from GitHub.

                            https://github.com/Leaflet/Leaflet.markercluster

                                                                                                    

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

            <script src="leaflet.markercluster.js"></script>
<link rel="stylesheet" href="MarkerCluster.Default.css"/>
<link rel="stylesheet" href="MarkerCluster.css"/>
                                

2. Import from CDN

            <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.3.0/leaflet.markercluster.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.3.0/MarkerCluster.Default.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.3.0/MarkerCluster.css"/>

Example code.

                                    resultLayer = L.markerClusterGroup({
spiderfyOnMaxZoom: false,
//Show the range occupied by the cluster when set to true
showCoverageOnHover: false,
//When set to true, it will scale to a lower level cluster
zoomToBoundsOnClick: false
});
result.features.map(function (feature) {
var latLng = L.CRS.EPSG3857.unproject(L.point(feature.geometry.coordinates));
resultLayer.addLayer(L.marker(latLng));
});
resultLayer.addTo(map);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)
                          

Create a graphicLayer and randomly draw 100,000 circles for visual display.

                                        var colorCount = 10;
var colors = getRandomColors(colorCount);
function addGraphicLayer() {
//Generate total number of circles
var count = 100000;
var graphics = [];
var e = 45;
var randomCircleStyles = [];
for (var i = 0; i < colorCount; i++) {
//Define style related properties, such as fill color, border color, radius, etc.
randomCircleStyles.push(new L.supermap.CircleStyle({
    color: colors[i],
    opacity: 1,
    radius: Math.floor(Math.random() * 15 + 1),
    fill: true,
    fillColor: colors[i],
    fillOpacity: 1
}));
}
//Draw an object and add it to the layer
for (var i = 0; i < count; ++i) {
//Loop generation random point coordinates
var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
//Define layers
graphics[i] = new L.supermap.Graphic({
    latLng: L.latLng(coordinates[0], coordinates[1]),
    style: randomCircleStyles[Math.floor(Math.random() * colorCount)].getCanvas()
});
}
//Render the drawn points to the map
new L.supermap.GraphicLayer(graphics).addTo(map);
}

//Generate random colors
function getRandomColors(count) {
return randomColor({
luminosity: 'bright',
hue: 'random',,
alpha: 0.5,
format: 'rgba',
count: count
});
}See full example code »
                                    

Enjoy the result.

ECharts

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

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

This example needs to import

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

SuperMap iClient for Leaflet supports for using Echarts visualization layer.

                            new L.supermap.EchartsLayer(option)
                        

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

                        var map;
//Load data and process the data
$.get('../data/lines-bus.json', function (data) {
var hStep = 300 / (data.length - 1);
var busLines = [].concat.apply([], data.map(function (busLine, idx) {
var prevPt;
var points = [];
for (var i = 0; i < busLine.length; i += 2) {
    var pt = [busLine[i], busLine[i + 1]];
    if (i > 0) {
        pt = [
            prevPt[0] + pt[0],
            prevPt[1] + pt[1]
        ];
    }
    prevPt = pt;
    points.push([pt[0] / 1e4, pt[1] / 1e4]);
}
return {
    coords: points,
    lineStyle: {
        normal: {
            color: echarts.color.modifyHSL('#5A94DF', Math.round(hStep * idx))
        }
    }
};
}));
//Specify configuration items and data for the chart
//Visualize data in a map
new L.supermap.EchartsLayer(option).addTo(map);
});
            

Specify configuration items and data for the chart.

                       option = {
//Chart configuration object
series: [
{
 //Type of chart
type: 'lines',
coordinateSystem: 'leaflet',
polyline: true,
data: busLines,
 //Whether the icon is static and cannot interact
silent: true,
lineStyle: {
    normal: {
        opacity: 0.2,
        width: 1
    }
},
 //Enable the number of graphics thresholds for progressive rendering
progressiveThreshold: 500,
 //Number of graphics drawn per frame during progressive rendering
progressive: 200
},
{
type: 'lines',
coordinateSystem: 'leaflet',
polyline: true,
data: busLines,
lineStyle: {
    normal: {
        width: 0
    }
},
 //Line effect configuration
effect: {
    constantSpeed: 20,
    show: true,
    trailLength: 0.1,
    symbolSize: 1.5
},
zlevel: 1
}]
};
See full example code »
                    

Enjoy the result.

MapV

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

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

This example needs to import

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

SuperMap iClient for Leaflet supports for using MapV visualization layer.

                            new L.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 citys = [cities];
var cityCenter = mapv.utilCityCenter.getCenterByCityName
var node_data = {
x: cityCenter.lng - 5 + Math.random() * 10,
y: cityCenter.lat - 5 + Math.random() * 10,
};
//Custom data
var edge_data = [
{"source": ~~(i * Math.random()), "target": '0'}
];
var results = mapv.utilForceEdgeBundling().nodes(node_data).edges(edge_data);
var data=[{datas}];
var timeData=[{timeData}];
//Create MapV layer
var dataSet1 = new mapv.DataSet(data);
//Set the style of MapV layer
var options1 = {
strokeStyle: 'rgba(55, 50, 250, 0.3)',
// Color overlay
globalCompositeOperation: 'lighter',
shadowColor: 'rgba(55, 50, 250, 0.5)',
shadowBlur: 10,
// Event callback functions
methods: {
click: function (item) {
}
},
lineWidth: 1.0,
//How to draw points, lines, and faces
draw: 'simple'
};
new L.supermap.MapVLayer(dataSet1, options1).addTo(map);

//Create MapV layer
var dataSet2 = new mapv.DataSet(timeData);
var options2 = {
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'
};
new L.supermap.MapVLayer(dataSet2, options2).addTo(map);See full example code »
                                                
                                            

Enjoy the result.

D3

D3 is a visual javascript library based on data manipulation html documents. D3 combines data with HTML, SVG, and CSS to create interactive data charts. D3 emphasizes Web standards, allowing you to leverage the power of modern browsers without the need for proprietary frameworks, combining powerful visualization components and data-driven methods into DOM operations.

For browser compatibility, D3 supports recent browsers such as Chrome, Edge, Firefox and Safari. D3 4.0 and below also supports IE9 and above. Some modules of D3 can work in older browsers.

This example needs to import

D3 (https://github.com/d3/d3)
                            
Leaflet.D3SvgOverlay (https://github.com/SuperMap/Leaflet.D3SvgOverlay)
                            

SuperMap iClient for Leaflet supports for using D3 visualization layer.

                            L.supermap.d3Layer(callback)
                        
                        var uniqueMap = {
"草地": "rgb(193,255,193)",
"城市": "rgb(205,112,84)",
"灌丛": "rgb(124,205,124)",
"旱地": "rgb(238,154,73)",
"湖泊水库": "rgb(142,229,238)",
"经济林": "rgb(222,184,135)",
"水浇地": "rgb(224,255,255)",
"水田": "rgb(56,142,142)",
"用材林": "rgb(85,107,47)",
"沼泽": "rgb(47,79,79)",
"缺省风格": "rgb(171,171,171)"
};
var d3Layer = L.supermap.d3Layer(function (sel, proj) {
var upd = sel.selectAll('path').data(serviceResult.result.features.features);
upd.enter()
.append('path')
.attr('d', proj.pathFromGeojson)
.attr('fill', function (feature) {
return uniqueMap[feature.properties.LANDTYPE];
})
.attr('fill-opacity', '0.8');
d3Layer.addTo(map);See full example code »

Enjoy the result.

OSM Buildings

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

OSM Buildings supports GeoJSON format。

There are two ways to import OSMBuildings-Leaflet.js plugin.

1. Download OSMBuildings-Leaflet.js plugin

Download OSMBuildings-Leaflet.js plugin from GitHub.

https://github.com/kekscom/osmbuildings

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

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

2. Import via CDN

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

Core code.

                $.get('../data/buildings.json', function (geojson) {
data = geojson;
new OSMBuildings(map)
.date(new Date(2017, 5, 15, 17,30))
.set(geojson)
});See full example code »

Enjoy the result.