SuperMap iClient3D for WebGL
Mainly introduces the introduction usage of SuperMap iClient3D for WebGL. For detailed interface parameters, please refer to the API page.
Prepare
Get SuperMap iClient3D for WebGL
SuperMap iClient3D for WebGL needs to be introduced during development. Including the necessary CSS files and JS file. You can get it in the following ways:
SuperMap iClient3D for WebGL
- via SuperMap iClient3D for WebGL official website Download the latest version
Import
Introduction by file method
After decompressing the obtained version of SuperMap iClient3D for WebGL, create a new HTML file in the examples folder, Pass in the file<script> The label introduces the Supermap3D.js file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../Build/SuperMap3D/SuperMap3D.js"></script>
</head>
</html>
At the same time as needed <head> Other css files and js files of SuperMap iClient3D for WebGL are introduced in the label, as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<link href="../Build/SuperMap3D/Widgets/widgets.css" rel="stylesheet">
<link href="./css/pretty.css" rel="stylesheet">
<script src="./js/jquery.min.js"></script>
<script src="./js/config.js"></script>
<script type="text/javascript" src="../Build/SuperMap3D/SuperMap3D.js"></script>
</head>
</html>
Create a 3D scene
Initialize the three-dimensional ball
In the preparation chapter, a new HTML page has been created, continue to add code in the page to initialize the three-dimensional ball, as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<link href="../Build/SuperMap3D/Widgets/widgets.css" rel="stylesheet">
<link href="./css/pretty.css" rel="stylesheet">
<script src="./js/jquery.min.js"></script>
<script src="./js/config.js"></script>
<script type="text/javascript" src="../Build/SuperMap3D/SuperMap3D.js"></script>
</head>
<body>
<div id="Container"></div>
<script>
function onload(SuperMap3D) {
var viewer = new SuperMap3D.Viewer('Container');
}
</html>
Set map style
While initializing, for example: superimpose local pictures on the initialized 3D ball as an image:
<script>
function onload(SuperMap3D) {
var viewer = new SuperMap3D.Viewer('Container');
//Use a local picture to initialize the earth, the recommended picture aspect ratio is 2:1
viewer.imageryLayers.addImageryProvider(new SuperMap3D.SingleTileImageryProvider({
url : './images/worldimage.jpg'
}));
}
Operation effect
Quoting online maps:SuperMap iClient3D for WebGL encapsulates a variety of Internet map information,
For example, BingMap, Tianditu, etc, and provide image addition interfaces BingMapsImageryProvider
and TiandituImageryProvider
Add BingMap image as:
<script>
function onload(SuperMap3D) {
var viewer = new SuperMap3D.Viewer('Container');
viewer.imageryLayers.addImageryProvider(new SuperMap3D.BingMapsImageryProvider({
url : 'https://dev.virtualearth.net',
mapStyle : SuperMap3D.BingMapsStyle.AERIAL,
key : BING_MAP_KEY //Key applied by BingMap official website
}));
}
Operation effect
Add the sky map as a base map:
<script>
function onload(SuperMap3D) {
var viewer = new SuperMap3D.Viewer('Container');
var labelImagery = new SuperMap3D.TiandituImageryProvider({
mapStyle: SuperMap3D.TiandituMapsStyle.CIA_C,//TianDitu Global Chinese annotation service
token: TOKEN_TIANDITU //Key applied for by Tiantu official website
});
viewer.imageryLayers.addImageryProvider(labelImagery);
}
Operation effect
Add layer
SuperMap iClient3D for WebGL provides a variety of interfaces to support adding a variety of data layers to the created 3D scene:
Add terrain layer:
terrainProvider : new SuperMap3D.SuperMapTerrainProvider({
url : TEST_TERRAIN, //Address of terrain service
isSct : true //The terrain service is derived from SuperMap iServer and needs to be set to true when publishing
})
Add an image layer:
var layer = new SuperMap3D.SuperMapImageryProvider({
url : TEST_IMG //Address of image service
});
var imgLayer = viewer.imageryLayers.addImageryProvider(layer)
Add S3M layer:The S3M service published on SuperMap iServer can be opened in the following two ways.
(1). Open the entire scene through the open interface. This method is simple and easy to operate and it is not easy to miss the layer.
var scene = viewer.scene;
var promise = scene.open("http://localhost:8090/iserver/services/3D-test/rest/realspace"); //url is the service address published on SuperMap iServer
(2). Add through the addS3MTilesLayerByScp
interface. The advantage of this method is that you can select some layers to add to the scene according to your needs to improve the loading performance, but you need to load multiple layers The whole scene is not as convenient as scene.open.
var promise = scene.addS3MTilesLayerByScp('http://localhost:8090/iserver/services/3D-test/rest/realspace/datas/zj/config',
{
name : "base",
cacheKey: "123456" //3D cache key, set and obtained by SuperMap iServer
});
promise.then(function(layer){
layer.visible = true;
});
Add MVT layer: After publishing the vector tile map generated by the map in the SuperMap desktop product through SuperMap iServer as a vector tile or 3D service, Use the interface addVectorTilesMap in WebGL to add the MVT layer service to the scene.
var mvtMap = scene.addVectorTilesMap({
url: url, //MVT service address
canvasWidth: 512,
name: 'testMVT',
viewer: viewer
});
Scene Setting
SuperMap iClient3D for WebGL provides a variety of interfaces to facilitate users to customize the scene.
Color settings
SuperMap iClient3D for WebGL supports setting the color of the scene:
viewer.scene.colorCorrection.show = true;
viewer.scene.colorCorrection.saturation = $("#saturation").val();
viewer.scene.colorCorrection.brightness = $("#brightness").val();
viewer.scene.colorCorrection.contrast = $("#contrast").val();
viewer.scene.colorCorrection.hue = $("#hue").val();
//Color correction switch
$("#colorCorrectionShow").on("input change", function() {
viewer.scene.colorCorrection.show = this.checked;
});
//Adjust saturation
$("#saturation").on("input change", function() {
viewer.scene.colorCorrection.saturation = this.value;
});
//Adjust the brightness
$("#brightness").on("input change", function() {
viewer.scene.colorCorrection.brightness = this.value;
});
//Adjust the contrast
$("#contrast").on("input change", function() {
viewer.scene.colorCorrection.contrast = this.value;
});
//Adjust the hue
$("#hue").on("input change", function() {
viewer.scene.colorCorrection.hue = this.value;
});
looming effect setting
SuperMap iClient3D for WebGL supports enabling floodlight in the scene, and supports setting the floodlight effect
//Flood light effect switch
viewer.scene.bloomEffect.show = this.checked;
//Adjust the brightness threshold
$("#bloom-threshold").on("input change", function() {
viewer.scene.bloomEffect.threshold = parseFloat(this.value);
});
//Adjust flood light intensity
$("#bloom-intensity").on("input change", function() {
viewer.scene.bloomEffect.bloomIntensity = parseFloat(this.value);
});
Split screen display
Support split-screen display of the scene, and perform different operations on the data in the scene in different viewports. Currently SuperMap iClient3D for WebGL supports Set 6 modes: "NONE", "HORIZONTAL", "TRIPLE", "VERTICAL", "VerticalTrisection" and "QUAD".
scene.multiViewportMode = SuperMap3D.MultiViewportMode[value];
Scene drawing
SuperMap iClient3D for WebGL supports saving a certain angle of a specified scene as a picture in the browser to the local. The specific method is:
//Generate a canvas based on the picture
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
};
//Save the picture locally
function download(base64data) {
var image = new Image();
image.src = base64data;
image.onload = function() {
var canvas = convertImageToCanvas(image);
url = canvas.toDataURL("image/jpeg");
var a = document.createElement('a');
var event = new MouseEvent('click');
a.download = (new Date()).getTime() + ".jpg"; // Specify the name of the downloaded picture
a.href = url;
a.dispatchEvent(event); // Click event that triggers hyperlink
}
}
Query
Spatial query
SuperMap iClient3D for WebGL provides a rich interface to support the spatial position information query of the scene model and GPU space query functions.
Spatial location information query: Obtain the spatial information of the mouse click position in real time.
var handler = new SuperMap3D.ScreenSpaceEventHandler(scene.canvas);
//Set the left mouse button click callback event
handler.setInputAction(function(e) {
//First remove the points added before
viewer.entities.removeAll();
//Get the Cartesian coordinates of the click position
var position = scene.pickPosition(e.position);
//Convert Cartesian coordinates to latitude and longitude coordinates
var cartographic = SuperMap3D.Cartographic.fromCartesian(position);
var longitude = SuperMap3D.Math.toDegrees(cartographic.longitude);
var latitude = SuperMap3D.Math.toDegrees(cartographic.latitude);
var height = cartographic.height;
if(height < 0) {
height = 0;
}
//Create pop-up box information to view the acquired location information instantly
var entity = new SuperMap3D.Entity({
name : "Position Information",
description : createDescription(SuperMap3D, [longitude, latitude, height])
});
viewer.selectedEntity = entity;
//In order to display the location of the query more intuitively, add the corresponding point at the click
viewer.entities.add(new SuperMap3D.Entity({
point : new SuperMap3D.PointGraphics({
color : new SuperMap3D.Color(1, 1, 0),
pixelSize : 10,
outlineColor : new SuperMap3D.Color(0, 1, 1)
}),
position : SuperMap3D.Cartesian3.fromDegrees(longitude, latitude , height + 0.5)
}));
}, SuperMap3D.ScreenSpaceEventType.LEFT_CLICK);
GPU Spatial Query: Create a query object in the scene, and obtain the spatial relationship between the query object and the model or model sub-objects through GPU space analysis. Currently the query object supports GeoCone, GeoBox, GeoCylinder, GeoEllipsoid and GeoSphere, etc. The sample code is as follows:
var geometry = undefined;
var pos = undefined;
var mode = SuperMap3D.PositionMode.Intersects
var spatialQuery = new SuperMap3D.SpatialQuery3D(scene);
var handler = new SuperMap3D.ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction(function (evt) {
var length = 100;
var width = 100;
var height = 100;
// Get the Cartesian coordinates of the mouse click
var cartesian = scene.pickPosition(evt.position);
var cartographic = SuperMap3D.Cartographic.fromCartesian(cartesian);
pos = new SuperMap3D.Point3D(SuperMap3D.Math.toDegrees(cartographic.longitude), SuperMap3D.Math.toDegrees(cartographic.latitude), cartographic.height);
geometry = new SuperMap3D.GeoBox(length, width, height);
geometry.geoPosition = pos;
spatialQuery.geometry = geometry;
spatialQuery.positionMode = mode;
spatialQuery.layers = layerSelect;
spatialQuery.outlineColor = SuperMap3D.Color.CORNFLOWERBLUE;
spatialQuery.fillStyle = SuperMap3D.FillStyle.Fill_And_WireFrame
spatialQuery.build();
tooltip.setVisible(false);
handler.removeInputAction(SuperMap3D.ScreenSpaceEventType.MOUSE_MOVE) //Remove mouse movement event listener
}, SuperMap3D.ScreenSpaceEventType.LEFT_CLICK);
Operation effect
Attribute query
Attribute query refers to querying the layer or object attributes of the S3M model in the scene
function doSqlQuery(SQL) {
var getFeatureParam;
getFeatureParam = new SuperMap.REST.FilterParameter({
attributeFilter: SQL //SQL is the query condition
});
Measurement
SuperMap iClient3D for WebGL provides a measurement function, which supports real-time measurement of distance, area and height difference of terrain or S3M models on the front end. It also supports the measurement of the ground distance and the ground area.
The following code shows the method of distance measurement:
var handlerDis;
//Initialize measuring distance
handlerDis = new SuperMap3D.MeasureHandler(viewer, SuperMap3D.MeasureMode.Distance, clampMode);
//Register the event of ranging function
handlerDis.measureEvt.addEventListener(function (result) {
var dis = Number(result.distance);
var selOptV = $("#selOpt").val();
var positions = result.positions;
if (selOptV == 3 || selOptV == 4) {
dis = Number(calcClampDistance(positions));
}
var distance = dis > 1000 ? (dis / 1000).toFixed(2) + 'km' : dis.toFixed(2) + 'm';
handlerDis.disLabel.text = 'Distance:' + distance;
});
Operation effect
Drawing
SuperMap iClient3D for WebGL supports real-time drawing of points, lines and areas on the front end.
The following code shows how to draw a line on the front end:
var handlerLine = new SuperMap3D.DrawHandler(viewer,SuperMap3D.DrawMode.Line);
handlerLine.activeEvt.addEventListener(function(isActive){
if(isActive == true){
viewer.enableCursorStyle = false;
viewer._element.style.cursor = '';
$('body').removeClass('drawCur').addClass('drawCur');
}
else{
viewer.enableCursorStyle = true;
$('body').removeClass('drawCur');
}
});
handlerLine.movingEvt.addEventListener(function(windowPosition){
if(handlerLine.isDrawing){
tooltip.showAt(windowPosition,'<p>Left click to confirm the middle point of the polyline</p><p>Right click to end drawing</p>');
}
else{
tooltip.showAt(windowPosition,'<p>Click to draw the first point</p>');
}
});
handlerLine.drawEvt.addEventListener(function(result){
tooltip.setVisible(false);
});
Three-Dimensional Spatial Analysis
SuperMap iClient3D for WebGL supports a series of spatial analysis of 3D scenes.
Visibility analysis
Visibility analysis refers to the analysis of the visibility between specified two points in the scene. The specific steps are as follows:
(1). Open the 3D scene or add 3D layers. For this step, please refer to "Overlay S3M Layers" in "Add Layers".
(2). Convert the acquired point coordinates to latitude and longitude coordinates, and conduct a visual analysis.
var cartographic = SuperMap3D.Cartographic.fromCartesian(position);
var longitude = SuperMap3D.Math.toDegrees(cartographic.longitude);
var latitude = SuperMap3D.Math.toDegrees(cartographic.latitude);
var height = cartographic.height;
(3). Add observation points and target points, and conduct a visual analysis.
//Set observation point
sightline.viewPosition = [longitude, latitude, height];
//Add target point
sightline.addTargetPoint({
position : [longitude, latitude, height],
name : "point" + new Date()
});
ViewDom analysis
Visibility analysis refers to the analysis of the visibility of objects in a certain field of view based on a specified observation point in a three-dimensional scene. The main steps are:
(1). Open the 3D scene.
(2). Create a visual domain analysis object, and specify the display style of the visible area and the invisible area:
var viewshed3D = new SuperMap3D.ViewShed3D(scene);
var colorStr1 = viewshed3D.visibleAreaColor.toCssColorString();
var colorStr2 = viewshed3D.hiddenAreaColor.toCssColorString();
$("#colorPicker1").spectrum({
color: colorStr1,
showPalette: true,
showAlpha: true,
localStorageKey: "spectrum.demo",
palette: palette
});
$('#colorPicker2').spectrum({
color: colorStr2,
showPalette: true,
showAlpha: true,
localStorageKey: "spectrum.demo",
palette: palette
});
(3). Set the viewport position:
var viewPosition;
viewshed3D.viewPosition = [longitude, latitude, height];
(4). Take the observer position (viewport position point) as the center of the sphere, pick a point in the scene, and draw the three-dimensional visual field with the line connecting the observer position and the point as the radius:
//Calculate the distance between the point and the coordinate of the viewport position
var distance = SuperMap3D.Cartesian3.distance(viewPosition, last);
if (distance > 0) {
// Convert the coordinates of the current mouse point into latitude and longitude
var cartographic = SuperMap3D.Cartographic.fromCartesian(last);
var longitude = SuperMap3D.Math.toDegrees(cartographic.longitude);
var latitude = SuperMap3D.Math.toDegrees(cartographic.latitude);
var height = cartographic.height;
// Set the distance and direction of the visual domain analysis object through this point
viewshed3D.setDistDirByPoint([longitude, latitude, height]);
}
(5). Perform visual domain analysis:
viewshed3D.build();
Shadow analysis
Shadow analysis refers to the analysis of the shadow rate of a specified area in the scene within a specified time period. The main steps are:
(1). Open the 3D scene. It is worth noting that when creating the Viewer, the shadow should be turned on to ensure that the shadow is available:
var viewer = new SuperMap3D.Viewer('Container', {
shadows : true
});
(2). Create a shadow query object, and set the shadow mode of the layer:
//Create a shadow query object
var shadowQuery = new SuperMap3D.ShadowQueryPoints(scene);
//Set the shadow mode of the layer
layers[0].shadowType = 2; //2 means that all models on the layer produce shadows
layers[1].shadowType = 2;
(3). Draw the shadow analysis area:
var handlerPolygon = new SuperMap3D.DrawHandler(viewer,SuperMap3D.DrawMode.Polygon,0);
handlerPolygon.activeEvt.addEventListener(function(isActive){
if(isActive == true){
viewer.enableCursorStyle = false;
viewer._element.style.cursor = '';
$('body').removeClass('drawCur').addClass('drawCur');
}
else{
viewer.enableCursorStyle = true;
$('body').removeClass('drawCur');
}
});
(4).After the shadow analysis is completed, you can also obtain the shadow rate at the spatial position in the analysis area:
var shadowRadio=shadowQuery.getShadowRadio(cartographic);
(5).Perform shadow analysis:
shadowQuery.build();
Skyline analysis
Skyline analysis refers to drawing and analyzing the skyline of a three-dimensional scene. The main steps are:
(1). Open the 3D scene.
(2). Create a skyline analysis object:
var skyline = new SuperMap3D.Skyline(scene);
(3). To make the result intuitive, set the current camera position as the viewport of the skyline analysis:
//The viewport position of the skyline analysis is set to the current camera position
skyline.viewPosition = [longitude, latitude, height];
//Set pitch and direction
skyline.pitch = SuperMap3D.Math.toDegrees(scene.camera.pitch);
skyline.direction = SuperMap3D.Math.toDegrees(scene.camera.heading);
skyline.radius = 10000; // Set the analysis radius of the skyline, unit: meter
(4).Perform skyline analysis:
skyline.build();
(5).Extract two-dimensional skyline:
var object = skyline.getSkyline2D();
(6). In addition, SuperMap iClient3D for WebGL also supports drawing height-limiting bodies to assist planning and construction departments to make decisions. The meaning of the height limit body is that in the current viewport, in order to keep the current skyline unchanged, the height of the building built in the designated area cannot exceed the height of the height limit body. The drawing method is as follows:
skyline.addLimitbody({
position: arr,
name: "limitBody"
});