/*! * * iclient-openlayers * Copyright© 2000 - 2023 SuperMap Software Co.Ltd * license: Apache-2.0 * version: v11.1.0-beta * */ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 693: /***/ (function(module) { (function(self) { 'use strict'; // if __disableNativeFetch is set to true, the it will always polyfill fetch // with Ajax. if (!self.__disableNativeFetch && self.fetch) { return } function normalizeName(name) { if (typeof name !== 'string') { name = String(name) } if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { throw new TypeError('Invalid character in header field name') } return name.toLowerCase() } function normalizeValue(value) { if (typeof value !== 'string') { value = String(value) } return value } function Headers(headers) { this.map = {} if (headers instanceof Headers) { headers.forEach(function(value, name) { this.append(name, value) }, this) } else if (headers) { Object.getOwnPropertyNames(headers).forEach(function(name) { this.append(name, headers[name]) }, this) } } Headers.prototype.append = function(name, value) { name = normalizeName(name) value = normalizeValue(value) var list = this.map[name] if (!list) { list = [] this.map[name] = list } list.push(value) } Headers.prototype['delete'] = function(name) { delete this.map[normalizeName(name)] } Headers.prototype.get = function(name) { var values = this.map[normalizeName(name)] return values ? values[0] : null } Headers.prototype.getAll = function(name) { return this.map[normalizeName(name)] || [] } Headers.prototype.has = function(name) { return this.map.hasOwnProperty(normalizeName(name)) } Headers.prototype.set = function(name, value) { this.map[normalizeName(name)] = [normalizeValue(value)] } Headers.prototype.forEach = function(callback, thisArg) { Object.getOwnPropertyNames(this.map).forEach(function(name) { this.map[name].forEach(function(value) { callback.call(thisArg, value, name, this) }, this) }, this) } function consumed(body) { if (body.bodyUsed) { return Promise.reject(new TypeError('Already read')) } body.bodyUsed = true } function fileReaderReady(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { resolve(reader.result) } reader.onerror = function() { reject(reader.error) } }) } function readBlobAsArrayBuffer(blob) { var reader = new FileReader() reader.readAsArrayBuffer(blob) return fileReaderReady(reader) } function readBlobAsText(blob, options) { var reader = new FileReader() var contentType = options.headers.map['content-type'] ? options.headers.map['content-type'].toString() : '' var regex = /charset\=[0-9a-zA-Z\-\_]*;?/ var _charset = blob.type.match(regex) || contentType.match(regex) var args = [blob] if(_charset) { args.push(_charset[0].replace(/^charset\=/, '').replace(/;$/, '')) } reader.readAsText.apply(reader, args) return fileReaderReady(reader) } var support = { blob: 'FileReader' in self && 'Blob' in self && (function() { try { new Blob(); return true } catch(e) { return false } })(), formData: 'FormData' in self, arrayBuffer: 'ArrayBuffer' in self } function Body() { this.bodyUsed = false this._initBody = function(body, options) { this._bodyInit = body if (typeof body === 'string') { this._bodyText = body } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { this._bodyBlob = body this._options = options } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { this._bodyFormData = body } else if (!body) { this._bodyText = '' } else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) { // Only support ArrayBuffers for POST method. // Receiving ArrayBuffers happens via Blobs, instead. } else { throw new Error('unsupported BodyInit type') } } if (support.blob) { this.blob = function() { var rejected = consumed(this) if (rejected) { return rejected } if (this._bodyBlob) { return Promise.resolve(this._bodyBlob) } else if (this._bodyFormData) { throw new Error('could not read FormData body as blob') } else { return Promise.resolve(new Blob([this._bodyText])) } } this.arrayBuffer = function() { return this.blob().then(readBlobAsArrayBuffer) } this.text = function() { var rejected = consumed(this) if (rejected) { return rejected } if (this._bodyBlob) { return readBlobAsText(this._bodyBlob, this._options) } else if (this._bodyFormData) { throw new Error('could not read FormData body as text') } else { return Promise.resolve(this._bodyText) } } } else { this.text = function() { var rejected = consumed(this) return rejected ? rejected : Promise.resolve(this._bodyText) } } if (support.formData) { this.formData = function() { return this.text().then(decode) } } this.json = function() { return this.text().then(JSON.parse) } return this } // HTTP methods whose capitalization should be normalized var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] function normalizeMethod(method) { var upcased = method.toUpperCase() return (methods.indexOf(upcased) > -1) ? upcased : method } function Request(input, options) { options = options || {} var body = options.body if (Request.prototype.isPrototypeOf(input)) { if (input.bodyUsed) { throw new TypeError('Already read') } this.url = input.url this.credentials = input.credentials if (!options.headers) { this.headers = new Headers(input.headers) } this.method = input.method this.mode = input.mode if (!body) { body = input._bodyInit input.bodyUsed = true } } else { this.url = input } this.credentials = options.credentials || this.credentials || 'omit' if (options.headers || !this.headers) { this.headers = new Headers(options.headers) } this.method = normalizeMethod(options.method || this.method || 'GET') this.mode = options.mode || this.mode || null this.referrer = null if ((this.method === 'GET' || this.method === 'HEAD') && body) { throw new TypeError('Body not allowed for GET or HEAD requests') } this._initBody(body, options) } Request.prototype.clone = function() { return new Request(this) } function decode(body) { var form = new FormData() body.trim().split('&').forEach(function(bytes) { if (bytes) { var split = bytes.split('=') var name = split.shift().replace(/\+/g, ' ') var value = split.join('=').replace(/\+/g, ' ') form.append(decodeURIComponent(name), decodeURIComponent(value)) } }) return form } function headers(xhr) { var head = new Headers() var pairs = xhr.getAllResponseHeaders().trim().split('\n') pairs.forEach(function(header) { var split = header.trim().split(':') var key = split.shift().trim() var value = split.join(':').trim() head.append(key, value) }) return head } Body.call(Request.prototype) function Response(bodyInit, options) { if (!options) { options = {} } this._initBody(bodyInit, options) this.type = 'default' this.status = options.status this.ok = this.status >= 200 && this.status < 300 this.statusText = options.statusText this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers) this.url = options.url || '' } Body.call(Response.prototype) Response.prototype.clone = function() { return new Response(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new Headers(this.headers), url: this.url }) } Response.error = function() { var response = new Response(null, {status: 0, statusText: ''}) response.type = 'error' return response } var redirectStatuses = [301, 302, 303, 307, 308] Response.redirect = function(url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError('Invalid status code') } return new Response(null, {status: status, headers: {location: url}}) } self.Headers = Headers; self.Request = Request; self.Response = Response; self.fetch = function(input, init) { return new Promise(function(resolve, reject) { var request if (Request.prototype.isPrototypeOf(input) && !init) { request = input } else { request = new Request(input, init) } var xhr = new XMLHttpRequest() function responseURL() { if ('responseURL' in xhr) { return xhr.responseURL } // Avoid security warnings on getResponseHeader when not allowed by CORS if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) { return xhr.getResponseHeader('X-Request-URL') } return; } var __onLoadHandled = false; function onload() { if (xhr.readyState !== 4) { return } var status = (xhr.status === 1223) ? 204 : xhr.status if (status < 100 || status > 599) { if (__onLoadHandled) { return; } else { __onLoadHandled = true; } reject(new TypeError('Network request failed')) return } var options = { status: status, statusText: xhr.statusText, headers: headers(xhr), url: responseURL() } var body = 'response' in xhr ? xhr.response : xhr.responseText; if (__onLoadHandled) { return; } else { __onLoadHandled = true; } resolve(new Response(body, options)) } xhr.onreadystatechange = onload; xhr.onload = onload; xhr.onerror = function() { if (__onLoadHandled) { return; } else { __onLoadHandled = true; } reject(new TypeError('Network request failed')) } xhr.open(request.method, request.url, true) // `withCredentials` should be setted after calling `.open` in IE10 // http://stackoverflow.com/a/19667959/1219343 try { if (request.credentials === 'include') { if ('withCredentials' in xhr) { xhr.withCredentials = true; } else { console && console.warn && console.warn('withCredentials is not supported, you can ignore this warning'); } } } catch (e) { console && console.warn && console.warn('set withCredentials error:' + e); } if ('responseType' in xhr && support.blob) { xhr.responseType = 'blob' } request.headers.forEach(function(value, name) { xhr.setRequestHeader(name, value) }) xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) }) } self.fetch.polyfill = true // Support CommonJS if ( true && module.exports) { module.exports = self.fetch; } })(typeof self !== 'undefined' ? self : this); /***/ }), /***/ 144: /***/ (function(module, exports) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, module], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { var mod; } })(this, function (exports, module) { 'use strict'; var defaultOptions = { timeout: 5000, jsonpCallback: 'callback', jsonpCallbackFunction: null }; function generateCallbackFunction() { return 'jsonp_' + Date.now() + '_' + Math.ceil(Math.random() * 100000); } function clearFunction(functionName) { // IE8 throws an exception when you try to delete a property on window // http://stackoverflow.com/a/1824228/751089 try { delete window[functionName]; } catch (e) { window[functionName] = undefined; } } function removeScript(scriptId) { var script = document.getElementById(scriptId); if (script) { document.getElementsByTagName('head')[0].removeChild(script); } } function fetchJsonp(_url) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; // to avoid param reassign var url = _url; var timeout = options.timeout || defaultOptions.timeout; var jsonpCallback = options.jsonpCallback || defaultOptions.jsonpCallback; var timeoutId = undefined; return new Promise(function (resolve, reject) { var callbackFunction = options.jsonpCallbackFunction || generateCallbackFunction(); var scriptId = jsonpCallback + '_' + callbackFunction; window[callbackFunction] = function (response) { resolve({ ok: true, // keep consistent with fetch API json: function json() { return Promise.resolve(response); } }); if (timeoutId) clearTimeout(timeoutId); removeScript(scriptId); clearFunction(callbackFunction); }; // Check if the user set their own params, and if not add a ? to start a list of params url += url.indexOf('?') === -1 ? '?' : '&'; var jsonpScript = document.createElement('script'); jsonpScript.setAttribute('src', '' + url + jsonpCallback + '=' + callbackFunction); if (options.charset) { jsonpScript.setAttribute('charset', options.charset); } jsonpScript.id = scriptId; document.getElementsByTagName('head')[0].appendChild(jsonpScript); timeoutId = setTimeout(function () { reject(new Error('JSONP request to ' + _url + ' timed out')); clearFunction(callbackFunction); removeScript(scriptId); window[callbackFunction] = function () { clearFunction(callbackFunction); }; }, timeout); // Caught if got 404/500 jsonpScript.onerror = function () { reject(new Error('JSONP request to ' + _url + ' failed')); clearFunction(callbackFunction); removeScript(scriptId); if (timeoutId) clearTimeout(timeoutId); }; }); } // export as global function /* let local; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } local.fetchJsonp = fetchJsonp; */ module.exports = fetchJsonp; }); /***/ }), /***/ 962: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Builder = void 0; var byte_buffer_js_1 = __webpack_require__(505); var constants_js_1 = __webpack_require__(147); var Builder = /** @class */ (function () { /** * Create a FlatBufferBuilder. */ function Builder(opt_initial_size) { /** Minimum alignment encountered so far. */ this.minalign = 1; /** The vtable for the current table. */ this.vtable = null; /** The amount of fields we're actually using. */ this.vtable_in_use = 0; /** Whether we are currently serializing a table. */ this.isNested = false; /** Starting offset of the current struct/table. */ this.object_start = 0; /** List of offsets of all vtables. */ this.vtables = []; /** For the current vector being built. */ this.vector_num_elems = 0; /** False omits default values from the serialized data */ this.force_defaults = false; this.string_maps = null; var initial_size; if (!opt_initial_size) { initial_size = 1024; } else { initial_size = opt_initial_size; } /** * @type {ByteBuffer} * @private */ this.bb = byte_buffer_js_1.ByteBuffer.allocate(initial_size); this.space = initial_size; } Builder.prototype.clear = function () { this.bb.clear(); this.space = this.bb.capacity(); this.minalign = 1; this.vtable = null; this.vtable_in_use = 0; this.isNested = false; this.object_start = 0; this.vtables = []; this.vector_num_elems = 0; this.force_defaults = false; this.string_maps = null; }; /** * In order to save space, fields that are set to their default value * don't get serialized into the buffer. Forcing defaults provides a * way to manually disable this optimization. * * @param forceDefaults true always serializes default values */ Builder.prototype.forceDefaults = function (forceDefaults) { this.force_defaults = forceDefaults; }; /** * Get the ByteBuffer representing the FlatBuffer. Only call this after you've * called finish(). The actual data starts at the ByteBuffer's current position, * not necessarily at 0. */ Builder.prototype.dataBuffer = function () { return this.bb; }; /** * Get the bytes representing the FlatBuffer. Only call this after you've * called finish(). */ Builder.prototype.asUint8Array = function () { return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset()); }; /** * Prepare to write an element of `size` after `additional_bytes` have been * written, e.g. if you write a string, you need to align such the int length * field is aligned to 4 bytes, and the string data follows it directly. If all * you need to do is alignment, `additional_bytes` will be 0. * * @param size This is the of the new element to write * @param additional_bytes The padding size */ Builder.prototype.prep = function (size, additional_bytes) { // Track the biggest thing we've ever aligned to. if (size > this.minalign) { this.minalign = size; } // Find the amount of alignment needed such that `size` is properly // aligned after `additional_bytes` var align_size = ((~(this.bb.capacity() - this.space + additional_bytes)) + 1) & (size - 1); // Reallocate the buffer if needed. while (this.space < align_size + size + additional_bytes) { var old_buf_size = this.bb.capacity(); this.bb = Builder.growByteBuffer(this.bb); this.space += this.bb.capacity() - old_buf_size; } this.pad(align_size); }; Builder.prototype.pad = function (byte_size) { for (var i = 0; i < byte_size; i++) { this.bb.writeInt8(--this.space, 0); } }; Builder.prototype.writeInt8 = function (value) { this.bb.writeInt8(this.space -= 1, value); }; Builder.prototype.writeInt16 = function (value) { this.bb.writeInt16(this.space -= 2, value); }; Builder.prototype.writeInt32 = function (value) { this.bb.writeInt32(this.space -= 4, value); }; Builder.prototype.writeInt64 = function (value) { this.bb.writeInt64(this.space -= 8, value); }; Builder.prototype.writeFloat32 = function (value) { this.bb.writeFloat32(this.space -= 4, value); }; Builder.prototype.writeFloat64 = function (value) { this.bb.writeFloat64(this.space -= 8, value); }; /** * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary). * @param value The `int8` to add the the buffer. */ Builder.prototype.addInt8 = function (value) { this.prep(1, 0); this.writeInt8(value); }; /** * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary). * @param value The `int16` to add the the buffer. */ Builder.prototype.addInt16 = function (value) { this.prep(2, 0); this.writeInt16(value); }; /** * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary). * @param value The `int32` to add the the buffer. */ Builder.prototype.addInt32 = function (value) { this.prep(4, 0); this.writeInt32(value); }; /** * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary). * @param value The `int64` to add the the buffer. */ Builder.prototype.addInt64 = function (value) { this.prep(8, 0); this.writeInt64(value); }; /** * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary). * @param value The `float32` to add the the buffer. */ Builder.prototype.addFloat32 = function (value) { this.prep(4, 0); this.writeFloat32(value); }; /** * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary). * @param value The `float64` to add the the buffer. */ Builder.prototype.addFloat64 = function (value) { this.prep(8, 0); this.writeFloat64(value); }; Builder.prototype.addFieldInt8 = function (voffset, value, defaultValue) { if (this.force_defaults || value != defaultValue) { this.addInt8(value); this.slot(voffset); } }; Builder.prototype.addFieldInt16 = function (voffset, value, defaultValue) { if (this.force_defaults || value != defaultValue) { this.addInt16(value); this.slot(voffset); } }; Builder.prototype.addFieldInt32 = function (voffset, value, defaultValue) { if (this.force_defaults || value != defaultValue) { this.addInt32(value); this.slot(voffset); } }; Builder.prototype.addFieldInt64 = function (voffset, value, defaultValue) { if (this.force_defaults || value !== defaultValue) { this.addInt64(value); this.slot(voffset); } }; Builder.prototype.addFieldFloat32 = function (voffset, value, defaultValue) { if (this.force_defaults || value != defaultValue) { this.addFloat32(value); this.slot(voffset); } }; Builder.prototype.addFieldFloat64 = function (voffset, value, defaultValue) { if (this.force_defaults || value != defaultValue) { this.addFloat64(value); this.slot(voffset); } }; Builder.prototype.addFieldOffset = function (voffset, value, defaultValue) { if (this.force_defaults || value != defaultValue) { this.addOffset(value); this.slot(voffset); } }; /** * Structs are stored inline, so nothing additional is being added. `d` is always 0. */ Builder.prototype.addFieldStruct = function (voffset, value, defaultValue) { if (value != defaultValue) { this.nested(value); this.slot(voffset); } }; /** * Structures are always stored inline, they need to be created right * where they're used. You'll get this assertion failure if you * created it elsewhere. */ Builder.prototype.nested = function (obj) { if (obj != this.offset()) { throw new Error('FlatBuffers: struct must be serialized inline.'); } }; /** * Should not be creating any other object, string or vector * while an object is being constructed */ Builder.prototype.notNested = function () { if (this.isNested) { throw new Error('FlatBuffers: object serialization must not be nested.'); } }; /** * Set the current vtable at `voffset` to the current location in the buffer. */ Builder.prototype.slot = function (voffset) { if (this.vtable !== null) this.vtable[voffset] = this.offset(); }; /** * @returns Offset relative to the end of the buffer. */ Builder.prototype.offset = function () { return this.bb.capacity() - this.space; }; /** * Doubles the size of the backing ByteBuffer and copies the old data towards * the end of the new buffer (since we build the buffer backwards). * * @param bb The current buffer with the existing data * @returns A new byte buffer with the old data copied * to it. The data is located at the end of the buffer. * * uint8Array.set() formally takes {Array|ArrayBufferView}, so to pass * it a uint8Array we need to suppress the type check: * @suppress {checkTypes} */ Builder.growByteBuffer = function (bb) { var old_buf_size = bb.capacity(); // Ensure we don't grow beyond what fits in an int. if (old_buf_size & 0xC0000000) { throw new Error('FlatBuffers: cannot grow buffer beyond 2 gigabytes.'); } var new_buf_size = old_buf_size << 1; var nbb = byte_buffer_js_1.ByteBuffer.allocate(new_buf_size); nbb.setPosition(new_buf_size - old_buf_size); nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size); return nbb; }; /** * Adds on offset, relative to where it will be written. * * @param offset The offset to add. */ Builder.prototype.addOffset = function (offset) { this.prep(constants_js_1.SIZEOF_INT, 0); // Ensure alignment is already done. this.writeInt32(this.offset() - offset + constants_js_1.SIZEOF_INT); }; /** * Start encoding a new object in the buffer. Users will not usually need to * call this directly. The FlatBuffers compiler will generate helper methods * that call this method internally. */ Builder.prototype.startObject = function (numfields) { this.notNested(); if (this.vtable == null) { this.vtable = []; } this.vtable_in_use = numfields; for (var i = 0; i < numfields; i++) { this.vtable[i] = 0; // This will push additional elements as needed } this.isNested = true; this.object_start = this.offset(); }; /** * Finish off writing the object that is under construction. * * @returns The offset to the object inside `dataBuffer` */ Builder.prototype.endObject = function () { if (this.vtable == null || !this.isNested) { throw new Error('FlatBuffers: endObject called without startObject'); } this.addInt32(0); var vtableloc = this.offset(); // Trim trailing zeroes. var i = this.vtable_in_use - 1; // eslint-disable-next-line no-empty for (; i >= 0 && this.vtable[i] == 0; i--) { } var trimmed_size = i + 1; // Write out the current vtable. for (; i >= 0; i--) { // Offset relative to the start of the table. this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0); } var standard_fields = 2; // The fields below: this.addInt16(vtableloc - this.object_start); var len = (trimmed_size + standard_fields) * constants_js_1.SIZEOF_SHORT; this.addInt16(len); // Search for an existing vtable that matches the current one. var existing_vtable = 0; var vt1 = this.space; outer_loop: for (i = 0; i < this.vtables.length; i++) { var vt2 = this.bb.capacity() - this.vtables[i]; if (len == this.bb.readInt16(vt2)) { for (var j = constants_js_1.SIZEOF_SHORT; j < len; j += constants_js_1.SIZEOF_SHORT) { if (this.bb.readInt16(vt1 + j) != this.bb.readInt16(vt2 + j)) { continue outer_loop; } } existing_vtable = this.vtables[i]; break; } } if (existing_vtable) { // Found a match: // Remove the current vtable. this.space = this.bb.capacity() - vtableloc; // Point table to existing vtable. this.bb.writeInt32(this.space, existing_vtable - vtableloc); } else { // No match: // Add the location of the current vtable to the list of vtables. this.vtables.push(this.offset()); // Point table to current vtable. this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc); } this.isNested = false; return vtableloc; }; /** * Finalize a buffer, poiting to the given `root_table`. */ Builder.prototype.finish = function (root_table, opt_file_identifier, opt_size_prefix) { var size_prefix = opt_size_prefix ? constants_js_1.SIZE_PREFIX_LENGTH : 0; if (opt_file_identifier) { var file_identifier = opt_file_identifier; this.prep(this.minalign, constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH + size_prefix); if (file_identifier.length != constants_js_1.FILE_IDENTIFIER_LENGTH) { throw new Error('FlatBuffers: file identifier must be length ' + constants_js_1.FILE_IDENTIFIER_LENGTH); } for (var i = constants_js_1.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) { this.writeInt8(file_identifier.charCodeAt(i)); } } this.prep(this.minalign, constants_js_1.SIZEOF_INT + size_prefix); this.addOffset(root_table); if (size_prefix) { this.addInt32(this.bb.capacity() - this.space); } this.bb.setPosition(this.space); }; /** * Finalize a size prefixed buffer, pointing to the given `root_table`. */ Builder.prototype.finishSizePrefixed = function (root_table, opt_file_identifier) { this.finish(root_table, opt_file_identifier, true); }; /** * This checks a required field has been set in a given table that has * just been constructed. */ Builder.prototype.requiredField = function (table, field) { var table_start = this.bb.capacity() - table; var vtable_start = table_start - this.bb.readInt32(table_start); var ok = this.bb.readInt16(vtable_start + field) != 0; // If this fails, the caller will show what field needs to be set. if (!ok) { throw new Error('FlatBuffers: field ' + field + ' must be set'); } }; /** * Start a new array/vector of objects. Users usually will not call * this directly. The FlatBuffers compiler will create a start/end * method for vector types in generated code. * * @param elem_size The size of each element in the array * @param num_elems The number of elements in the array * @param alignment The alignment of the array */ Builder.prototype.startVector = function (elem_size, num_elems, alignment) { this.notNested(); this.vector_num_elems = num_elems; this.prep(constants_js_1.SIZEOF_INT, elem_size * num_elems); this.prep(alignment, elem_size * num_elems); // Just in case alignment > int. }; /** * Finish off the creation of an array and all its elements. The array must be * created with `startVector`. * * @returns The offset at which the newly created array * starts. */ Builder.prototype.endVector = function () { this.writeInt32(this.vector_num_elems); return this.offset(); }; /** * Encode the string `s` in the buffer using UTF-8. If the string passed has * already been seen, we return the offset of the already written string * * @param s The string to encode * @return The offset in the buffer where the encoded string starts */ Builder.prototype.createSharedString = function (s) { if (!s) { return 0; } if (!this.string_maps) { this.string_maps = new Map(); } if (this.string_maps.has(s)) { return this.string_maps.get(s); } var offset = this.createString(s); this.string_maps.set(s, offset); return offset; }; /** * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed * instead of a string, it is assumed to contain valid UTF-8 encoded data. * * @param s The string to encode * @return The offset in the buffer where the encoded string starts */ Builder.prototype.createString = function (s) { if (s === null || s === undefined) { return 0; } var utf8; if (s instanceof Uint8Array) { utf8 = s; } else { utf8 = []; var i = 0; while (i < s.length) { var codePoint = void 0; // Decode UTF-16 var a = s.charCodeAt(i++); if (a < 0xD800 || a >= 0xDC00) { codePoint = a; } else { var b = s.charCodeAt(i++); codePoint = (a << 10) + b + (0x10000 - (0xD800 << 10) - 0xDC00); } // Encode UTF-8 if (codePoint < 0x80) { utf8.push(codePoint); } else { if (codePoint < 0x800) { utf8.push(((codePoint >> 6) & 0x1F) | 0xC0); } else { if (codePoint < 0x10000) { utf8.push(((codePoint >> 12) & 0x0F) | 0xE0); } else { utf8.push(((codePoint >> 18) & 0x07) | 0xF0, ((codePoint >> 12) & 0x3F) | 0x80); } utf8.push(((codePoint >> 6) & 0x3F) | 0x80); } utf8.push((codePoint & 0x3F) | 0x80); } } } this.addInt8(0); this.startVector(1, utf8.length, 1); this.bb.setPosition(this.space -= utf8.length); for (var i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) { bytes[offset++] = utf8[i]; } return this.endVector(); }; /** * A helper function to pack an object * * @returns offset of obj */ Builder.prototype.createObjectOffset = function (obj) { if (obj === null) { return 0; } if (typeof obj === 'string') { return this.createString(obj); } else { return obj.pack(this); } }; /** * A helper function to pack a list of object * * @returns list of offsets of each non null object */ Builder.prototype.createObjectOffsetList = function (list) { var ret = []; for (var i = 0; i < list.length; ++i) { var val = list[i]; if (val !== null) { ret.push(this.createObjectOffset(val)); } else { throw new Error('FlatBuffers: Argument for createObjectOffsetList cannot contain null.'); } } return ret; }; Builder.prototype.createStructOffsetList = function (list, startFunc) { startFunc(this, list.length); this.createObjectOffsetList(list); return this.endVector(); }; return Builder; }()); exports.Builder = Builder; /***/ }), /***/ 505: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ByteBuffer = void 0; var constants_js_1 = __webpack_require__(147); var utils_js_1 = __webpack_require__(766); var encoding_js_1 = __webpack_require__(650); var ByteBuffer = /** @class */ (function () { /** * Create a new ByteBuffer with a given array of bytes (`Uint8Array`) */ function ByteBuffer(bytes_) { this.bytes_ = bytes_; this.position_ = 0; } /** * Create and allocate a new ByteBuffer with a given size. */ ByteBuffer.allocate = function (byte_size) { return new ByteBuffer(new Uint8Array(byte_size)); }; ByteBuffer.prototype.clear = function () { this.position_ = 0; }; /** * Get the underlying `Uint8Array`. */ ByteBuffer.prototype.bytes = function () { return this.bytes_; }; /** * Get the buffer's position. */ ByteBuffer.prototype.position = function () { return this.position_; }; /** * Set the buffer's position. */ ByteBuffer.prototype.setPosition = function (position) { this.position_ = position; }; /** * Get the buffer's capacity. */ ByteBuffer.prototype.capacity = function () { return this.bytes_.length; }; ByteBuffer.prototype.readInt8 = function (offset) { return this.readUint8(offset) << 24 >> 24; }; ByteBuffer.prototype.readUint8 = function (offset) { return this.bytes_[offset]; }; ByteBuffer.prototype.readInt16 = function (offset) { return this.readUint16(offset) << 16 >> 16; }; ByteBuffer.prototype.readUint16 = function (offset) { return this.bytes_[offset] | this.bytes_[offset + 1] << 8; }; ByteBuffer.prototype.readInt32 = function (offset) { return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24; }; ByteBuffer.prototype.readUint32 = function (offset) { return this.readInt32(offset) >>> 0; }; ByteBuffer.prototype.readInt64 = function (offset) { return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32))); }; ByteBuffer.prototype.readUint64 = function (offset) { return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32))); }; ByteBuffer.prototype.readFloat32 = function (offset) { utils_js_1.int32[0] = this.readInt32(offset); return utils_js_1.float32[0]; }; ByteBuffer.prototype.readFloat64 = function (offset) { utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1] = this.readInt32(offset); utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4); return utils_js_1.float64[0]; }; ByteBuffer.prototype.writeInt8 = function (offset, value) { this.bytes_[offset] = value; }; ByteBuffer.prototype.writeUint8 = function (offset, value) { this.bytes_[offset] = value; }; ByteBuffer.prototype.writeInt16 = function (offset, value) { this.bytes_[offset] = value; this.bytes_[offset + 1] = value >> 8; }; ByteBuffer.prototype.writeUint16 = function (offset, value) { this.bytes_[offset] = value; this.bytes_[offset + 1] = value >> 8; }; ByteBuffer.prototype.writeInt32 = function (offset, value) { this.bytes_[offset] = value; this.bytes_[offset + 1] = value >> 8; this.bytes_[offset + 2] = value >> 16; this.bytes_[offset + 3] = value >> 24; }; ByteBuffer.prototype.writeUint32 = function (offset, value) { this.bytes_[offset] = value; this.bytes_[offset + 1] = value >> 8; this.bytes_[offset + 2] = value >> 16; this.bytes_[offset + 3] = value >> 24; }; ByteBuffer.prototype.writeInt64 = function (offset, value) { this.writeInt32(offset, Number(BigInt.asIntN(32, value))); this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32)))); }; ByteBuffer.prototype.writeUint64 = function (offset, value) { this.writeUint32(offset, Number(BigInt.asUintN(32, value))); this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32)))); }; ByteBuffer.prototype.writeFloat32 = function (offset, value) { utils_js_1.float32[0] = value; this.writeInt32(offset, utils_js_1.int32[0]); }; ByteBuffer.prototype.writeFloat64 = function (offset, value) { utils_js_1.float64[0] = value; this.writeInt32(offset, utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1]); this.writeInt32(offset + 4, utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0]); }; /** * Return the file identifier. Behavior is undefined for FlatBuffers whose * schema does not include a file_identifier (likely points at padding or the * start of a the root vtable). */ ByteBuffer.prototype.getBufferIdentifier = function () { if (this.bytes_.length < this.position_ + constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH) { throw new Error('FlatBuffers: ByteBuffer is too short to contain an identifier.'); } var result = ""; for (var i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) { result += String.fromCharCode(this.readInt8(this.position_ + constants_js_1.SIZEOF_INT + i)); } return result; }; /** * Look up a field in the vtable, return an offset into the object, or 0 if the * field is not present. */ ByteBuffer.prototype.__offset = function (bb_pos, vtable_offset) { var vtable = bb_pos - this.readInt32(bb_pos); return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0; }; /** * Initialize any Table-derived type to point to the union at the given offset. */ ByteBuffer.prototype.__union = function (t, offset) { t.bb_pos = offset + this.readInt32(offset); t.bb = this; return t; }; /** * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer. * This allocates a new string and converts to wide chars upon each access. * * To avoid the conversion to UTF-16, pass Encoding.UTF8_BYTES as * the "optionalEncoding" argument. This is useful for avoiding conversion to * and from UTF-16 when the data will just be packaged back up in another * FlatBuffer later on. * * @param offset * @param opt_encoding Defaults to UTF16_STRING */ ByteBuffer.prototype.__string = function (offset, opt_encoding) { offset += this.readInt32(offset); var length = this.readInt32(offset); var result = ''; var i = 0; offset += constants_js_1.SIZEOF_INT; if (opt_encoding === encoding_js_1.Encoding.UTF8_BYTES) { return this.bytes_.subarray(offset, offset + length); } while (i < length) { var codePoint = void 0; // Decode UTF-8 var a = this.readUint8(offset + i++); if (a < 0xC0) { codePoint = a; } else { var b = this.readUint8(offset + i++); if (a < 0xE0) { codePoint = ((a & 0x1F) << 6) | (b & 0x3F); } else { var c = this.readUint8(offset + i++); if (a < 0xF0) { codePoint = ((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F); } else { var d = this.readUint8(offset + i++); codePoint = ((a & 0x07) << 18) | ((b & 0x3F) << 12) | ((c & 0x3F) << 6) | (d & 0x3F); } } } // Encode UTF-16 if (codePoint < 0x10000) { result += String.fromCharCode(codePoint); } else { codePoint -= 0x10000; result += String.fromCharCode((codePoint >> 10) + 0xD800, (codePoint & ((1 << 10) - 1)) + 0xDC00); } } return result; }; /** * Handle unions that can contain string as its member, if a Table-derived type then initialize it, * if a string then return a new one * * WARNING: strings are immutable in JS so we can't change the string that the user gave us, this * makes the behaviour of __union_with_string different compared to __union */ ByteBuffer.prototype.__union_with_string = function (o, offset) { if (typeof o === 'string') { return this.__string(offset); } return this.__union(o, offset); }; /** * Retrieve the relative offset stored at "offset" */ ByteBuffer.prototype.__indirect = function (offset) { return offset + this.readInt32(offset); }; /** * Get the start of data of a vector whose offset is stored at "offset" in this object. */ ByteBuffer.prototype.__vector = function (offset) { return offset + this.readInt32(offset) + constants_js_1.SIZEOF_INT; // data starts after the length }; /** * Get the length of a vector whose offset is stored at "offset" in this object. */ ByteBuffer.prototype.__vector_len = function (offset) { return this.readInt32(offset + this.readInt32(offset)); }; ByteBuffer.prototype.__has_identifier = function (ident) { if (ident.length != constants_js_1.FILE_IDENTIFIER_LENGTH) { throw new Error('FlatBuffers: file identifier must be length ' + constants_js_1.FILE_IDENTIFIER_LENGTH); } for (var i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) { if (ident.charCodeAt(i) != this.readInt8(this.position() + constants_js_1.SIZEOF_INT + i)) { return false; } } return true; }; /** * A helper function for generating list for obj api */ ByteBuffer.prototype.createScalarList = function (listAccessor, listLength) { var ret = []; for (var i = 0; i < listLength; ++i) { if (listAccessor(i) !== null) { ret.push(listAccessor(i)); } } return ret; }; /** * A helper function for generating list for obj api * @param listAccessor function that accepts an index and return data at that index * @param listLength listLength * @param res result list */ ByteBuffer.prototype.createObjList = function (listAccessor, listLength) { var ret = []; for (var i = 0; i < listLength; ++i) { var val = listAccessor(i); if (val !== null) { ret.push(val.unpack()); } } return ret; }; return ByteBuffer; }()); exports.ByteBuffer = ByteBuffer; /***/ }), /***/ 147: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SIZE_PREFIX_LENGTH = exports.FILE_IDENTIFIER_LENGTH = exports.SIZEOF_INT = exports.SIZEOF_SHORT = void 0; exports.SIZEOF_SHORT = 2; exports.SIZEOF_INT = 4; exports.FILE_IDENTIFIER_LENGTH = 4; exports.SIZE_PREFIX_LENGTH = 4; /***/ }), /***/ 650: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Encoding = void 0; var Encoding; (function (Encoding) { Encoding[Encoding["UTF8_BYTES"] = 1] = "UTF8_BYTES"; Encoding[Encoding["UTF16_STRING"] = 2] = "UTF16_STRING"; })(Encoding = exports.Encoding || (exports.Encoding = {})); /***/ }), /***/ 903: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.cZ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = exports.XU = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = void 0; var constants_js_1 = __webpack_require__(147); __webpack_unused_export__ = ({ enumerable: true, get: function () { return constants_js_1.SIZEOF_SHORT; } }); var constants_js_2 = __webpack_require__(147); __webpack_unused_export__ = ({ enumerable: true, get: function () { return constants_js_2.SIZEOF_INT; } }); var constants_js_3 = __webpack_require__(147); __webpack_unused_export__ = ({ enumerable: true, get: function () { return constants_js_3.FILE_IDENTIFIER_LENGTH; } }); var constants_js_4 = __webpack_require__(147); Object.defineProperty(exports, "XU", ({ enumerable: true, get: function () { return constants_js_4.SIZE_PREFIX_LENGTH; } })); var utils_js_1 = __webpack_require__(766); __webpack_unused_export__ = ({ enumerable: true, get: function () { return utils_js_1.int32; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return utils_js_1.float32; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return utils_js_1.float64; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return utils_js_1.isLittleEndian; } }); var encoding_js_1 = __webpack_require__(650); __webpack_unused_export__ = ({ enumerable: true, get: function () { return encoding_js_1.Encoding; } }); var builder_js_1 = __webpack_require__(962); __webpack_unused_export__ = ({ enumerable: true, get: function () { return builder_js_1.Builder; } }); var byte_buffer_js_1 = __webpack_require__(505); Object.defineProperty(exports, "cZ", ({ enumerable: true, get: function () { return byte_buffer_js_1.ByteBuffer; } })); /***/ }), /***/ 766: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isLittleEndian = exports.float64 = exports.float32 = exports.int32 = void 0; exports.int32 = new Int32Array(2); exports.float32 = new Float32Array(exports.int32.buffer); exports.float64 = new Float64Array(exports.int32.buffer); exports.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1; /***/ }), /***/ 478: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array ? array.length : 0; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array ? array.length : 0, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { if (value !== value) { return baseFindIndex(array, baseIsNaN, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * Checks if a cache value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Symbol = root.Symbol, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'), nativeCreate = getNative(Object, 'create'); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values ? values.length : 0; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = array; return apply(func, this, otherArgs); }; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order of result values is determined by the * order they occur in the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = difference; /***/ }), /***/ 794: /***/ ((module, exports, __webpack_require__) => { /* module decorator */ module = __webpack_require__.nmd(module); /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', promiseTag = '[object Promise]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values ? values.length : 0; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { this.__data__ = new ListCache(entries); } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { return this.__data__['delete'](key); } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var cache = this.__data__; if (cache instanceof ListCache) { var pairs = cache.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); return this; } cache = this.__data__ = new MapCache(pairs); } cache.set(key, value); return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. // Safari 9 makes `arguments.length` enumerable in strict mode. var result = (isArray(value) || isArguments(value)) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) { result.push(key); } } return result; } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = isKey(path, object) ? [path] : castPath(path); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getTag`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { return objectToString.call(value); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @param {boolean} [bitmask] The bitmask of comparison flags. * The bitmask may be composed of the following flags: * 1 - Unordered comparison * 2 - Partial comparison * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, bitmask, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparisons. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); } if (!(bitmask & PARTIAL_COMPARE_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, equalFunc, customizer, bitmask, stack); } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else if (!isKey(index, array)) { var path = castPath(index), object = parent(array, path); if (object != null) { delete object[toKey(last(path))]; } } else { delete array[toKey(index)]; } } } return array; } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the cast property path array. */ function castPath(value) { return isArray(value) ? value : stringToPath(value); } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { return seen.add(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & PARTIAL_COMPARE_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= UNORDERED_COMPARE_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11, // for data views in Edge < 14, and promises in Node.js. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = isKey(path, object) ? [path] : castPath(path); var result, index = -1, length = path.length; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result) { return result; } var length = object ? object.length : 0; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoize(function(string) { string = toString(string); var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = baseIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Assign cache to `_.memoize`. memoize.Cache = MapCache; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = remove; /***/ }), /***/ 52: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array ? array.length : 0, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. // Safari 9 makes `arguments.length` enumerable in strict mode. var result = (isArray(value) || isArguments(value)) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) { result.push(key); } } return result; } /** * The base implementation of `getTag`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { return objectToString.call(value); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11, // for data views in Edge < 14, and promises in Node.js. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); module.exports = toPairs; /***/ }), /***/ 785: /***/ (function(module) { (function (global, factory) { true ? module.exports = factory() : 0; }(this, (function () { 'use strict'; var globals = function(defs) { defs('EPSG:4326', "+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees"); defs('EPSG:4269', "+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees"); defs('EPSG:3857', "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"); defs.WGS84 = defs['EPSG:4326']; defs['EPSG:3785'] = defs['EPSG:3857']; // maintain backward compat, official code is 3857 defs.GOOGLE = defs['EPSG:3857']; defs['EPSG:900913'] = defs['EPSG:3857']; defs['EPSG:102113'] = defs['EPSG:3857']; }; var PJD_3PARAM = 1; var PJD_7PARAM = 2; var PJD_GRIDSHIFT = 3; var PJD_WGS84 = 4; // WGS84 or equivalent var PJD_NODATUM = 5; // WGS84 or equivalent var SRS_WGS84_SEMIMAJOR = 6378137.0; // only used in grid shift transforms var SRS_WGS84_SEMIMINOR = 6356752.314; // only used in grid shift transforms var SRS_WGS84_ESQUARED = 0.0066943799901413165; // only used in grid shift transforms var SEC_TO_RAD = 4.84813681109535993589914102357e-6; var HALF_PI = Math.PI/2; // ellipoid pj_set_ell.c var SIXTH = 0.1666666666666666667; /* 1/6 */ var RA4 = 0.04722222222222222222; /* 17/360 */ var RA6 = 0.02215608465608465608; var EPSLN = 1.0e-10; // you'd think you could use Number.EPSILON above but that makes // Mollweide get into an infinate loop. var D2R = 0.01745329251994329577; var R2D = 57.29577951308232088; var FORTPI = Math.PI/4; var TWO_PI = Math.PI * 2; // SPI is slightly greater than Math.PI, so values that exceed the -180..180 // degree range by a tiny amount don't get wrapped. This prevents points that // have drifted from their original location along the 180th meridian (due to // floating point error) from changing their sign. var SPI = 3.14159265359; var exports$1 = {}; exports$1.greenwich = 0.0; //"0dE", exports$1.lisbon = -9.131906111111; //"9d07'54.862\"W", exports$1.paris = 2.337229166667; //"2d20'14.025\"E", exports$1.bogota = -74.080916666667; //"74d04'51.3\"W", exports$1.madrid = -3.687938888889; //"3d41'16.58\"W", exports$1.rome = 12.452333333333; //"12d27'8.4\"E", exports$1.bern = 7.439583333333; //"7d26'22.5\"E", exports$1.jakarta = 106.807719444444; //"106d48'27.79\"E", exports$1.ferro = -17.666666666667; //"17d40'W", exports$1.brussels = 4.367975; //"4d22'4.71\"E", exports$1.stockholm = 18.058277777778; //"18d3'29.8\"E", exports$1.athens = 23.7163375; //"23d42'58.815\"E", exports$1.oslo = 10.722916666667; //"10d43'22.5\"E" var units = { ft: {to_meter: 0.3048}, 'us-ft': {to_meter: 1200 / 3937} }; var ignoredChar = /[\s_\-\/\(\)]/g; function match(obj, key) { if (obj[key]) { return obj[key]; } var keys = Object.keys(obj); var lkey = key.toLowerCase().replace(ignoredChar, ''); var i = -1; var testkey, processedKey; while (++i < keys.length) { testkey = keys[i]; processedKey = testkey.toLowerCase().replace(ignoredChar, ''); if (processedKey === lkey) { return obj[testkey]; } } } var parseProj = function(defData) { var self = {}; var paramObj = defData.split('+').map(function(v) { return v.trim(); }).filter(function(a) { return a; }).reduce(function(p, a) { var split = a.split('='); split.push(true); p[split[0].toLowerCase()] = split[1]; return p; }, {}); var paramName, paramVal, paramOutname; var params = { proj: 'projName', datum: 'datumCode', rf: function(v) { self.rf = parseFloat(v); }, lat_0: function(v) { self.lat0 = v * D2R; }, lat_1: function(v) { self.lat1 = v * D2R; }, lat_2: function(v) { self.lat2 = v * D2R; }, lat_ts: function(v) { self.lat_ts = v * D2R; }, lon_0: function(v) { self.long0 = v * D2R; }, lon_1: function(v) { self.long1 = v * D2R; }, lon_2: function(v) { self.long2 = v * D2R; }, alpha: function(v) { self.alpha = parseFloat(v) * D2R; }, gamma: function(v) { self.rectified_grid_angle = parseFloat(v); }, lonc: function(v) { self.longc = v * D2R; }, x_0: function(v) { self.x0 = parseFloat(v); }, y_0: function(v) { self.y0 = parseFloat(v); }, k_0: function(v) { self.k0 = parseFloat(v); }, k: function(v) { self.k0 = parseFloat(v); }, a: function(v) { self.a = parseFloat(v); }, b: function(v) { self.b = parseFloat(v); }, r_a: function() { self.R_A = true; }, zone: function(v) { self.zone = parseInt(v, 10); }, south: function() { self.utmSouth = true; }, towgs84: function(v) { self.datum_params = v.split(",").map(function(a) { return parseFloat(a); }); }, to_meter: function(v) { self.to_meter = parseFloat(v); }, units: function(v) { self.units = v; var unit = match(units, v); if (unit) { self.to_meter = unit.to_meter; } }, from_greenwich: function(v) { self.from_greenwich = v * D2R; }, pm: function(v) { var pm = match(exports$1, v); self.from_greenwich = (pm ? pm : parseFloat(v)) * D2R; }, nadgrids: function(v) { if (v === '@null') { self.datumCode = 'none'; } else { self.nadgrids = v; } }, axis: function(v) { var legalAxis = "ewnsud"; if (v.length === 3 && legalAxis.indexOf(v.substr(0, 1)) !== -1 && legalAxis.indexOf(v.substr(1, 1)) !== -1 && legalAxis.indexOf(v.substr(2, 1)) !== -1) { self.axis = v; } }, approx: function() { self.approx = true; } }; for (paramName in paramObj) { paramVal = paramObj[paramName]; if (paramName in params) { paramOutname = params[paramName]; if (typeof paramOutname === 'function') { paramOutname(paramVal); } else { self[paramOutname] = paramVal; } } else { self[paramName] = paramVal; } } if(typeof self.datumCode === 'string' && self.datumCode !== "WGS84"){ self.datumCode = self.datumCode.toLowerCase(); } return self; }; var NEUTRAL = 1; var KEYWORD = 2; var NUMBER = 3; var QUOTED = 4; var AFTERQUOTE = 5; var ENDED = -1; var whitespace = /\s/; var latin = /[A-Za-z]/; var keyword = /[A-Za-z84_]/; var endThings = /[,\]]/; var digets = /[\d\.E\-\+]/; // const ignoredChar = /[\s_\-\/\(\)]/g; function Parser(text) { if (typeof text !== 'string') { throw new Error('not a string'); } this.text = text.trim(); this.level = 0; this.place = 0; this.root = null; this.stack = []; this.currentObject = null; this.state = NEUTRAL; } Parser.prototype.readCharicter = function() { var char = this.text[this.place++]; if (this.state !== QUOTED) { while (whitespace.test(char)) { if (this.place >= this.text.length) { return; } char = this.text[this.place++]; } } switch (this.state) { case NEUTRAL: return this.neutral(char); case KEYWORD: return this.keyword(char) case QUOTED: return this.quoted(char); case AFTERQUOTE: return this.afterquote(char); case NUMBER: return this.number(char); case ENDED: return; } }; Parser.prototype.afterquote = function(char) { if (char === '"') { this.word += '"'; this.state = QUOTED; return; } if (endThings.test(char)) { this.word = this.word.trim(); this.afterItem(char); return; } throw new Error('havn\'t handled "' +char + '" in afterquote yet, index ' + this.place); }; Parser.prototype.afterItem = function(char) { if (char === ',') { if (this.word !== null) { this.currentObject.push(this.word); } this.word = null; this.state = NEUTRAL; return; } if (char === ']') { this.level--; if (this.word !== null) { this.currentObject.push(this.word); this.word = null; } this.state = NEUTRAL; this.currentObject = this.stack.pop(); if (!this.currentObject) { this.state = ENDED; } return; } }; Parser.prototype.number = function(char) { if (digets.test(char)) { this.word += char; return; } if (endThings.test(char)) { this.word = parseFloat(this.word); this.afterItem(char); return; } throw new Error('havn\'t handled "' +char + '" in number yet, index ' + this.place); }; Parser.prototype.quoted = function(char) { if (char === '"') { this.state = AFTERQUOTE; return; } this.word += char; return; }; Parser.prototype.keyword = function(char) { if (keyword.test(char)) { this.word += char; return; } if (char === '[') { var newObjects = []; newObjects.push(this.word); this.level++; if (this.root === null) { this.root = newObjects; } else { this.currentObject.push(newObjects); } this.stack.push(this.currentObject); this.currentObject = newObjects; this.state = NEUTRAL; return; } if (endThings.test(char)) { this.afterItem(char); return; } throw new Error('havn\'t handled "' +char + '" in keyword yet, index ' + this.place); }; Parser.prototype.neutral = function(char) { if (latin.test(char)) { this.word = char; this.state = KEYWORD; return; } if (char === '"') { this.word = ''; this.state = QUOTED; return; } if (digets.test(char)) { this.word = char; this.state = NUMBER; return; } if (endThings.test(char)) { this.afterItem(char); return; } throw new Error('havn\'t handled "' +char + '" in neutral yet, index ' + this.place); }; Parser.prototype.output = function() { while (this.place < this.text.length) { this.readCharicter(); } if (this.state === ENDED) { return this.root; } throw new Error('unable to parse string "' +this.text + '". State is ' + this.state); }; function parseString(txt) { var parser = new Parser(txt); return parser.output(); } function mapit(obj, key, value) { if (Array.isArray(key)) { value.unshift(key); key = null; } var thing = key ? {} : obj; var out = value.reduce(function(newObj, item) { sExpr(item, newObj); return newObj }, thing); if (key) { obj[key] = out; } } function sExpr(v, obj) { if (!Array.isArray(v)) { obj[v] = true; return; } var key = v.shift(); if (key === 'PARAMETER') { key = v.shift(); } if (v.length === 1) { if (Array.isArray(v[0])) { obj[key] = {}; sExpr(v[0], obj[key]); return; } obj[key] = v[0]; return; } if (!v.length) { obj[key] = true; return; } if (key === 'TOWGS84') { obj[key] = v; return; } if (key === 'AXIS') { if (!(key in obj)) { obj[key] = []; } obj[key].push(v); return; } if (!Array.isArray(key)) { obj[key] = {}; } var i; switch (key) { case 'UNIT': case 'PRIMEM': case 'VERT_DATUM': obj[key] = { name: v[0].toLowerCase(), convert: v[1] }; if (v.length === 3) { sExpr(v[2], obj[key]); } return; case 'SPHEROID': case 'ELLIPSOID': obj[key] = { name: v[0], a: v[1], rf: v[2] }; if (v.length === 4) { sExpr(v[3], obj[key]); } return; case 'PROJECTEDCRS': case 'PROJCRS': case 'GEOGCS': case 'GEOCCS': case 'PROJCS': case 'LOCAL_CS': case 'GEODCRS': case 'GEODETICCRS': case 'GEODETICDATUM': case 'EDATUM': case 'ENGINEERINGDATUM': case 'VERT_CS': case 'VERTCRS': case 'VERTICALCRS': case 'COMPD_CS': case 'COMPOUNDCRS': case 'ENGINEERINGCRS': case 'ENGCRS': case 'FITTED_CS': case 'LOCAL_DATUM': case 'DATUM': v[0] = ['name', v[0]]; mapit(obj, key, v); return; default: i = -1; while (++i < v.length) { if (!Array.isArray(v[i])) { return sExpr(v, obj[key]); } } return mapit(obj, key, v); } } var D2R$1 = 0.01745329251994329577; function rename(obj, params) { var outName = params[0]; var inName = params[1]; if (!(outName in obj) && (inName in obj)) { obj[outName] = obj[inName]; if (params.length === 3) { obj[outName] = params[2](obj[outName]); } } } function d2r(input) { return input * D2R$1; } function cleanWKT(wkt) { if (wkt.type === 'GEOGCS') { wkt.projName = 'longlat'; } else if (wkt.type === 'LOCAL_CS') { wkt.projName = 'identity'; wkt.local = true; } else { if (typeof wkt.PROJECTION === 'object') { wkt.projName = Object.keys(wkt.PROJECTION)[0]; } else { wkt.projName = wkt.PROJECTION; } } if (wkt.AXIS) { var axisOrder = ''; for (var i = 0, ii = wkt.AXIS.length; i < ii; ++i) { var axis = [wkt.AXIS[i][0].toLowerCase(), wkt.AXIS[i][1].toLowerCase()]; if (axis[0].indexOf('north') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'north')) { axisOrder += 'n'; } else if (axis[0].indexOf('south') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'south')) { axisOrder += 's'; } else if (axis[0].indexOf('east') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'east')) { axisOrder += 'e'; } else if (axis[0].indexOf('west') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'west')) { axisOrder += 'w'; } } if (axisOrder.length === 2) { axisOrder += 'u'; } if (axisOrder.length === 3) { wkt.axis = axisOrder; } } if (wkt.UNIT) { wkt.units = wkt.UNIT.name.toLowerCase(); if (wkt.units === 'metre') { wkt.units = 'meter'; } if (wkt.UNIT.convert) { if (wkt.type === 'GEOGCS') { if (wkt.DATUM && wkt.DATUM.SPHEROID) { wkt.to_meter = wkt.UNIT.convert*wkt.DATUM.SPHEROID.a; } } else { wkt.to_meter = wkt.UNIT.convert; } } } var geogcs = wkt.GEOGCS; if (wkt.type === 'GEOGCS') { geogcs = wkt; } if (geogcs) { //if(wkt.GEOGCS.PRIMEM&&wkt.GEOGCS.PRIMEM.convert){ // wkt.from_greenwich=wkt.GEOGCS.PRIMEM.convert*D2R; //} if (geogcs.DATUM) { wkt.datumCode = geogcs.DATUM.name.toLowerCase(); } else { wkt.datumCode = geogcs.name.toLowerCase(); } if (wkt.datumCode.slice(0, 2) === 'd_') { wkt.datumCode = wkt.datumCode.slice(2); } if (wkt.datumCode === 'new_zealand_geodetic_datum_1949' || wkt.datumCode === 'new_zealand_1949') { wkt.datumCode = 'nzgd49'; } if (wkt.datumCode === 'wgs_1984' || wkt.datumCode === 'world_geodetic_system_1984') { if (wkt.PROJECTION === 'Mercator_Auxiliary_Sphere') { wkt.sphere = true; } wkt.datumCode = 'wgs84'; } if (wkt.datumCode.slice(-6) === '_ferro') { wkt.datumCode = wkt.datumCode.slice(0, - 6); } if (wkt.datumCode.slice(-8) === '_jakarta') { wkt.datumCode = wkt.datumCode.slice(0, - 8); } if (~wkt.datumCode.indexOf('belge')) { wkt.datumCode = 'rnb72'; } if (geogcs.DATUM && geogcs.DATUM.SPHEROID) { wkt.ellps = geogcs.DATUM.SPHEROID.name.replace('_19', '').replace(/[Cc]larke\_18/, 'clrk'); if (wkt.ellps.toLowerCase().slice(0, 13) === 'international') { wkt.ellps = 'intl'; } wkt.a = geogcs.DATUM.SPHEROID.a; wkt.rf = parseFloat(geogcs.DATUM.SPHEROID.rf, 10); } if (geogcs.DATUM && geogcs.DATUM.TOWGS84) { wkt.datum_params = geogcs.DATUM.TOWGS84; } if (~wkt.datumCode.indexOf('osgb_1936')) { wkt.datumCode = 'osgb36'; } if (~wkt.datumCode.indexOf('osni_1952')) { wkt.datumCode = 'osni52'; } if (~wkt.datumCode.indexOf('tm65') || ~wkt.datumCode.indexOf('geodetic_datum_of_1965')) { wkt.datumCode = 'ire65'; } if (wkt.datumCode === 'ch1903+') { wkt.datumCode = 'ch1903'; } if (~wkt.datumCode.indexOf('israel')) { wkt.datumCode = 'isr93'; } } if (wkt.b && !isFinite(wkt.b)) { wkt.b = wkt.a; } function toMeter(input) { var ratio = wkt.to_meter || 1; return input * ratio; } var renamer = function(a) { return rename(wkt, a); }; var list = [ ['standard_parallel_1', 'Standard_Parallel_1'], ['standard_parallel_1', 'Latitude of 1st standard parallel'], ['standard_parallel_2', 'Standard_Parallel_2'], ['standard_parallel_2', 'Latitude of 2nd standard parallel'], ['false_easting', 'False_Easting'], ['false_easting', 'False easting'], ['false-easting', 'Easting at false origin'], ['false_northing', 'False_Northing'], ['false_northing', 'False northing'], ['false_northing', 'Northing at false origin'], ['central_meridian', 'Central_Meridian'], ['central_meridian', 'Longitude of natural origin'], ['central_meridian', 'Longitude of false origin'], ['latitude_of_origin', 'Latitude_Of_Origin'], ['latitude_of_origin', 'Central_Parallel'], ['latitude_of_origin', 'Latitude of natural origin'], ['latitude_of_origin', 'Latitude of false origin'], ['scale_factor', 'Scale_Factor'], ['k0', 'scale_factor'], ['latitude_of_center', 'Latitude_Of_Center'], ['latitude_of_center', 'Latitude_of_center'], ['lat0', 'latitude_of_center', d2r], ['longitude_of_center', 'Longitude_Of_Center'], ['longitude_of_center', 'Longitude_of_center'], ['longc', 'longitude_of_center', d2r], ['x0', 'false_easting', toMeter], ['y0', 'false_northing', toMeter], ['long0', 'central_meridian', d2r], ['lat0', 'latitude_of_origin', d2r], ['lat0', 'standard_parallel_1', d2r], ['lat1', 'standard_parallel_1', d2r], ['lat2', 'standard_parallel_2', d2r], ['azimuth', 'Azimuth'], ['alpha', 'azimuth', d2r], ['srsCode', 'name'] ]; list.forEach(renamer); if (!wkt.long0 && wkt.longc && (wkt.projName === 'Albers_Conic_Equal_Area' || wkt.projName === 'Lambert_Azimuthal_Equal_Area')) { wkt.long0 = wkt.longc; } if (!wkt.lat_ts && wkt.lat1 && (wkt.projName === 'Stereographic_South_Pole' || wkt.projName === 'Polar Stereographic (variant B)')) { wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90); wkt.lat_ts = wkt.lat1; } } var wkt = function(wkt) { var lisp = parseString(wkt); var type = lisp.shift(); var name = lisp.shift(); lisp.unshift(['name', name]); lisp.unshift(['type', type]); var obj = {}; sExpr(lisp, obj); cleanWKT(obj); return obj; }; function defs(name) { /*global console*/ var that = this; if (arguments.length === 2) { var def = arguments[1]; if (typeof def === 'string') { if (def.charAt(0) === '+') { defs[name] = parseProj(arguments[1]); } else { defs[name] = wkt(arguments[1]); } } else { defs[name] = def; } } else if (arguments.length === 1) { if (Array.isArray(name)) { return name.map(function(v) { if (Array.isArray(v)) { defs.apply(that, v); } else { defs(v); } }); } else if (typeof name === 'string') { if (name in defs) { return defs[name]; } } else if ('EPSG' in name) { defs['EPSG:' + name.EPSG] = name; } else if ('ESRI' in name) { defs['ESRI:' + name.ESRI] = name; } else if ('IAU2000' in name) { defs['IAU2000:' + name.IAU2000] = name; } else { console.log(name); } return; } } globals(defs); function testObj(code){ return typeof code === 'string'; } function testDef(code){ return code in defs; } var codeWords = ['PROJECTEDCRS', 'PROJCRS', 'GEOGCS','GEOCCS','PROJCS','LOCAL_CS', 'GEODCRS', 'GEODETICCRS', 'GEODETICDATUM', 'ENGCRS', 'ENGINEERINGCRS']; function testWKT(code){ return codeWords.some(function (word) { return code.indexOf(word) > -1; }); } var codes = ['3857', '900913', '3785', '102113']; function checkMercator(item) { var auth = match(item, 'authority'); if (!auth) { return; } var code = match(auth, 'epsg'); return code && codes.indexOf(code) > -1; } function checkProjStr(item) { var ext = match(item, 'extension'); if (!ext) { return; } return match(ext, 'proj4'); } function testProj(code){ return code[0] === '+'; } function parse(code){ if (testObj(code)) { //check to see if this is a WKT string if (testDef(code)) { return defs[code]; } if (testWKT(code)) { var out = wkt(code); // test of spetial case, due to this being a very common and often malformed if (checkMercator(out)) { return defs['EPSG:3857']; } var maybeProjStr = checkProjStr(out); if (maybeProjStr) { return parseProj(maybeProjStr); } return out; } if (testProj(code)) { return parseProj(code); } }else{ return code; } } var extend = function(destination, source) { destination = destination || {}; var value, property; if (!source) { return destination; } for (property in source) { value = source[property]; if (value !== undefined) { destination[property] = value; } } return destination; }; var msfnz = function(eccent, sinphi, cosphi) { var con = eccent * sinphi; return cosphi / (Math.sqrt(1 - con * con)); }; var sign = function(x) { return x<0 ? -1 : 1; }; var adjust_lon = function(x) { return (Math.abs(x) <= SPI) ? x : (x - (sign(x) * TWO_PI)); }; var tsfnz = function(eccent, phi, sinphi) { var con = eccent * sinphi; var com = 0.5 * eccent; con = Math.pow(((1 - con) / (1 + con)), com); return (Math.tan(0.5 * (HALF_PI - phi)) / con); }; var phi2z = function(eccent, ts) { var eccnth = 0.5 * eccent; var con, dphi; var phi = HALF_PI - 2 * Math.atan(ts); for (var i = 0; i <= 15; i++) { con = eccent * Math.sin(phi); dphi = HALF_PI - 2 * Math.atan(ts * (Math.pow(((1 - con) / (1 + con)), eccnth))) - phi; phi += dphi; if (Math.abs(dphi) <= 0.0000000001) { return phi; } } //console.log("phi2z has NoConvergence"); return -9999; }; function init() { var con = this.b / this.a; this.es = 1 - con * con; if(!('x0' in this)){ this.x0 = 0; } if(!('y0' in this)){ this.y0 = 0; } this.e = Math.sqrt(this.es); if (this.lat_ts) { if (this.sphere) { this.k0 = Math.cos(this.lat_ts); } else { this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts)); } } else { if (!this.k0) { if (this.k) { this.k0 = this.k; } else { this.k0 = 1; } } } } /* Mercator forward equations--mapping lat,long to x,y --------------------------------------------------*/ function forward(p) { var lon = p.x; var lat = p.y; // convert to radians if (lat * R2D > 90 && lat * R2D < -90 && lon * R2D > 180 && lon * R2D < -180) { return null; } var x, y; if (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN) { return null; } else { if (this.sphere) { x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0); y = this.y0 + this.a * this.k0 * Math.log(Math.tan(FORTPI + 0.5 * lat)); } else { var sinphi = Math.sin(lat); var ts = tsfnz(this.e, lat, sinphi); x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0); y = this.y0 - this.a * this.k0 * Math.log(ts); } p.x = x; p.y = y; return p; } } /* Mercator inverse equations--mapping x,y to lat/long --------------------------------------------------*/ function inverse(p) { var x = p.x - this.x0; var y = p.y - this.y0; var lon, lat; if (this.sphere) { lat = HALF_PI - 2 * Math.atan(Math.exp(-y / (this.a * this.k0))); } else { var ts = Math.exp(-y / (this.a * this.k0)); lat = phi2z(this.e, ts); if (lat === -9999) { return null; } } lon = adjust_lon(this.long0 + x / (this.a * this.k0)); p.x = lon; p.y = lat; return p; } var names$1 = ["Mercator", "Popular Visualisation Pseudo Mercator", "Mercator_1SP", "Mercator_Auxiliary_Sphere", "merc"]; var merc = { init: init, forward: forward, inverse: inverse, names: names$1 }; function init$1() { //no-op for longlat } function identity(pt) { return pt; } var names$2 = ["longlat", "identity"]; var longlat = { init: init$1, forward: identity, inverse: identity, names: names$2 }; var projs = [merc, longlat]; var names = {}; var projStore = []; function add(proj, i) { var len = projStore.length; if (!proj.names) { console.log(i); return true; } projStore[len] = proj; proj.names.forEach(function(n) { names[n.toLowerCase()] = len; }); return this; } function get(name) { if (!name) { return false; } var n = name.toLowerCase(); if (typeof names[n] !== 'undefined' && projStore[names[n]]) { return projStore[names[n]]; } } function start() { projs.forEach(add); } var projections = { start: start, add: add, get: get }; var exports$2 = {}; exports$2.MERIT = { a: 6378137.0, rf: 298.257, ellipseName: "MERIT 1983" }; exports$2.SGS85 = { a: 6378136.0, rf: 298.257, ellipseName: "Soviet Geodetic System 85" }; exports$2.GRS80 = { a: 6378137.0, rf: 298.257222101, ellipseName: "GRS 1980(IUGG, 1980)" }; exports$2.IAU76 = { a: 6378140.0, rf: 298.257, ellipseName: "IAU 1976" }; exports$2.airy = { a: 6377563.396, b: 6356256.910, ellipseName: "Airy 1830" }; exports$2.APL4 = { a: 6378137, rf: 298.25, ellipseName: "Appl. Physics. 1965" }; exports$2.NWL9D = { a: 6378145.0, rf: 298.25, ellipseName: "Naval Weapons Lab., 1965" }; exports$2.mod_airy = { a: 6377340.189, b: 6356034.446, ellipseName: "Modified Airy" }; exports$2.andrae = { a: 6377104.43, rf: 300.0, ellipseName: "Andrae 1876 (Den., Iclnd.)" }; exports$2.aust_SA = { a: 6378160.0, rf: 298.25, ellipseName: "Australian Natl & S. Amer. 1969" }; exports$2.GRS67 = { a: 6378160.0, rf: 298.2471674270, ellipseName: "GRS 67(IUGG 1967)" }; exports$2.bessel = { a: 6377397.155, rf: 299.1528128, ellipseName: "Bessel 1841" }; exports$2.bess_nam = { a: 6377483.865, rf: 299.1528128, ellipseName: "Bessel 1841 (Namibia)" }; exports$2.clrk66 = { a: 6378206.4, b: 6356583.8, ellipseName: "Clarke 1866" }; exports$2.clrk80 = { a: 6378249.145, rf: 293.4663, ellipseName: "Clarke 1880 mod." }; exports$2.clrk80ign = { a: 6378249.2, b: 6356515, rf: 293.4660213, ellipseName: "Clarke 1880 (IGN)" }; exports$2.clrk58 = { a: 6378293.645208759, rf: 294.2606763692654, ellipseName: "Clarke 1858" }; exports$2.CPM = { a: 6375738.7, rf: 334.29, ellipseName: "Comm. des Poids et Mesures 1799" }; exports$2.delmbr = { a: 6376428.0, rf: 311.5, ellipseName: "Delambre 1810 (Belgium)" }; exports$2.engelis = { a: 6378136.05, rf: 298.2566, ellipseName: "Engelis 1985" }; exports$2.evrst30 = { a: 6377276.345, rf: 300.8017, ellipseName: "Everest 1830" }; exports$2.evrst48 = { a: 6377304.063, rf: 300.8017, ellipseName: "Everest 1948" }; exports$2.evrst56 = { a: 6377301.243, rf: 300.8017, ellipseName: "Everest 1956" }; exports$2.evrst69 = { a: 6377295.664, rf: 300.8017, ellipseName: "Everest 1969" }; exports$2.evrstSS = { a: 6377298.556, rf: 300.8017, ellipseName: "Everest (Sabah & Sarawak)" }; exports$2.fschr60 = { a: 6378166.0, rf: 298.3, ellipseName: "Fischer (Mercury Datum) 1960" }; exports$2.fschr60m = { a: 6378155.0, rf: 298.3, ellipseName: "Fischer 1960" }; exports$2.fschr68 = { a: 6378150.0, rf: 298.3, ellipseName: "Fischer 1968" }; exports$2.helmert = { a: 6378200.0, rf: 298.3, ellipseName: "Helmert 1906" }; exports$2.hough = { a: 6378270.0, rf: 297.0, ellipseName: "Hough" }; exports$2.intl = { a: 6378388.0, rf: 297.0, ellipseName: "International 1909 (Hayford)" }; exports$2.kaula = { a: 6378163.0, rf: 298.24, ellipseName: "Kaula 1961" }; exports$2.lerch = { a: 6378139.0, rf: 298.257, ellipseName: "Lerch 1979" }; exports$2.mprts = { a: 6397300.0, rf: 191.0, ellipseName: "Maupertius 1738" }; exports$2.new_intl = { a: 6378157.5, b: 6356772.2, ellipseName: "New International 1967" }; exports$2.plessis = { a: 6376523.0, rf: 6355863.0, ellipseName: "Plessis 1817 (France)" }; exports$2.krass = { a: 6378245.0, rf: 298.3, ellipseName: "Krassovsky, 1942" }; exports$2.SEasia = { a: 6378155.0, b: 6356773.3205, ellipseName: "Southeast Asia" }; exports$2.walbeck = { a: 6376896.0, b: 6355834.8467, ellipseName: "Walbeck" }; exports$2.WGS60 = { a: 6378165.0, rf: 298.3, ellipseName: "WGS 60" }; exports$2.WGS66 = { a: 6378145.0, rf: 298.25, ellipseName: "WGS 66" }; exports$2.WGS7 = { a: 6378135.0, rf: 298.26, ellipseName: "WGS 72" }; var WGS84 = exports$2.WGS84 = { a: 6378137.0, rf: 298.257223563, ellipseName: "WGS 84" }; exports$2.sphere = { a: 6370997.0, b: 6370997.0, ellipseName: "Normal Sphere (r=6370997)" }; function eccentricity(a, b, rf, R_A) { var a2 = a * a; // used in geocentric var b2 = b * b; // used in geocentric var es = (a2 - b2) / a2; // e ^ 2 var e = 0; if (R_A) { a *= 1 - es * (SIXTH + es * (RA4 + es * RA6)); a2 = a * a; es = 0; } else { e = Math.sqrt(es); // eccentricity } var ep2 = (a2 - b2) / b2; // used in geocentric return { es: es, e: e, ep2: ep2 }; } function sphere(a, b, rf, ellps, sphere) { if (!a) { // do we have an ellipsoid? var ellipse = match(exports$2, ellps); if (!ellipse) { ellipse = WGS84; } a = ellipse.a; b = ellipse.b; rf = ellipse.rf; } if (rf && !b) { b = (1.0 - 1.0 / rf) * a; } if (rf === 0 || Math.abs(a - b) < EPSLN) { sphere = true; b = a; } return { a: a, b: b, rf: rf, sphere: sphere }; } var exports$3 = {}; exports$3.wgs84 = { towgs84: "0,0,0", ellipse: "WGS84", datumName: "WGS84" }; exports$3.ch1903 = { towgs84: "674.374,15.056,405.346", ellipse: "bessel", datumName: "swiss" }; exports$3.ggrs87 = { towgs84: "-199.87,74.79,246.62", ellipse: "GRS80", datumName: "Greek_Geodetic_Reference_System_1987" }; exports$3.nad83 = { towgs84: "0,0,0", ellipse: "GRS80", datumName: "North_American_Datum_1983" }; exports$3.nad27 = { nadgrids: "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat", ellipse: "clrk66", datumName: "North_American_Datum_1927" }; exports$3.potsdam = { towgs84: "598.1,73.7,418.2,0.202,0.045,-2.455,6.7", ellipse: "bessel", datumName: "Potsdam Rauenberg 1950 DHDN" }; exports$3.carthage = { towgs84: "-263.0,6.0,431.0", ellipse: "clark80", datumName: "Carthage 1934 Tunisia" }; exports$3.hermannskogel = { towgs84: "577.326,90.129,463.919,5.137,1.474,5.297,2.4232", ellipse: "bessel", datumName: "Hermannskogel" }; exports$3.osni52 = { towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15", ellipse: "airy", datumName: "Irish National" }; exports$3.ire65 = { towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15", ellipse: "mod_airy", datumName: "Ireland 1965" }; exports$3.rassadiran = { towgs84: "-133.63,-157.5,-158.62", ellipse: "intl", datumName: "Rassadiran" }; exports$3.nzgd49 = { towgs84: "59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993", ellipse: "intl", datumName: "New Zealand Geodetic Datum 1949" }; exports$3.osgb36 = { towgs84: "446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894", ellipse: "airy", datumName: "Airy 1830" }; exports$3.s_jtsk = { towgs84: "589,76,480", ellipse: 'bessel', datumName: 'S-JTSK (Ferro)' }; exports$3.beduaram = { towgs84: '-106,-87,188', ellipse: 'clrk80', datumName: 'Beduaram' }; exports$3.gunung_segara = { towgs84: '-403,684,41', ellipse: 'bessel', datumName: 'Gunung Segara Jakarta' }; exports$3.rnb72 = { towgs84: "106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1", ellipse: "intl", datumName: "Reseau National Belge 1972" }; function datum(datumCode, datum_params, a, b, es, ep2, nadgrids) { var out = {}; if (datumCode === undefined || datumCode === 'none') { out.datum_type = PJD_NODATUM; } else { out.datum_type = PJD_WGS84; } if (datum_params) { out.datum_params = datum_params.map(parseFloat); if (out.datum_params[0] !== 0 || out.datum_params[1] !== 0 || out.datum_params[2] !== 0) { out.datum_type = PJD_3PARAM; } if (out.datum_params.length > 3) { if (out.datum_params[3] !== 0 || out.datum_params[4] !== 0 || out.datum_params[5] !== 0 || out.datum_params[6] !== 0) { out.datum_type = PJD_7PARAM; out.datum_params[3] *= SEC_TO_RAD; out.datum_params[4] *= SEC_TO_RAD; out.datum_params[5] *= SEC_TO_RAD; out.datum_params[6] = (out.datum_params[6] / 1000000.0) + 1.0; } } } if (nadgrids) { out.datum_type = PJD_GRIDSHIFT; out.grids = nadgrids; } out.a = a; //datum object also uses these values out.b = b; out.es = es; out.ep2 = ep2; return out; } /** * Resources for details of NTv2 file formats: * - https://web.archive.org/web/20140127204822if_/http://www.mgs.gov.on.ca:80/stdprodconsume/groups/content/@mgs/@iandit/documents/resourcelist/stel02_047447.pdf * - http://mimaka.com/help/gs/html/004_NTV2%20Data%20Format.htm */ var loadedNadgrids = {}; /** * Load a binary NTv2 file (.gsb) to a key that can be used in a proj string like +nadgrids=. Pass the NTv2 file * as an ArrayBuffer. */ function nadgrid(key, data) { var view = new DataView(data); var isLittleEndian = detectLittleEndian(view); var header = readHeader(view, isLittleEndian); if (header.nSubgrids > 1) { console.log('Only single NTv2 subgrids are currently supported, subsequent sub grids are ignored'); } var subgrids = readSubgrids(view, header, isLittleEndian); var nadgrid = {header: header, subgrids: subgrids}; loadedNadgrids[key] = nadgrid; return nadgrid; } /** * Given a proj4 value for nadgrids, return an array of loaded grids */ function getNadgrids(nadgrids) { // Format details: http://proj.maptools.org/gen_parms.html if (nadgrids === undefined) { return null; } var grids = nadgrids.split(','); return grids.map(parseNadgridString); } function parseNadgridString(value) { if (value.length === 0) { return null; } var optional = value[0] === '@'; if (optional) { value = value.slice(1); } if (value === 'null') { return {name: 'null', mandatory: !optional, grid: null, isNull: true}; } return { name: value, mandatory: !optional, grid: loadedNadgrids[value] || null, isNull: false }; } function secondsToRadians(seconds) { return (seconds / 3600) * Math.PI / 180; } function detectLittleEndian(view) { var nFields = view.getInt32(8, false); if (nFields === 11) { return false; } nFields = view.getInt32(8, true); if (nFields !== 11) { console.warn('Failed to detect nadgrid endian-ness, defaulting to little-endian'); } return true; } function readHeader(view, isLittleEndian) { return { nFields: view.getInt32(8, isLittleEndian), nSubgridFields: view.getInt32(24, isLittleEndian), nSubgrids: view.getInt32(40, isLittleEndian), shiftType: decodeString(view, 56, 56 + 8).trim(), fromSemiMajorAxis: view.getFloat64(120, isLittleEndian), fromSemiMinorAxis: view.getFloat64(136, isLittleEndian), toSemiMajorAxis: view.getFloat64(152, isLittleEndian), toSemiMinorAxis: view.getFloat64(168, isLittleEndian), }; } function decodeString(view, start, end) { return String.fromCharCode.apply(null, new Uint8Array(view.buffer.slice(start, end))); } function readSubgrids(view, header, isLittleEndian) { var gridOffset = 176; var grids = []; for (var i = 0; i < header.nSubgrids; i++) { var subHeader = readGridHeader(view, gridOffset, isLittleEndian); var nodes = readGridNodes(view, gridOffset, subHeader, isLittleEndian); var lngColumnCount = Math.round( 1 + (subHeader.upperLongitude - subHeader.lowerLongitude) / subHeader.longitudeInterval); var latColumnCount = Math.round( 1 + (subHeader.upperLatitude - subHeader.lowerLatitude) / subHeader.latitudeInterval); // Proj4 operates on radians whereas the coordinates are in seconds in the grid grids.push({ ll: [secondsToRadians(subHeader.lowerLongitude), secondsToRadians(subHeader.lowerLatitude)], del: [secondsToRadians(subHeader.longitudeInterval), secondsToRadians(subHeader.latitudeInterval)], lim: [lngColumnCount, latColumnCount], count: subHeader.gridNodeCount, cvs: mapNodes(nodes) }); } return grids; } function mapNodes(nodes) { return nodes.map(function (r) {return [secondsToRadians(r.longitudeShift), secondsToRadians(r.latitudeShift)];}); } function readGridHeader(view, offset, isLittleEndian) { return { name: decodeString(view, offset + 8, offset + 16).trim(), parent: decodeString(view, offset + 24, offset + 24 + 8).trim(), lowerLatitude: view.getFloat64(offset + 72, isLittleEndian), upperLatitude: view.getFloat64(offset + 88, isLittleEndian), lowerLongitude: view.getFloat64(offset + 104, isLittleEndian), upperLongitude: view.getFloat64(offset + 120, isLittleEndian), latitudeInterval: view.getFloat64(offset + 136, isLittleEndian), longitudeInterval: view.getFloat64(offset + 152, isLittleEndian), gridNodeCount: view.getInt32(offset + 168, isLittleEndian) }; } function readGridNodes(view, offset, gridHeader, isLittleEndian) { var nodesOffset = offset + 176; var gridRecordLength = 16; var gridShiftRecords = []; for (var i = 0; i < gridHeader.gridNodeCount; i++) { var record = { latitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength, isLittleEndian), longitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength + 4, isLittleEndian), latitudeAccuracy: view.getFloat32(nodesOffset + i * gridRecordLength + 8, isLittleEndian), longitudeAccuracy: view.getFloat32(nodesOffset + i * gridRecordLength + 12, isLittleEndian), }; gridShiftRecords.push(record); } return gridShiftRecords; } function Projection(srsCode,callback) { if (!(this instanceof Projection)) { return new Projection(srsCode); } callback = callback || function(error){ if(error){ throw error; } }; var json = parse(srsCode); if(typeof json !== 'object'){ callback(srsCode); return; } var ourProj = Projection.projections.get(json.projName); if(!ourProj){ callback(srsCode); return; } if (json.datumCode && json.datumCode !== 'none') { var datumDef = match(exports$3, json.datumCode); if (datumDef) { json.datum_params = json.datum_params || (datumDef.towgs84 ? datumDef.towgs84.split(',') : null); json.ellps = datumDef.ellipse; json.datumName = datumDef.datumName ? datumDef.datumName : json.datumCode; } } json.k0 = json.k0 || 1.0; json.axis = json.axis || 'enu'; json.ellps = json.ellps || 'wgs84'; json.lat1 = json.lat1 || json.lat0; // Lambert_Conformal_Conic_1SP, for example, needs this var sphere_ = sphere(json.a, json.b, json.rf, json.ellps, json.sphere); var ecc = eccentricity(sphere_.a, sphere_.b, sphere_.rf, json.R_A); var nadgrids = getNadgrids(json.nadgrids); var datumObj = json.datum || datum(json.datumCode, json.datum_params, sphere_.a, sphere_.b, ecc.es, ecc.ep2, nadgrids); extend(this, json); // transfer everything over from the projection because we don't know what we'll need extend(this, ourProj); // transfer all the methods from the projection // copy the 4 things over we calculated in deriveConstants.sphere this.a = sphere_.a; this.b = sphere_.b; this.rf = sphere_.rf; this.sphere = sphere_.sphere; // copy the 3 things we calculated in deriveConstants.eccentricity this.es = ecc.es; this.e = ecc.e; this.ep2 = ecc.ep2; // add in the datum object this.datum = datumObj; // init the projection this.init(); // legecy callback from back in the day when it went to spatialreference.org callback(null, this); } Projection.projections = projections; Projection.projections.start(); 'use strict'; function compareDatums(source, dest) { if (source.datum_type !== dest.datum_type) { return false; // false, datums are not equal } else if (source.a !== dest.a || Math.abs(source.es - dest.es) > 0.000000000050) { // the tolerance for es is to ensure that GRS80 and WGS84 // are considered identical return false; } else if (source.datum_type === PJD_3PARAM) { return (source.datum_params[0] === dest.datum_params[0] && source.datum_params[1] === dest.datum_params[1] && source.datum_params[2] === dest.datum_params[2]); } else if (source.datum_type === PJD_7PARAM) { return (source.datum_params[0] === dest.datum_params[0] && source.datum_params[1] === dest.datum_params[1] && source.datum_params[2] === dest.datum_params[2] && source.datum_params[3] === dest.datum_params[3] && source.datum_params[4] === dest.datum_params[4] && source.datum_params[5] === dest.datum_params[5] && source.datum_params[6] === dest.datum_params[6]); } else { return true; // datums are equal } } // cs_compare_datums() /* * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z), * according to the current ellipsoid parameters. * * Latitude : Geodetic latitude in radians (input) * Longitude : Geodetic longitude in radians (input) * Height : Geodetic height, in meters (input) * X : Calculated Geocentric X coordinate, in meters (output) * Y : Calculated Geocentric Y coordinate, in meters (output) * Z : Calculated Geocentric Z coordinate, in meters (output) * */ function geodeticToGeocentric(p, es, a) { var Longitude = p.x; var Latitude = p.y; var Height = p.z ? p.z : 0; //Z value not always supplied var Rn; /* Earth radius at location */ var Sin_Lat; /* Math.sin(Latitude) */ var Sin2_Lat; /* Square of Math.sin(Latitude) */ var Cos_Lat; /* Math.cos(Latitude) */ /* ** Don't blow up if Latitude is just a little out of the value ** range as it may just be a rounding issue. Also removed longitude ** test, it should be wrapped by Math.cos() and Math.sin(). NFW for PROJ.4, Sep/2001. */ if (Latitude < -HALF_PI && Latitude > -1.001 * HALF_PI) { Latitude = -HALF_PI; } else if (Latitude > HALF_PI && Latitude < 1.001 * HALF_PI) { Latitude = HALF_PI; } else if (Latitude < -HALF_PI) { /* Latitude out of range */ //..reportError('geocent:lat out of range:' + Latitude); return { x: -Infinity, y: -Infinity, z: p.z }; } else if (Latitude > HALF_PI) { /* Latitude out of range */ return { x: Infinity, y: Infinity, z: p.z }; } if (Longitude > Math.PI) { Longitude -= (2 * Math.PI); } Sin_Lat = Math.sin(Latitude); Cos_Lat = Math.cos(Latitude); Sin2_Lat = Sin_Lat * Sin_Lat; Rn = a / (Math.sqrt(1.0e0 - es * Sin2_Lat)); return { x: (Rn + Height) * Cos_Lat * Math.cos(Longitude), y: (Rn + Height) * Cos_Lat * Math.sin(Longitude), z: ((Rn * (1 - es)) + Height) * Sin_Lat }; } // cs_geodetic_to_geocentric() function geocentricToGeodetic(p, es, a, b) { /* local defintions and variables */ /* end-criterium of loop, accuracy of sin(Latitude) */ var genau = 1e-12; var genau2 = (genau * genau); var maxiter = 30; var P; /* distance between semi-minor axis and location */ var RR; /* distance between center and location */ var CT; /* sin of geocentric latitude */ var ST; /* cos of geocentric latitude */ var RX; var RK; var RN; /* Earth radius at location */ var CPHI0; /* cos of start or old geodetic latitude in iterations */ var SPHI0; /* sin of start or old geodetic latitude in iterations */ var CPHI; /* cos of searched geodetic latitude */ var SPHI; /* sin of searched geodetic latitude */ var SDPHI; /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */ var iter; /* # of continous iteration, max. 30 is always enough (s.a.) */ var X = p.x; var Y = p.y; var Z = p.z ? p.z : 0.0; //Z value not always supplied var Longitude; var Latitude; var Height; P = Math.sqrt(X * X + Y * Y); RR = Math.sqrt(X * X + Y * Y + Z * Z); /* special cases for latitude and longitude */ if (P / a < genau) { /* special case, if P=0. (X=0., Y=0.) */ Longitude = 0.0; /* if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis * of ellipsoid (=center of mass), Latitude becomes PI/2 */ if (RR / a < genau) { Latitude = HALF_PI; Height = -b; return { x: p.x, y: p.y, z: p.z }; } } else { /* ellipsoidal (geodetic) longitude * interval: -PI < Longitude <= +PI */ Longitude = Math.atan2(Y, X); } /* -------------------------------------------------------------- * Following iterative algorithm was developped by * "Institut for Erdmessung", University of Hannover, July 1988. * Internet: www.ife.uni-hannover.de * Iterative computation of CPHI,SPHI and Height. * Iteration of CPHI and SPHI to 10**-12 radian resp. * 2*10**-7 arcsec. * -------------------------------------------------------------- */ CT = Z / RR; ST = P / RR; RX = 1.0 / Math.sqrt(1.0 - es * (2.0 - es) * ST * ST); CPHI0 = ST * (1.0 - es) * RX; SPHI0 = CT * RX; iter = 0; /* loop to find sin(Latitude) resp. Latitude * until |sin(Latitude(iter)-Latitude(iter-1))| < genau */ do { iter++; RN = a / Math.sqrt(1.0 - es * SPHI0 * SPHI0); /* ellipsoidal (geodetic) height */ Height = P * CPHI0 + Z * SPHI0 - RN * (1.0 - es * SPHI0 * SPHI0); RK = es * RN / (RN + Height); RX = 1.0 / Math.sqrt(1.0 - RK * (2.0 - RK) * ST * ST); CPHI = ST * (1.0 - RK) * RX; SPHI = CT * RX; SDPHI = SPHI * CPHI0 - CPHI * SPHI0; CPHI0 = CPHI; SPHI0 = SPHI; } while (SDPHI * SDPHI > genau2 && iter < maxiter); /* ellipsoidal (geodetic) latitude */ Latitude = Math.atan(SPHI / Math.abs(CPHI)); return { x: Longitude, y: Latitude, z: Height }; } // cs_geocentric_to_geodetic() /****************************************************************/ // pj_geocentic_to_wgs84( p ) // p = point to transform in geocentric coordinates (x,y,z) /** point object, nothing fancy, just allows values to be passed back and forth by reference rather than by value. Other point classes may be used as long as they have x and y properties, which will get modified in the transform method. */ function geocentricToWgs84(p, datum_type, datum_params) { if (datum_type === PJD_3PARAM) { // if( x[io] === HUGE_VAL ) // continue; return { x: p.x + datum_params[0], y: p.y + datum_params[1], z: p.z + datum_params[2], }; } else if (datum_type === PJD_7PARAM) { var Dx_BF = datum_params[0]; var Dy_BF = datum_params[1]; var Dz_BF = datum_params[2]; var Rx_BF = datum_params[3]; var Ry_BF = datum_params[4]; var Rz_BF = datum_params[5]; var M_BF = datum_params[6]; // if( x[io] === HUGE_VAL ) // continue; return { x: M_BF * (p.x - Rz_BF * p.y + Ry_BF * p.z) + Dx_BF, y: M_BF * (Rz_BF * p.x + p.y - Rx_BF * p.z) + Dy_BF, z: M_BF * (-Ry_BF * p.x + Rx_BF * p.y + p.z) + Dz_BF }; } } // cs_geocentric_to_wgs84 /****************************************************************/ // pj_geocentic_from_wgs84() // coordinate system definition, // point to transform in geocentric coordinates (x,y,z) function geocentricFromWgs84(p, datum_type, datum_params) { if (datum_type === PJD_3PARAM) { //if( x[io] === HUGE_VAL ) // continue; return { x: p.x - datum_params[0], y: p.y - datum_params[1], z: p.z - datum_params[2], }; } else if (datum_type === PJD_7PARAM) { var Dx_BF = datum_params[0]; var Dy_BF = datum_params[1]; var Dz_BF = datum_params[2]; var Rx_BF = datum_params[3]; var Ry_BF = datum_params[4]; var Rz_BF = datum_params[5]; var M_BF = datum_params[6]; var x_tmp = (p.x - Dx_BF) / M_BF; var y_tmp = (p.y - Dy_BF) / M_BF; var z_tmp = (p.z - Dz_BF) / M_BF; //if( x[io] === HUGE_VAL ) // continue; return { x: x_tmp + Rz_BF * y_tmp - Ry_BF * z_tmp, y: -Rz_BF * x_tmp + y_tmp + Rx_BF * z_tmp, z: Ry_BF * x_tmp - Rx_BF * y_tmp + z_tmp }; } //cs_geocentric_from_wgs84() } function checkParams(type) { return (type === PJD_3PARAM || type === PJD_7PARAM); } var datum_transform = function(source, dest, point) { // Short cut if the datums are identical. if (compareDatums(source, dest)) { return point; // in this case, zero is sucess, // whereas cs_compare_datums returns 1 to indicate TRUE // confusing, should fix this } // Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest if (source.datum_type === PJD_NODATUM || dest.datum_type === PJD_NODATUM) { return point; } // If this datum requires grid shifts, then apply it to geodetic coordinates. var source_a = source.a; var source_es = source.es; if (source.datum_type === PJD_GRIDSHIFT) { var gridShiftCode = applyGridShift(source, false, point); if (gridShiftCode !== 0) { return undefined; } source_a = SRS_WGS84_SEMIMAJOR; source_es = SRS_WGS84_ESQUARED; } var dest_a = dest.a; var dest_b = dest.b; var dest_es = dest.es; if (dest.datum_type === PJD_GRIDSHIFT) { dest_a = SRS_WGS84_SEMIMAJOR; dest_b = SRS_WGS84_SEMIMINOR; dest_es = SRS_WGS84_ESQUARED; } // Do we need to go through geocentric coordinates? if (source_es === dest_es && source_a === dest_a && !checkParams(source.datum_type) && !checkParams(dest.datum_type)) { return point; } // Convert to geocentric coordinates. point = geodeticToGeocentric(point, source_es, source_a); // Convert between datums if (checkParams(source.datum_type)) { point = geocentricToWgs84(point, source.datum_type, source.datum_params); } if (checkParams(dest.datum_type)) { point = geocentricFromWgs84(point, dest.datum_type, dest.datum_params); } point = geocentricToGeodetic(point, dest_es, dest_a, dest_b); if (dest.datum_type === PJD_GRIDSHIFT) { var destGridShiftResult = applyGridShift(dest, true, point); if (destGridShiftResult !== 0) { return undefined; } } return point; }; function applyGridShift(source, inverse, point) { if (source.grids === null || source.grids.length === 0) { console.log('Grid shift grids not found'); return -1; } var input = {x: -point.x, y: point.y}; var output = {x: Number.NaN, y: Number.NaN}; var attemptedGrids = []; for (var i = 0; i < source.grids.length; i++) { var grid = source.grids[i]; attemptedGrids.push(grid.name); if (grid.isNull) { output = input; break; } if (grid.grid === null) { if (grid.mandatory) { console.log("Unable to find mandatory grid '" + grid.name + "'"); return -1; } continue; } var subgrid = grid.grid.subgrids[0]; // skip tables that don't match our point at all var epsilon = (Math.abs(subgrid.del[1]) + Math.abs(subgrid.del[0])) / 10000.0; var minX = subgrid.ll[0] - epsilon; var minY = subgrid.ll[1] - epsilon; var maxX = subgrid.ll[0] + (subgrid.lim[0] - 1) * subgrid.del[0] + epsilon; var maxY = subgrid.ll[1] + (subgrid.lim[1] - 1) * subgrid.del[1] + epsilon; if (minY > input.y || minX > input.x || maxY < input.y || maxX < input.x ) { continue; } output = applySubgridShift(input, inverse, subgrid); if (!isNaN(output.x)) { break; } } if (isNaN(output.x)) { console.log("Failed to find a grid shift table for location '"+ -input.x * R2D + " " + input.y * R2D + " tried: '" + attemptedGrids + "'"); return -1; } point.x = -output.x; point.y = output.y; return 0; } function applySubgridShift(pin, inverse, ct) { var val = {x: Number.NaN, y: Number.NaN}; if (isNaN(pin.x)) { return val; } var tb = {x: pin.x, y: pin.y}; tb.x -= ct.ll[0]; tb.y -= ct.ll[1]; tb.x = adjust_lon(tb.x - Math.PI) + Math.PI; var t = nadInterpolate(tb, ct); if (inverse) { if (isNaN(t.x)) { return val; } t.x = tb.x - t.x; t.y = tb.y - t.y; var i = 9, tol = 1e-12; var dif, del; do { del = nadInterpolate(t, ct); if (isNaN(del.x)) { console.log("Inverse grid shift iteration failed, presumably at grid edge. Using first approximation."); break; } dif = {x: tb.x - (del.x + t.x), y: tb.y - (del.y + t.y)}; t.x += dif.x; t.y += dif.y; } while (i-- && Math.abs(dif.x) > tol && Math.abs(dif.y) > tol); if (i < 0) { console.log("Inverse grid shift iterator failed to converge."); return val; } val.x = adjust_lon(t.x + ct.ll[0]); val.y = t.y + ct.ll[1]; } else { if (!isNaN(t.x)) { val.x = pin.x + t.x; val.y = pin.y + t.y; } } return val; } function nadInterpolate(pin, ct) { var t = {x: pin.x / ct.del[0], y: pin.y / ct.del[1]}; var indx = {x: Math.floor(t.x), y: Math.floor(t.y)}; var frct = {x: t.x - 1.0 * indx.x, y: t.y - 1.0 * indx.y}; var val= {x: Number.NaN, y: Number.NaN}; var inx; if (indx.x < 0 || indx.x >= ct.lim[0]) { return val; } if (indx.y < 0 || indx.y >= ct.lim[1]) { return val; } inx = (indx.y * ct.lim[0]) + indx.x; var f00 = {x: ct.cvs[inx][0], y: ct.cvs[inx][1]}; inx++; var f10= {x: ct.cvs[inx][0], y: ct.cvs[inx][1]}; inx += ct.lim[0]; var f11 = {x: ct.cvs[inx][0], y: ct.cvs[inx][1]}; inx--; var f01 = {x: ct.cvs[inx][0], y: ct.cvs[inx][1]}; var m11 = frct.x * frct.y, m10 = frct.x * (1.0 - frct.y), m00 = (1.0 - frct.x) * (1.0 - frct.y), m01 = (1.0 - frct.x) * frct.y; val.x = (m00 * f00.x + m10 * f10.x + m01 * f01.x + m11 * f11.x); val.y = (m00 * f00.y + m10 * f10.y + m01 * f01.y + m11 * f11.y); return val; } var adjust_axis = function(crs, denorm, point) { var xin = point.x, yin = point.y, zin = point.z || 0.0; var v, t, i; var out = {}; for (i = 0; i < 3; i++) { if (denorm && i === 2 && point.z === undefined) { continue; } if (i === 0) { v = xin; if ("ew".indexOf(crs.axis[i]) !== -1) { t = 'x'; } else { t = 'y'; } } else if (i === 1) { v = yin; if ("ns".indexOf(crs.axis[i]) !== -1) { t = 'y'; } else { t = 'x'; } } else { v = zin; t = 'z'; } switch (crs.axis[i]) { case 'e': out[t] = v; break; case 'w': out[t] = -v; break; case 'n': out[t] = v; break; case 's': out[t] = -v; break; case 'u': if (point[t] !== undefined) { out.z = v; } break; case 'd': if (point[t] !== undefined) { out.z = -v; } break; default: //console.log("ERROR: unknow axis ("+crs.axis[i]+") - check definition of "+crs.projName); return null; } } return out; }; var toPoint = function (array){ var out = { x: array[0], y: array[1] }; if (array.length>2) { out.z = array[2]; } if (array.length>3) { out.m = array[3]; } return out; }; var checkSanity = function (point) { checkCoord(point.x); checkCoord(point.y); }; function checkCoord(num) { if (typeof Number.isFinite === 'function') { if (Number.isFinite(num)) { return; } throw new TypeError('coordinates must be finite numbers'); } if (typeof num !== 'number' || num !== num || !isFinite(num)) { throw new TypeError('coordinates must be finite numbers'); } } function checkNotWGS(source, dest) { return ( (source.datum.datum_type === PJD_3PARAM || source.datum.datum_type === PJD_7PARAM || source.datum.datum_type === PJD_GRIDSHIFT) && dest.datumCode !== 'WGS84') || ((dest.datum.datum_type === PJD_3PARAM || dest.datum.datum_type === PJD_7PARAM || dest.datum.datum_type === PJD_GRIDSHIFT) && source.datumCode !== 'WGS84'); } function transform(source, dest, point, enforceAxis) { var wgs84; if (Array.isArray(point)) { point = toPoint(point); } else { // Clone the point object so inputs don't get modified point = { x: point.x, y: point.y, z: point.z, m: point.m }; } var hasZ = point.z !== undefined; checkSanity(point); // Workaround for datum shifts towgs84, if either source or destination projection is not wgs84 if (source.datum && dest.datum && checkNotWGS(source, dest)) { wgs84 = new Projection('WGS84'); point = transform(source, wgs84, point, enforceAxis); source = wgs84; } // DGR, 2010/11/12 if (enforceAxis && source.axis !== 'enu') { point = adjust_axis(source, false, point); } // Transform source points to long/lat, if they aren't already. if (source.projName === 'longlat') { point = { x: point.x * D2R, y: point.y * D2R, z: point.z || 0 }; } else { if (source.to_meter) { point = { x: point.x * source.to_meter, y: point.y * source.to_meter, z: point.z || 0 }; } point = source.inverse(point); // Convert Cartesian to longlat if (!point) { return; } } // Adjust for the prime meridian if necessary if (source.from_greenwich) { point.x += source.from_greenwich; } // Convert datums if needed, and if possible. point = datum_transform(source.datum, dest.datum, point); if (!point) { return; } // Adjust for the prime meridian if necessary if (dest.from_greenwich) { point = { x: point.x - dest.from_greenwich, y: point.y, z: point.z || 0 }; } if (dest.projName === 'longlat') { // convert radians to decimal degrees point = { x: point.x * R2D, y: point.y * R2D, z: point.z || 0 }; } else { // else project point = dest.forward(point); if (dest.to_meter) { point = { x: point.x / dest.to_meter, y: point.y / dest.to_meter, z: point.z || 0 }; } } // DGR, 2010/11/12 if (enforceAxis && dest.axis !== 'enu') { return adjust_axis(dest, true, point); } if (!hasZ) { delete point.z; } return point; } var wgs84 = Projection('WGS84'); function transformer(from, to, coords, enforceAxis) { var transformedArray, out, keys; if (Array.isArray(coords)) { transformedArray = transform(from, to, coords, enforceAxis) || {x: NaN, y: NaN}; if (coords.length > 2) { if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) { if (typeof transformedArray.z === 'number') { return [transformedArray.x, transformedArray.y, transformedArray.z].concat(coords.splice(3)); } else { return [transformedArray.x, transformedArray.y, coords[2]].concat(coords.splice(3)); } } else { return [transformedArray.x, transformedArray.y].concat(coords.splice(2)); } } else { return [transformedArray.x, transformedArray.y]; } } else { out = transform(from, to, coords, enforceAxis); keys = Object.keys(coords); if (keys.length === 2) { return out; } keys.forEach(function (key) { if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) { if (key === 'x' || key === 'y' || key === 'z') { return; } } else { if (key === 'x' || key === 'y') { return; } } out[key] = coords[key]; }); return out; } } function checkProj(item) { if (item instanceof Projection) { return item; } if (item.oProj) { return item.oProj; } return Projection(item); } function proj4$1(fromProj, toProj, coord) { fromProj = checkProj(fromProj); var single = false; var obj; if (typeof toProj === 'undefined') { toProj = fromProj; fromProj = wgs84; single = true; } else if (typeof toProj.x !== 'undefined' || Array.isArray(toProj)) { coord = toProj; toProj = fromProj; fromProj = wgs84; single = true; } toProj = checkProj(toProj); if (coord) { return transformer(fromProj, toProj, coord); } else { obj = { forward: function (coords, enforceAxis) { return transformer(fromProj, toProj, coords, enforceAxis); }, inverse: function (coords, enforceAxis) { return transformer(toProj, fromProj, coords, enforceAxis); } }; if (single) { obj.oProj = toProj; } return obj; } } /** * UTM zones are grouped, and assigned to one of a group of 6 * sets. * * {int} @private */ var NUM_100K_SETS = 6; /** * The column letters (for easting) of the lower left value, per * set. * * {string} @private */ var SET_ORIGIN_COLUMN_LETTERS = 'AJSAJS'; /** * The row letters (for northing) of the lower left value, per * set. * * {string} @private */ var SET_ORIGIN_ROW_LETTERS = 'AFAFAF'; var A = 65; // A var I = 73; // I var O = 79; // O var V = 86; // V var Z = 90; // Z var mgrs = { forward: forward$1, inverse: inverse$1, toPoint: toPoint$1 }; /** * Conversion of lat/lon to MGRS. * * @param {object} ll Object literal with lat and lon properties on a * WGS84 ellipsoid. * @param {int} accuracy Accuracy in digits (5 for 1 m, 4 for 10 m, 3 for * 100 m, 2 for 1000 m or 1 for 10000 m). Optional, default is 5. * @return {string} the MGRS string for the given location and accuracy. */ function forward$1(ll, accuracy) { accuracy = accuracy || 5; // default accuracy 1m return encode(LLtoUTM({ lat: ll[1], lon: ll[0] }), accuracy); } /** * Conversion of MGRS to lat/lon. * * @param {string} mgrs MGRS string. * @return {array} An array with left (longitude), bottom (latitude), right * (longitude) and top (latitude) values in WGS84, representing the * bounding box for the provided MGRS reference. */ function inverse$1(mgrs) { var bbox = UTMtoLL(decode(mgrs.toUpperCase())); if (bbox.lat && bbox.lon) { return [bbox.lon, bbox.lat, bbox.lon, bbox.lat]; } return [bbox.left, bbox.bottom, bbox.right, bbox.top]; } function toPoint$1(mgrs) { var bbox = UTMtoLL(decode(mgrs.toUpperCase())); if (bbox.lat && bbox.lon) { return [bbox.lon, bbox.lat]; } return [(bbox.left + bbox.right) / 2, (bbox.top + bbox.bottom) / 2]; } /** * Conversion from degrees to radians. * * @private * @param {number} deg the angle in degrees. * @return {number} the angle in radians. */ function degToRad(deg) { return (deg * (Math.PI / 180.0)); } /** * Conversion from radians to degrees. * * @private * @param {number} rad the angle in radians. * @return {number} the angle in degrees. */ function radToDeg(rad) { return (180.0 * (rad / Math.PI)); } /** * Converts a set of Longitude and Latitude co-ordinates to UTM * using the WGS84 ellipsoid. * * @private * @param {object} ll Object literal with lat and lon properties * representing the WGS84 coordinate to be converted. * @return {object} Object literal containing the UTM value with easting, * northing, zoneNumber and zoneLetter properties, and an optional * accuracy property in digits. Returns null if the conversion failed. */ function LLtoUTM(ll) { var Lat = ll.lat; var Long = ll.lon; var a = 6378137.0; //ellip.radius; var eccSquared = 0.00669438; //ellip.eccsq; var k0 = 0.9996; var LongOrigin; var eccPrimeSquared; var N, T, C, A, M; var LatRad = degToRad(Lat); var LongRad = degToRad(Long); var LongOriginRad; var ZoneNumber; // (int) ZoneNumber = Math.floor((Long + 180) / 6) + 1; //Make sure the longitude 180.00 is in Zone 60 if (Long === 180) { ZoneNumber = 60; } // Special zone for Norway if (Lat >= 56.0 && Lat < 64.0 && Long >= 3.0 && Long < 12.0) { ZoneNumber = 32; } // Special zones for Svalbard if (Lat >= 72.0 && Lat < 84.0) { if (Long >= 0.0 && Long < 9.0) { ZoneNumber = 31; } else if (Long >= 9.0 && Long < 21.0) { ZoneNumber = 33; } else if (Long >= 21.0 && Long < 33.0) { ZoneNumber = 35; } else if (Long >= 33.0 && Long < 42.0) { ZoneNumber = 37; } } LongOrigin = (ZoneNumber - 1) * 6 - 180 + 3; //+3 puts origin // in middle of // zone LongOriginRad = degToRad(LongOrigin); eccPrimeSquared = (eccSquared) / (1 - eccSquared); N = a / Math.sqrt(1 - eccSquared * Math.sin(LatRad) * Math.sin(LatRad)); T = Math.tan(LatRad) * Math.tan(LatRad); C = eccPrimeSquared * Math.cos(LatRad) * Math.cos(LatRad); A = Math.cos(LatRad) * (LongRad - LongOriginRad); M = a * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * LatRad - (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(2 * LatRad) + (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(4 * LatRad) - (35 * eccSquared * eccSquared * eccSquared / 3072) * Math.sin(6 * LatRad)); var UTMEasting = (k0 * N * (A + (1 - T + C) * A * A * A / 6.0 + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120.0) + 500000.0); var UTMNorthing = (k0 * (M + N * Math.tan(LatRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24.0 + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720.0))); if (Lat < 0.0) { UTMNorthing += 10000000.0; //10000000 meter offset for // southern hemisphere } return { northing: Math.round(UTMNorthing), easting: Math.round(UTMEasting), zoneNumber: ZoneNumber, zoneLetter: getLetterDesignator(Lat) }; } /** * Converts UTM coords to lat/long, using the WGS84 ellipsoid. This is a convenience * class where the Zone can be specified as a single string eg."60N" which * is then broken down into the ZoneNumber and ZoneLetter. * * @private * @param {object} utm An object literal with northing, easting, zoneNumber * and zoneLetter properties. If an optional accuracy property is * provided (in meters), a bounding box will be returned instead of * latitude and longitude. * @return {object} An object literal containing either lat and lon values * (if no accuracy was provided), or top, right, bottom and left values * for the bounding box calculated according to the provided accuracy. * Returns null if the conversion failed. */ function UTMtoLL(utm) { var UTMNorthing = utm.northing; var UTMEasting = utm.easting; var zoneLetter = utm.zoneLetter; var zoneNumber = utm.zoneNumber; // check the ZoneNummber is valid if (zoneNumber < 0 || zoneNumber > 60) { return null; } var k0 = 0.9996; var a = 6378137.0; //ellip.radius; var eccSquared = 0.00669438; //ellip.eccsq; var eccPrimeSquared; var e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared)); var N1, T1, C1, R1, D, M; var LongOrigin; var mu, phi1Rad; // remove 500,000 meter offset for longitude var x = UTMEasting - 500000.0; var y = UTMNorthing; // We must know somehow if we are in the Northern or Southern // hemisphere, this is the only time we use the letter So even // if the Zone letter isn't exactly correct it should indicate // the hemisphere correctly if (zoneLetter < 'N') { y -= 10000000.0; // remove 10,000,000 meter offset used // for southern hemisphere } // There are 60 zones with zone 1 being at West -180 to -174 LongOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin // in middle of // zone eccPrimeSquared = (eccSquared) / (1 - eccSquared); M = y / k0; mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256)); phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.sin(4 * mu) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * mu); // double phi1 = ProjMath.radToDeg(phi1Rad); N1 = a / Math.sqrt(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad)); T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad); C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad); R1 = a * (1 - eccSquared) / Math.pow(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad), 1.5); D = x / (N1 * k0); var lat = phi1Rad - (N1 * Math.tan(phi1Rad) / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * eccPrimeSquared - 3 * C1 * C1) * D * D * D * D * D * D / 720); lat = radToDeg(lat); var lon = (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * eccPrimeSquared + 24 * T1 * T1) * D * D * D * D * D / 120) / Math.cos(phi1Rad); lon = LongOrigin + radToDeg(lon); var result; if (utm.accuracy) { var topRight = UTMtoLL({ northing: utm.northing + utm.accuracy, easting: utm.easting + utm.accuracy, zoneLetter: utm.zoneLetter, zoneNumber: utm.zoneNumber }); result = { top: topRight.lat, right: topRight.lon, bottom: lat, left: lon }; } else { result = { lat: lat, lon: lon }; } return result; } /** * Calculates the MGRS letter designator for the given latitude. * * @private * @param {number} lat The latitude in WGS84 to get the letter designator * for. * @return {char} The letter designator. */ function getLetterDesignator(lat) { //This is here as an error flag to show that the Latitude is //outside MGRS limits var LetterDesignator = 'Z'; if ((84 >= lat) && (lat >= 72)) { LetterDesignator = 'X'; } else if ((72 > lat) && (lat >= 64)) { LetterDesignator = 'W'; } else if ((64 > lat) && (lat >= 56)) { LetterDesignator = 'V'; } else if ((56 > lat) && (lat >= 48)) { LetterDesignator = 'U'; } else if ((48 > lat) && (lat >= 40)) { LetterDesignator = 'T'; } else if ((40 > lat) && (lat >= 32)) { LetterDesignator = 'S'; } else if ((32 > lat) && (lat >= 24)) { LetterDesignator = 'R'; } else if ((24 > lat) && (lat >= 16)) { LetterDesignator = 'Q'; } else if ((16 > lat) && (lat >= 8)) { LetterDesignator = 'P'; } else if ((8 > lat) && (lat >= 0)) { LetterDesignator = 'N'; } else if ((0 > lat) && (lat >= -8)) { LetterDesignator = 'M'; } else if ((-8 > lat) && (lat >= -16)) { LetterDesignator = 'L'; } else if ((-16 > lat) && (lat >= -24)) { LetterDesignator = 'K'; } else if ((-24 > lat) && (lat >= -32)) { LetterDesignator = 'J'; } else if ((-32 > lat) && (lat >= -40)) { LetterDesignator = 'H'; } else if ((-40 > lat) && (lat >= -48)) { LetterDesignator = 'G'; } else if ((-48 > lat) && (lat >= -56)) { LetterDesignator = 'F'; } else if ((-56 > lat) && (lat >= -64)) { LetterDesignator = 'E'; } else if ((-64 > lat) && (lat >= -72)) { LetterDesignator = 'D'; } else if ((-72 > lat) && (lat >= -80)) { LetterDesignator = 'C'; } return LetterDesignator; } /** * Encodes a UTM location as MGRS string. * * @private * @param {object} utm An object literal with easting, northing, * zoneLetter, zoneNumber * @param {number} accuracy Accuracy in digits (1-5). * @return {string} MGRS string for the given UTM location. */ function encode(utm, accuracy) { // prepend with leading zeroes var seasting = "00000" + utm.easting, snorthing = "00000" + utm.northing; return utm.zoneNumber + utm.zoneLetter + get100kID(utm.easting, utm.northing, utm.zoneNumber) + seasting.substr(seasting.length - 5, accuracy) + snorthing.substr(snorthing.length - 5, accuracy); } /** * Get the two letter 100k designator for a given UTM easting, * northing and zone number value. * * @private * @param {number} easting * @param {number} northing * @param {number} zoneNumber * @return the two letter 100k designator for the given UTM location. */ function get100kID(easting, northing, zoneNumber) { var setParm = get100kSetForZone(zoneNumber); var setColumn = Math.floor(easting / 100000); var setRow = Math.floor(northing / 100000) % 20; return getLetter100kID(setColumn, setRow, setParm); } /** * Given a UTM zone number, figure out the MGRS 100K set it is in. * * @private * @param {number} i An UTM zone number. * @return {number} the 100k set the UTM zone is in. */ function get100kSetForZone(i) { var setParm = i % NUM_100K_SETS; if (setParm === 0) { setParm = NUM_100K_SETS; } return setParm; } /** * Get the two-letter MGRS 100k designator given information * translated from the UTM northing, easting and zone number. * * @private * @param {number} column the column index as it relates to the MGRS * 100k set spreadsheet, created from the UTM easting. * Values are 1-8. * @param {number} row the row index as it relates to the MGRS 100k set * spreadsheet, created from the UTM northing value. Values * are from 0-19. * @param {number} parm the set block, as it relates to the MGRS 100k set * spreadsheet, created from the UTM zone. Values are from * 1-60. * @return two letter MGRS 100k code. */ function getLetter100kID(column, row, parm) { // colOrigin and rowOrigin are the letters at the origin of the set var index = parm - 1; var colOrigin = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(index); var rowOrigin = SET_ORIGIN_ROW_LETTERS.charCodeAt(index); // colInt and rowInt are the letters to build to return var colInt = colOrigin + column - 1; var rowInt = rowOrigin + row; var rollover = false; if (colInt > Z) { colInt = colInt - Z + A - 1; rollover = true; } if (colInt === I || (colOrigin < I && colInt > I) || ((colInt > I || colOrigin < I) && rollover)) { colInt++; } if (colInt === O || (colOrigin < O && colInt > O) || ((colInt > O || colOrigin < O) && rollover)) { colInt++; if (colInt === I) { colInt++; } } if (colInt > Z) { colInt = colInt - Z + A - 1; } if (rowInt > V) { rowInt = rowInt - V + A - 1; rollover = true; } else { rollover = false; } if (((rowInt === I) || ((rowOrigin < I) && (rowInt > I))) || (((rowInt > I) || (rowOrigin < I)) && rollover)) { rowInt++; } if (((rowInt === O) || ((rowOrigin < O) && (rowInt > O))) || (((rowInt > O) || (rowOrigin < O)) && rollover)) { rowInt++; if (rowInt === I) { rowInt++; } } if (rowInt > V) { rowInt = rowInt - V + A - 1; } var twoLetter = String.fromCharCode(colInt) + String.fromCharCode(rowInt); return twoLetter; } /** * Decode the UTM parameters from a MGRS string. * * @private * @param {string} mgrsString an UPPERCASE coordinate string is expected. * @return {object} An object literal with easting, northing, zoneLetter, * zoneNumber and accuracy (in meters) properties. */ function decode(mgrsString) { if (mgrsString && mgrsString.length === 0) { throw ("MGRSPoint coverting from nothing"); } var length = mgrsString.length; var hunK = null; var sb = ""; var testChar; var i = 0; // get Zone number while (!(/[A-Z]/).test(testChar = mgrsString.charAt(i))) { if (i >= 2) { throw ("MGRSPoint bad conversion from: " + mgrsString); } sb += testChar; i++; } var zoneNumber = parseInt(sb, 10); if (i === 0 || i + 3 > length) { // A good MGRS string has to be 4-5 digits long, // ##AAA/#AAA at least. throw ("MGRSPoint bad conversion from: " + mgrsString); } var zoneLetter = mgrsString.charAt(i++); // Should we check the zone letter here? Why not. if (zoneLetter <= 'A' || zoneLetter === 'B' || zoneLetter === 'Y' || zoneLetter >= 'Z' || zoneLetter === 'I' || zoneLetter === 'O') { throw ("MGRSPoint zone letter " + zoneLetter + " not handled: " + mgrsString); } hunK = mgrsString.substring(i, i += 2); var set = get100kSetForZone(zoneNumber); var east100k = getEastingFromChar(hunK.charAt(0), set); var north100k = getNorthingFromChar(hunK.charAt(1), set); // We have a bug where the northing may be 2000000 too low. // How // do we know when to roll over? while (north100k < getMinNorthing(zoneLetter)) { north100k += 2000000; } // calculate the char index for easting/northing separator var remainder = length - i; if (remainder % 2 !== 0) { throw ("MGRSPoint has to have an even number \nof digits after the zone letter and two 100km letters - front \nhalf for easting meters, second half for \nnorthing meters" + mgrsString); } var sep = remainder / 2; var sepEasting = 0.0; var sepNorthing = 0.0; var accuracyBonus, sepEastingString, sepNorthingString, easting, northing; if (sep > 0) { accuracyBonus = 100000.0 / Math.pow(10, sep); sepEastingString = mgrsString.substring(i, i + sep); sepEasting = parseFloat(sepEastingString) * accuracyBonus; sepNorthingString = mgrsString.substring(i + sep); sepNorthing = parseFloat(sepNorthingString) * accuracyBonus; } easting = sepEasting + east100k; northing = sepNorthing + north100k; return { easting: easting, northing: northing, zoneLetter: zoneLetter, zoneNumber: zoneNumber, accuracy: accuracyBonus }; } /** * Given the first letter from a two-letter MGRS 100k zone, and given the * MGRS table set for the zone number, figure out the easting value that * should be added to the other, secondary easting value. * * @private * @param {char} e The first letter from a two-letter MGRS 100´k zone. * @param {number} set The MGRS table set for the zone number. * @return {number} The easting value for the given letter and set. */ function getEastingFromChar(e, set) { // colOrigin is the letter at the origin of the set for the // column var curCol = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(set - 1); var eastingValue = 100000.0; var rewindMarker = false; while (curCol !== e.charCodeAt(0)) { curCol++; if (curCol === I) { curCol++; } if (curCol === O) { curCol++; } if (curCol > Z) { if (rewindMarker) { throw ("Bad character: " + e); } curCol = A; rewindMarker = true; } eastingValue += 100000.0; } return eastingValue; } /** * Given the second letter from a two-letter MGRS 100k zone, and given the * MGRS table set for the zone number, figure out the northing value that * should be added to the other, secondary northing value. You have to * remember that Northings are determined from the equator, and the vertical * cycle of letters mean a 2000000 additional northing meters. This happens * approx. every 18 degrees of latitude. This method does *NOT* count any * additional northings. You have to figure out how many 2000000 meters need * to be added for the zone letter of the MGRS coordinate. * * @private * @param {char} n Second letter of the MGRS 100k zone * @param {number} set The MGRS table set number, which is dependent on the * UTM zone number. * @return {number} The northing value for the given letter and set. */ function getNorthingFromChar(n, set) { if (n > 'V') { throw ("MGRSPoint given invalid Northing " + n); } // rowOrigin is the letter at the origin of the set for the // column var curRow = SET_ORIGIN_ROW_LETTERS.charCodeAt(set - 1); var northingValue = 0.0; var rewindMarker = false; while (curRow !== n.charCodeAt(0)) { curRow++; if (curRow === I) { curRow++; } if (curRow === O) { curRow++; } // fixing a bug making whole application hang in this loop // when 'n' is a wrong character if (curRow > V) { if (rewindMarker) { // making sure that this loop ends throw ("Bad character: " + n); } curRow = A; rewindMarker = true; } northingValue += 100000.0; } return northingValue; } /** * The function getMinNorthing returns the minimum northing value of a MGRS * zone. * * Ported from Geotrans' c Lattitude_Band_Value structure table. * * @private * @param {char} zoneLetter The MGRS zone to get the min northing for. * @return {number} */ function getMinNorthing(zoneLetter) { var northing; switch (zoneLetter) { case 'C': northing = 1100000.0; break; case 'D': northing = 2000000.0; break; case 'E': northing = 2800000.0; break; case 'F': northing = 3700000.0; break; case 'G': northing = 4600000.0; break; case 'H': northing = 5500000.0; break; case 'J': northing = 6400000.0; break; case 'K': northing = 7300000.0; break; case 'L': northing = 8200000.0; break; case 'M': northing = 9100000.0; break; case 'N': northing = 0.0; break; case 'P': northing = 800000.0; break; case 'Q': northing = 1700000.0; break; case 'R': northing = 2600000.0; break; case 'S': northing = 3500000.0; break; case 'T': northing = 4400000.0; break; case 'U': northing = 5300000.0; break; case 'V': northing = 6200000.0; break; case 'W': northing = 7000000.0; break; case 'X': northing = 7900000.0; break; default: northing = -1.0; } if (northing >= 0.0) { return northing; } else { throw ("Invalid zone letter: " + zoneLetter); } } function Point(x, y, z) { if (!(this instanceof Point)) { return new Point(x, y, z); } if (Array.isArray(x)) { this.x = x[0]; this.y = x[1]; this.z = x[2] || 0.0; } else if(typeof x === 'object') { this.x = x.x; this.y = x.y; this.z = x.z || 0.0; } else if (typeof x === 'string' && typeof y === 'undefined') { var coords = x.split(','); this.x = parseFloat(coords[0], 10); this.y = parseFloat(coords[1], 10); this.z = parseFloat(coords[2], 10) || 0.0; } else { this.x = x; this.y = y; this.z = z || 0.0; } console.warn('proj4.Point will be removed in version 3, use proj4.toPoint'); } Point.fromMGRS = function(mgrsStr) { return new Point(toPoint$1(mgrsStr)); }; Point.prototype.toMGRS = function(accuracy) { return forward$1([this.x, this.y], accuracy); }; var C00 = 1; var C02 = 0.25; var C04 = 0.046875; var C06 = 0.01953125; var C08 = 0.01068115234375; var C22 = 0.75; var C44 = 0.46875; var C46 = 0.01302083333333333333; var C48 = 0.00712076822916666666; var C66 = 0.36458333333333333333; var C68 = 0.00569661458333333333; var C88 = 0.3076171875; var pj_enfn = function(es) { var en = []; en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08))); en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08))); var t = es * es; en[2] = t * (C44 - es * (C46 + es * C48)); t *= es; en[3] = t * (C66 - es * C68); en[4] = t * es * C88; return en; }; var pj_mlfn = function(phi, sphi, cphi, en) { cphi *= sphi; sphi *= sphi; return (en[0] * phi - cphi * (en[1] + sphi * (en[2] + sphi * (en[3] + sphi * en[4])))); }; var MAX_ITER = 20; var pj_inv_mlfn = function(arg, es, en) { var k = 1 / (1 - es); var phi = arg; for (var i = MAX_ITER; i; --i) { /* rarely goes over 2 iterations */ var s = Math.sin(phi); var t = 1 - es * s * s; //t = this.pj_mlfn(phi, s, Math.cos(phi), en) - arg; //phi -= t * (t * Math.sqrt(t)) * k; t = (pj_mlfn(phi, s, Math.cos(phi), en) - arg) * (t * Math.sqrt(t)) * k; phi -= t; if (Math.abs(t) < EPSLN) { return phi; } } //..reportError("cass:pj_inv_mlfn: Convergence error"); return phi; }; // Heavily based on this tmerc projection implementation // https://github.com/mbloch/mapshaper-proj/blob/master/src/projections/tmerc.js function init$2() { this.x0 = this.x0 !== undefined ? this.x0 : 0; this.y0 = this.y0 !== undefined ? this.y0 : 0; this.long0 = this.long0 !== undefined ? this.long0 : 0; this.lat0 = this.lat0 !== undefined ? this.lat0 : 0; if (this.es) { this.en = pj_enfn(this.es); this.ml0 = pj_mlfn(this.lat0, Math.sin(this.lat0), Math.cos(this.lat0), this.en); } } /** Transverse Mercator Forward - long/lat to x/y long/lat in radians */ function forward$2(p) { var lon = p.x; var lat = p.y; var delta_lon = adjust_lon(lon - this.long0); var con; var x, y; var sin_phi = Math.sin(lat); var cos_phi = Math.cos(lat); if (!this.es) { var b = cos_phi * Math.sin(delta_lon); if ((Math.abs(Math.abs(b) - 1)) < EPSLN) { return (93); } else { x = 0.5 * this.a * this.k0 * Math.log((1 + b) / (1 - b)) + this.x0; y = cos_phi * Math.cos(delta_lon) / Math.sqrt(1 - Math.pow(b, 2)); b = Math.abs(y); if (b >= 1) { if ((b - 1) > EPSLN) { return (93); } else { y = 0; } } else { y = Math.acos(y); } if (lat < 0) { y = -y; } y = this.a * this.k0 * (y - this.lat0) + this.y0; } } else { var al = cos_phi * delta_lon; var als = Math.pow(al, 2); var c = this.ep2 * Math.pow(cos_phi, 2); var cs = Math.pow(c, 2); var tq = Math.abs(cos_phi) > EPSLN ? Math.tan(lat) : 0; var t = Math.pow(tq, 2); var ts = Math.pow(t, 2); con = 1 - this.es * Math.pow(sin_phi, 2); al = al / Math.sqrt(con); var ml = pj_mlfn(lat, sin_phi, cos_phi, this.en); x = this.a * (this.k0 * al * (1 + als / 6 * (1 - t + c + als / 20 * (5 - 18 * t + ts + 14 * c - 58 * t * c + als / 42 * (61 + 179 * ts - ts * t - 479 * t))))) + this.x0; y = this.a * (this.k0 * (ml - this.ml0 + sin_phi * delta_lon * al / 2 * (1 + als / 12 * (5 - t + 9 * c + 4 * cs + als / 30 * (61 + ts - 58 * t + 270 * c - 330 * t * c + als / 56 * (1385 + 543 * ts - ts * t - 3111 * t)))))) + this.y0; } p.x = x; p.y = y; return p; } /** Transverse Mercator Inverse - x/y to long/lat */ function inverse$2(p) { var con, phi; var lat, lon; var x = (p.x - this.x0) * (1 / this.a); var y = (p.y - this.y0) * (1 / this.a); if (!this.es) { var f = Math.exp(x / this.k0); var g = 0.5 * (f - 1 / f); var temp = this.lat0 + y / this.k0; var h = Math.cos(temp); con = Math.sqrt((1 - Math.pow(h, 2)) / (1 + Math.pow(g, 2))); lat = Math.asin(con); if (y < 0) { lat = -lat; } if ((g === 0) && (h === 0)) { lon = 0; } else { lon = adjust_lon(Math.atan2(g, h) + this.long0); } } else { // ellipsoidal form con = this.ml0 + y / this.k0; phi = pj_inv_mlfn(con, this.es, this.en); if (Math.abs(phi) < HALF_PI) { var sin_phi = Math.sin(phi); var cos_phi = Math.cos(phi); var tan_phi = Math.abs(cos_phi) > EPSLN ? Math.tan(phi) : 0; var c = this.ep2 * Math.pow(cos_phi, 2); var cs = Math.pow(c, 2); var t = Math.pow(tan_phi, 2); var ts = Math.pow(t, 2); con = 1 - this.es * Math.pow(sin_phi, 2); var d = x * Math.sqrt(con) / this.k0; var ds = Math.pow(d, 2); con = con * tan_phi; lat = phi - (con * ds / (1 - this.es)) * 0.5 * (1 - ds / 12 * (5 + 3 * t - 9 * c * t + c - 4 * cs - ds / 30 * (61 + 90 * t - 252 * c * t + 45 * ts + 46 * c - ds / 56 * (1385 + 3633 * t + 4095 * ts + 1574 * ts * t)))); lon = adjust_lon(this.long0 + (d * (1 - ds / 6 * (1 + 2 * t + c - ds / 20 * (5 + 28 * t + 24 * ts + 8 * c * t + 6 * c - ds / 42 * (61 + 662 * t + 1320 * ts + 720 * ts * t)))) / cos_phi)); } else { lat = HALF_PI * sign(y); lon = 0; } } p.x = lon; p.y = lat; return p; } var names$3 = ["Fast_Transverse_Mercator", "Fast Transverse Mercator"]; var tmerc = { init: init$2, forward: forward$2, inverse: inverse$2, names: names$3 }; var sinh = function(x) { var r = Math.exp(x); r = (r - 1 / r) / 2; return r; }; var hypot = function(x, y) { x = Math.abs(x); y = Math.abs(y); var a = Math.max(x, y); var b = Math.min(x, y) / (a ? a : 1); return a * Math.sqrt(1 + Math.pow(b, 2)); }; var log1py = function(x) { var y = 1 + x; var z = y - 1; return z === 0 ? x : x * Math.log(y) / z; }; var asinhy = function(x) { var y = Math.abs(x); y = log1py(y * (1 + y / (hypot(1, y) + 1))); return x < 0 ? -y : y; }; var gatg = function(pp, B) { var cos_2B = 2 * Math.cos(2 * B); var i = pp.length - 1; var h1 = pp[i]; var h2 = 0; var h; while (--i >= 0) { h = -h2 + cos_2B * h1 + pp[i]; h2 = h1; h1 = h; } return (B + h * Math.sin(2 * B)); }; var clens = function(pp, arg_r) { var r = 2 * Math.cos(arg_r); var i = pp.length - 1; var hr1 = pp[i]; var hr2 = 0; var hr; while (--i >= 0) { hr = -hr2 + r * hr1 + pp[i]; hr2 = hr1; hr1 = hr; } return Math.sin(arg_r) * hr; }; var cosh = function(x) { var r = Math.exp(x); r = (r + 1 / r) / 2; return r; }; var clens_cmplx = function(pp, arg_r, arg_i) { var sin_arg_r = Math.sin(arg_r); var cos_arg_r = Math.cos(arg_r); var sinh_arg_i = sinh(arg_i); var cosh_arg_i = cosh(arg_i); var r = 2 * cos_arg_r * cosh_arg_i; var i = -2 * sin_arg_r * sinh_arg_i; var j = pp.length - 1; var hr = pp[j]; var hi1 = 0; var hr1 = 0; var hi = 0; var hr2; var hi2; while (--j >= 0) { hr2 = hr1; hi2 = hi1; hr1 = hr; hi1 = hi; hr = -hr2 + r * hr1 - i * hi1 + pp[j]; hi = -hi2 + i * hr1 + r * hi1; } r = sin_arg_r * cosh_arg_i; i = cos_arg_r * sinh_arg_i; return [r * hr - i * hi, r * hi + i * hr]; }; // Heavily based on this etmerc projection implementation // https://github.com/mbloch/mapshaper-proj/blob/master/src/projections/etmerc.js function init$3() { if (!this.approx && (isNaN(this.es) || this.es <= 0)) { throw new Error('Incorrect elliptical usage. Try using the +approx option in the proj string, or PROJECTION["Fast_Transverse_Mercator"] in the WKT.'); } if (this.approx) { // When '+approx' is set, use tmerc instead tmerc.init.apply(this); this.forward = tmerc.forward; this.inverse = tmerc.inverse; } this.x0 = this.x0 !== undefined ? this.x0 : 0; this.y0 = this.y0 !== undefined ? this.y0 : 0; this.long0 = this.long0 !== undefined ? this.long0 : 0; this.lat0 = this.lat0 !== undefined ? this.lat0 : 0; this.cgb = []; this.cbg = []; this.utg = []; this.gtu = []; var f = this.es / (1 + Math.sqrt(1 - this.es)); var n = f / (2 - f); var np = n; this.cgb[0] = n * (2 + n * (-2 / 3 + n * (-2 + n * (116 / 45 + n * (26 / 45 + n * (-2854 / 675 )))))); this.cbg[0] = n * (-2 + n * ( 2 / 3 + n * ( 4 / 3 + n * (-82 / 45 + n * (32 / 45 + n * (4642 / 4725)))))); np = np * n; this.cgb[1] = np * (7 / 3 + n * (-8 / 5 + n * (-227 / 45 + n * (2704 / 315 + n * (2323 / 945))))); this.cbg[1] = np * (5 / 3 + n * (-16 / 15 + n * ( -13 / 9 + n * (904 / 315 + n * (-1522 / 945))))); np = np * n; this.cgb[2] = np * (56 / 15 + n * (-136 / 35 + n * (-1262 / 105 + n * (73814 / 2835)))); this.cbg[2] = np * (-26 / 15 + n * (34 / 21 + n * (8 / 5 + n * (-12686 / 2835)))); np = np * n; this.cgb[3] = np * (4279 / 630 + n * (-332 / 35 + n * (-399572 / 14175))); this.cbg[3] = np * (1237 / 630 + n * (-12 / 5 + n * ( -24832 / 14175))); np = np * n; this.cgb[4] = np * (4174 / 315 + n * (-144838 / 6237)); this.cbg[4] = np * (-734 / 315 + n * (109598 / 31185)); np = np * n; this.cgb[5] = np * (601676 / 22275); this.cbg[5] = np * (444337 / 155925); np = Math.pow(n, 2); this.Qn = this.k0 / (1 + n) * (1 + np * (1 / 4 + np * (1 / 64 + np / 256))); this.utg[0] = n * (-0.5 + n * ( 2 / 3 + n * (-37 / 96 + n * ( 1 / 360 + n * (81 / 512 + n * (-96199 / 604800)))))); this.gtu[0] = n * (0.5 + n * (-2 / 3 + n * (5 / 16 + n * (41 / 180 + n * (-127 / 288 + n * (7891 / 37800)))))); this.utg[1] = np * (-1 / 48 + n * (-1 / 15 + n * (437 / 1440 + n * (-46 / 105 + n * (1118711 / 3870720))))); this.gtu[1] = np * (13 / 48 + n * (-3 / 5 + n * (557 / 1440 + n * (281 / 630 + n * (-1983433 / 1935360))))); np = np * n; this.utg[2] = np * (-17 / 480 + n * (37 / 840 + n * (209 / 4480 + n * (-5569 / 90720 )))); this.gtu[2] = np * (61 / 240 + n * (-103 / 140 + n * (15061 / 26880 + n * (167603 / 181440)))); np = np * n; this.utg[3] = np * (-4397 / 161280 + n * (11 / 504 + n * (830251 / 7257600))); this.gtu[3] = np * (49561 / 161280 + n * (-179 / 168 + n * (6601661 / 7257600))); np = np * n; this.utg[4] = np * (-4583 / 161280 + n * (108847 / 3991680)); this.gtu[4] = np * (34729 / 80640 + n * (-3418889 / 1995840)); np = np * n; this.utg[5] = np * (-20648693 / 638668800); this.gtu[5] = np * (212378941 / 319334400); var Z = gatg(this.cbg, this.lat0); this.Zb = -this.Qn * (Z + clens(this.gtu, 2 * Z)); } function forward$3(p) { var Ce = adjust_lon(p.x - this.long0); var Cn = p.y; Cn = gatg(this.cbg, Cn); var sin_Cn = Math.sin(Cn); var cos_Cn = Math.cos(Cn); var sin_Ce = Math.sin(Ce); var cos_Ce = Math.cos(Ce); Cn = Math.atan2(sin_Cn, cos_Ce * cos_Cn); Ce = Math.atan2(sin_Ce * cos_Cn, hypot(sin_Cn, cos_Cn * cos_Ce)); Ce = asinhy(Math.tan(Ce)); var tmp = clens_cmplx(this.gtu, 2 * Cn, 2 * Ce); Cn = Cn + tmp[0]; Ce = Ce + tmp[1]; var x; var y; if (Math.abs(Ce) <= 2.623395162778) { x = this.a * (this.Qn * Ce) + this.x0; y = this.a * (this.Qn * Cn + this.Zb) + this.y0; } else { x = Infinity; y = Infinity; } p.x = x; p.y = y; return p; } function inverse$3(p) { var Ce = (p.x - this.x0) * (1 / this.a); var Cn = (p.y - this.y0) * (1 / this.a); Cn = (Cn - this.Zb) / this.Qn; Ce = Ce / this.Qn; var lon; var lat; if (Math.abs(Ce) <= 2.623395162778) { var tmp = clens_cmplx(this.utg, 2 * Cn, 2 * Ce); Cn = Cn + tmp[0]; Ce = Ce + tmp[1]; Ce = Math.atan(sinh(Ce)); var sin_Cn = Math.sin(Cn); var cos_Cn = Math.cos(Cn); var sin_Ce = Math.sin(Ce); var cos_Ce = Math.cos(Ce); Cn = Math.atan2(sin_Cn * cos_Ce, hypot(sin_Ce, cos_Ce * cos_Cn)); Ce = Math.atan2(sin_Ce, cos_Ce * cos_Cn); lon = adjust_lon(Ce + this.long0); lat = gatg(this.cgb, Cn); } else { lon = Infinity; lat = Infinity; } p.x = lon; p.y = lat; return p; } var names$4 = ["Extended_Transverse_Mercator", "Extended Transverse Mercator", "etmerc", "Transverse_Mercator", "Transverse Mercator", "tmerc"]; var etmerc = { init: init$3, forward: forward$3, inverse: inverse$3, names: names$4 }; var adjust_zone = function(zone, lon) { if (zone === undefined) { zone = Math.floor((adjust_lon(lon) + Math.PI) * 30 / Math.PI) + 1; if (zone < 0) { return 0; } else if (zone > 60) { return 60; } } return zone; }; var dependsOn = 'etmerc'; function init$4() { var zone = adjust_zone(this.zone, this.long0); if (zone === undefined) { throw new Error('unknown utm zone'); } this.lat0 = 0; this.long0 = ((6 * Math.abs(zone)) - 183) * D2R; this.x0 = 500000; this.y0 = this.utmSouth ? 10000000 : 0; this.k0 = 0.9996; etmerc.init.apply(this); this.forward = etmerc.forward; this.inverse = etmerc.inverse; } var names$5 = ["Universal Transverse Mercator System", "utm"]; var utm = { init: init$4, names: names$5, dependsOn: dependsOn }; var srat = function(esinp, exp) { return (Math.pow((1 - esinp) / (1 + esinp), exp)); }; var MAX_ITER$1 = 20; function init$6() { var sphi = Math.sin(this.lat0); var cphi = Math.cos(this.lat0); cphi *= cphi; this.rc = Math.sqrt(1 - this.es) / (1 - this.es * sphi * sphi); this.C = Math.sqrt(1 + this.es * cphi * cphi / (1 - this.es)); this.phic0 = Math.asin(sphi / this.C); this.ratexp = 0.5 * this.C * this.e; this.K = Math.tan(0.5 * this.phic0 + FORTPI) / (Math.pow(Math.tan(0.5 * this.lat0 + FORTPI), this.C) * srat(this.e * sphi, this.ratexp)); } function forward$5(p) { var lon = p.x; var lat = p.y; p.y = 2 * Math.atan(this.K * Math.pow(Math.tan(0.5 * lat + FORTPI), this.C) * srat(this.e * Math.sin(lat), this.ratexp)) - HALF_PI; p.x = this.C * lon; return p; } function inverse$5(p) { var DEL_TOL = 1e-14; var lon = p.x / this.C; var lat = p.y; var num = Math.pow(Math.tan(0.5 * lat + FORTPI) / this.K, 1 / this.C); for (var i = MAX_ITER$1; i > 0; --i) { lat = 2 * Math.atan(num * srat(this.e * Math.sin(p.y), - 0.5 * this.e)) - HALF_PI; if (Math.abs(lat - p.y) < DEL_TOL) { break; } p.y = lat; } /* convergence failed */ if (!i) { return null; } p.x = lon; p.y = lat; return p; } var names$7 = ["gauss"]; var gauss = { init: init$6, forward: forward$5, inverse: inverse$5, names: names$7 }; function init$5() { gauss.init.apply(this); if (!this.rc) { return; } this.sinc0 = Math.sin(this.phic0); this.cosc0 = Math.cos(this.phic0); this.R2 = 2 * this.rc; if (!this.title) { this.title = "Oblique Stereographic Alternative"; } } function forward$4(p) { var sinc, cosc, cosl, k; p.x = adjust_lon(p.x - this.long0); gauss.forward.apply(this, [p]); sinc = Math.sin(p.y); cosc = Math.cos(p.y); cosl = Math.cos(p.x); k = this.k0 * this.R2 / (1 + this.sinc0 * sinc + this.cosc0 * cosc * cosl); p.x = k * cosc * Math.sin(p.x); p.y = k * (this.cosc0 * sinc - this.sinc0 * cosc * cosl); p.x = this.a * p.x + this.x0; p.y = this.a * p.y + this.y0; return p; } function inverse$4(p) { var sinc, cosc, lon, lat, rho; p.x = (p.x - this.x0) / this.a; p.y = (p.y - this.y0) / this.a; p.x /= this.k0; p.y /= this.k0; if ((rho = Math.sqrt(p.x * p.x + p.y * p.y))) { var c = 2 * Math.atan2(rho, this.R2); sinc = Math.sin(c); cosc = Math.cos(c); lat = Math.asin(cosc * this.sinc0 + p.y * sinc * this.cosc0 / rho); lon = Math.atan2(p.x * sinc, rho * this.cosc0 * cosc - p.y * this.sinc0 * sinc); } else { lat = this.phic0; lon = 0; } p.x = lon; p.y = lat; gauss.inverse.apply(this, [p]); p.x = adjust_lon(p.x + this.long0); return p; } var names$6 = ["Stereographic_North_Pole", "Oblique_Stereographic", "Polar_Stereographic", "sterea","Oblique Stereographic Alternative","Double_Stereographic"]; var sterea = { init: init$5, forward: forward$4, inverse: inverse$4, names: names$6 }; function ssfn_(phit, sinphi, eccen) { sinphi *= eccen; return (Math.tan(0.5 * (HALF_PI + phit)) * Math.pow((1 - sinphi) / (1 + sinphi), 0.5 * eccen)); } function init$7() { this.coslat0 = Math.cos(this.lat0); this.sinlat0 = Math.sin(this.lat0); if (this.sphere) { if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) { this.k0 = 0.5 * (1 + sign(this.lat0) * Math.sin(this.lat_ts)); } } else { if (Math.abs(this.coslat0) <= EPSLN) { if (this.lat0 > 0) { //North pole //trace('stere:north pole'); this.con = 1; } else { //South pole //trace('stere:south pole'); this.con = -1; } } this.cons = Math.sqrt(Math.pow(1 + this.e, 1 + this.e) * Math.pow(1 - this.e, 1 - this.e)); if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) { this.k0 = 0.5 * this.cons * msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts)) / tsfnz(this.e, this.con * this.lat_ts, this.con * Math.sin(this.lat_ts)); } this.ms1 = msfnz(this.e, this.sinlat0, this.coslat0); this.X0 = 2 * Math.atan(this.ssfn_(this.lat0, this.sinlat0, this.e)) - HALF_PI; this.cosX0 = Math.cos(this.X0); this.sinX0 = Math.sin(this.X0); } } // Stereographic forward equations--mapping lat,long to x,y function forward$6(p) { var lon = p.x; var lat = p.y; var sinlat = Math.sin(lat); var coslat = Math.cos(lat); var A, X, sinX, cosX, ts, rh; var dlon = adjust_lon(lon - this.long0); if (Math.abs(Math.abs(lon - this.long0) - Math.PI) <= EPSLN && Math.abs(lat + this.lat0) <= EPSLN) { //case of the origine point //trace('stere:this is the origin point'); p.x = NaN; p.y = NaN; return p; } if (this.sphere) { //trace('stere:sphere case'); A = 2 * this.k0 / (1 + this.sinlat0 * sinlat + this.coslat0 * coslat * Math.cos(dlon)); p.x = this.a * A * coslat * Math.sin(dlon) + this.x0; p.y = this.a * A * (this.coslat0 * sinlat - this.sinlat0 * coslat * Math.cos(dlon)) + this.y0; return p; } else { X = 2 * Math.atan(this.ssfn_(lat, sinlat, this.e)) - HALF_PI; cosX = Math.cos(X); sinX = Math.sin(X); if (Math.abs(this.coslat0) <= EPSLN) { ts = tsfnz(this.e, lat * this.con, this.con * sinlat); rh = 2 * this.a * this.k0 * ts / this.cons; p.x = this.x0 + rh * Math.sin(lon - this.long0); p.y = this.y0 - this.con * rh * Math.cos(lon - this.long0); //trace(p.toString()); return p; } else if (Math.abs(this.sinlat0) < EPSLN) { //Eq //trace('stere:equateur'); A = 2 * this.a * this.k0 / (1 + cosX * Math.cos(dlon)); p.y = A * sinX; } else { //other case //trace('stere:normal case'); A = 2 * this.a * this.k0 * this.ms1 / (this.cosX0 * (1 + this.sinX0 * sinX + this.cosX0 * cosX * Math.cos(dlon))); p.y = A * (this.cosX0 * sinX - this.sinX0 * cosX * Math.cos(dlon)) + this.y0; } p.x = A * cosX * Math.sin(dlon) + this.x0; } //trace(p.toString()); return p; } //* Stereographic inverse equations--mapping x,y to lat/long function inverse$6(p) { p.x -= this.x0; p.y -= this.y0; var lon, lat, ts, ce, Chi; var rh = Math.sqrt(p.x * p.x + p.y * p.y); if (this.sphere) { var c = 2 * Math.atan(rh / (2 * this.a * this.k0)); lon = this.long0; lat = this.lat0; if (rh <= EPSLN) { p.x = lon; p.y = lat; return p; } lat = Math.asin(Math.cos(c) * this.sinlat0 + p.y * Math.sin(c) * this.coslat0 / rh); if (Math.abs(this.coslat0) < EPSLN) { if (this.lat0 > 0) { lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y)); } else { lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y)); } } else { lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(c), rh * this.coslat0 * Math.cos(c) - p.y * this.sinlat0 * Math.sin(c))); } p.x = lon; p.y = lat; return p; } else { if (Math.abs(this.coslat0) <= EPSLN) { if (rh <= EPSLN) { lat = this.lat0; lon = this.long0; p.x = lon; p.y = lat; //trace(p.toString()); return p; } p.x *= this.con; p.y *= this.con; ts = rh * this.cons / (2 * this.a * this.k0); lat = this.con * phi2z(this.e, ts); lon = this.con * adjust_lon(this.con * this.long0 + Math.atan2(p.x, - 1 * p.y)); } else { ce = 2 * Math.atan(rh * this.cosX0 / (2 * this.a * this.k0 * this.ms1)); lon = this.long0; if (rh <= EPSLN) { Chi = this.X0; } else { Chi = Math.asin(Math.cos(ce) * this.sinX0 + p.y * Math.sin(ce) * this.cosX0 / rh); lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(ce), rh * this.cosX0 * Math.cos(ce) - p.y * this.sinX0 * Math.sin(ce))); } lat = -1 * phi2z(this.e, Math.tan(0.5 * (HALF_PI + Chi))); } } p.x = lon; p.y = lat; //trace(p.toString()); return p; } var names$8 = ["stere", "Stereographic_South_Pole", "Polar Stereographic (variant B)"]; var stere = { init: init$7, forward: forward$6, inverse: inverse$6, names: names$8, ssfn_: ssfn_ }; /* references: Formules et constantes pour le Calcul pour la projection cylindrique conforme à axe oblique et pour la transformation entre des systèmes de référence. http://www.swisstopo.admin.ch/internet/swisstopo/fr/home/topics/survey/sys/refsys/switzerland.parsysrelated1.31216.downloadList.77004.DownloadFile.tmp/swissprojectionfr.pdf */ function init$8() { var phy0 = this.lat0; this.lambda0 = this.long0; var sinPhy0 = Math.sin(phy0); var semiMajorAxis = this.a; var invF = this.rf; var flattening = 1 / invF; var e2 = 2 * flattening - Math.pow(flattening, 2); var e = this.e = Math.sqrt(e2); this.R = this.k0 * semiMajorAxis * Math.sqrt(1 - e2) / (1 - e2 * Math.pow(sinPhy0, 2)); this.alpha = Math.sqrt(1 + e2 / (1 - e2) * Math.pow(Math.cos(phy0), 4)); this.b0 = Math.asin(sinPhy0 / this.alpha); var k1 = Math.log(Math.tan(Math.PI / 4 + this.b0 / 2)); var k2 = Math.log(Math.tan(Math.PI / 4 + phy0 / 2)); var k3 = Math.log((1 + e * sinPhy0) / (1 - e * sinPhy0)); this.K = k1 - this.alpha * k2 + this.alpha * e / 2 * k3; } function forward$7(p) { var Sa1 = Math.log(Math.tan(Math.PI / 4 - p.y / 2)); var Sa2 = this.e / 2 * Math.log((1 + this.e * Math.sin(p.y)) / (1 - this.e * Math.sin(p.y))); var S = -this.alpha * (Sa1 + Sa2) + this.K; // spheric latitude var b = 2 * (Math.atan(Math.exp(S)) - Math.PI / 4); // spheric longitude var I = this.alpha * (p.x - this.lambda0); // psoeudo equatorial rotation var rotI = Math.atan(Math.sin(I) / (Math.sin(this.b0) * Math.tan(b) + Math.cos(this.b0) * Math.cos(I))); var rotB = Math.asin(Math.cos(this.b0) * Math.sin(b) - Math.sin(this.b0) * Math.cos(b) * Math.cos(I)); p.y = this.R / 2 * Math.log((1 + Math.sin(rotB)) / (1 - Math.sin(rotB))) + this.y0; p.x = this.R * rotI + this.x0; return p; } function inverse$7(p) { var Y = p.x - this.x0; var X = p.y - this.y0; var rotI = Y / this.R; var rotB = 2 * (Math.atan(Math.exp(X / this.R)) - Math.PI / 4); var b = Math.asin(Math.cos(this.b0) * Math.sin(rotB) + Math.sin(this.b0) * Math.cos(rotB) * Math.cos(rotI)); var I = Math.atan(Math.sin(rotI) / (Math.cos(this.b0) * Math.cos(rotI) - Math.sin(this.b0) * Math.tan(rotB))); var lambda = this.lambda0 + I / this.alpha; var S = 0; var phy = b; var prevPhy = -1000; var iteration = 0; while (Math.abs(phy - prevPhy) > 0.0000001) { if (++iteration > 20) { //...reportError("omercFwdInfinity"); return; } //S = Math.log(Math.tan(Math.PI / 4 + phy / 2)); S = 1 / this.alpha * (Math.log(Math.tan(Math.PI / 4 + b / 2)) - this.K) + this.e * Math.log(Math.tan(Math.PI / 4 + Math.asin(this.e * Math.sin(phy)) / 2)); prevPhy = phy; phy = 2 * Math.atan(Math.exp(S)) - Math.PI / 2; } p.x = lambda; p.y = phy; return p; } var names$9 = ["somerc"]; var somerc = { init: init$8, forward: forward$7, inverse: inverse$7, names: names$9 }; var TOL = 1e-7; function isTypeA(P) { var typeAProjections = ['Hotine_Oblique_Mercator','Hotine_Oblique_Mercator_Azimuth_Natural_Origin']; var projectionName = typeof P.PROJECTION === "object" ? Object.keys(P.PROJECTION)[0] : P.PROJECTION; return 'no_uoff' in P || 'no_off' in P || typeAProjections.indexOf(projectionName) !== -1; } /* Initialize the Oblique Mercator projection ------------------------------------------*/ function init$9() { var con, com, cosph0, D, F, H, L, sinph0, p, J, gamma = 0, gamma0, lamc = 0, lam1 = 0, lam2 = 0, phi1 = 0, phi2 = 0, alpha_c = 0; // only Type A uses the no_off or no_uoff property // https://github.com/OSGeo/proj.4/issues/104 this.no_off = isTypeA(this); this.no_rot = 'no_rot' in this; var alp = false; if ("alpha" in this) { alp = true; } var gam = false; if ("rectified_grid_angle" in this) { gam = true; } if (alp) { alpha_c = this.alpha; } if (gam) { gamma = (this.rectified_grid_angle * D2R); } if (alp || gam) { lamc = this.longc; } else { lam1 = this.long1; phi1 = this.lat1; lam2 = this.long2; phi2 = this.lat2; if (Math.abs(phi1 - phi2) <= TOL || (con = Math.abs(phi1)) <= TOL || Math.abs(con - HALF_PI) <= TOL || Math.abs(Math.abs(this.lat0) - HALF_PI) <= TOL || Math.abs(Math.abs(phi2) - HALF_PI) <= TOL) { throw new Error(); } } var one_es = 1.0 - this.es; com = Math.sqrt(one_es); if (Math.abs(this.lat0) > EPSLN) { sinph0 = Math.sin(this.lat0); cosph0 = Math.cos(this.lat0); con = 1 - this.es * sinph0 * sinph0; this.B = cosph0 * cosph0; this.B = Math.sqrt(1 + this.es * this.B * this.B / one_es); this.A = this.B * this.k0 * com / con; D = this.B * com / (cosph0 * Math.sqrt(con)); F = D * D -1; if (F <= 0) { F = 0; } else { F = Math.sqrt(F); if (this.lat0 < 0) { F = -F; } } this.E = F += D; this.E *= Math.pow(tsfnz(this.e, this.lat0, sinph0), this.B); } else { this.B = 1 / com; this.A = this.k0; this.E = D = F = 1; } if (alp || gam) { if (alp) { gamma0 = Math.asin(Math.sin(alpha_c) / D); if (!gam) { gamma = alpha_c; } } else { gamma0 = gamma; alpha_c = Math.asin(D * Math.sin(gamma0)); } this.lam0 = lamc - Math.asin(0.5 * (F - 1 / F) * Math.tan(gamma0)) / this.B; } else { H = Math.pow(tsfnz(this.e, phi1, Math.sin(phi1)), this.B); L = Math.pow(tsfnz(this.e, phi2, Math.sin(phi2)), this.B); F = this.E / H; p = (L - H) / (L + H); J = this.E * this.E; J = (J - L * H) / (J + L * H); con = lam1 - lam2; if (con < -Math.pi) { lam2 -=TWO_PI; } else if (con > Math.pi) { lam2 += TWO_PI; } this.lam0 = adjust_lon(0.5 * (lam1 + lam2) - Math.atan(J * Math.tan(0.5 * this.B * (lam1 - lam2)) / p) / this.B); gamma0 = Math.atan(2 * Math.sin(this.B * adjust_lon(lam1 - this.lam0)) / (F - 1 / F)); gamma = alpha_c = Math.asin(D * Math.sin(gamma0)); } this.singam = Math.sin(gamma0); this.cosgam = Math.cos(gamma0); this.sinrot = Math.sin(gamma); this.cosrot = Math.cos(gamma); this.rB = 1 / this.B; this.ArB = this.A * this.rB; this.BrA = 1 / this.ArB; if (this.no_off) { this.u_0 = 0; } else { this.u_0 = Math.abs(this.ArB * Math.atan(Math.sqrt(D * D - 1) / Math.cos(alpha_c))); if (this.lat0 < 0) { this.u_0 = - this.u_0; } } F = 0.5 * gamma0; this.v_pole_n = this.ArB * Math.log(Math.tan(FORTPI - F)); this.v_pole_s = this.ArB * Math.log(Math.tan(FORTPI + F)); } /* Oblique Mercator forward equations--mapping lat,long to x,y ----------------------------------------------------------*/ function forward$8(p) { var coords = {}; var S, T, U, V, W, temp, u, v; p.x = p.x - this.lam0; if (Math.abs(Math.abs(p.y) - HALF_PI) > EPSLN) { W = this.E / Math.pow(tsfnz(this.e, p.y, Math.sin(p.y)), this.B); temp = 1 / W; S = 0.5 * (W - temp); T = 0.5 * (W + temp); V = Math.sin(this.B * p.x); U = (S * this.singam - V * this.cosgam) / T; if (Math.abs(Math.abs(U) - 1.0) < EPSLN) { throw new Error(); } v = 0.5 * this.ArB * Math.log((1 - U)/(1 + U)); temp = Math.cos(this.B * p.x); if (Math.abs(temp) < TOL) { u = this.A * p.x; } else { u = this.ArB * Math.atan2((S * this.cosgam + V * this.singam), temp); } } else { v = p.y > 0 ? this.v_pole_n : this.v_pole_s; u = this.ArB * p.y; } if (this.no_rot) { coords.x = u; coords.y = v; } else { u -= this.u_0; coords.x = v * this.cosrot + u * this.sinrot; coords.y = u * this.cosrot - v * this.sinrot; } coords.x = (this.a * coords.x + this.x0); coords.y = (this.a * coords.y + this.y0); return coords; } function inverse$8(p) { var u, v, Qp, Sp, Tp, Vp, Up; var coords = {}; p.x = (p.x - this.x0) * (1.0 / this.a); p.y = (p.y - this.y0) * (1.0 / this.a); if (this.no_rot) { v = p.y; u = p.x; } else { v = p.x * this.cosrot - p.y * this.sinrot; u = p.y * this.cosrot + p.x * this.sinrot + this.u_0; } Qp = Math.exp(-this.BrA * v); Sp = 0.5 * (Qp - 1 / Qp); Tp = 0.5 * (Qp + 1 / Qp); Vp = Math.sin(this.BrA * u); Up = (Vp * this.cosgam + Sp * this.singam) / Tp; if (Math.abs(Math.abs(Up) - 1) < EPSLN) { coords.x = 0; coords.y = Up < 0 ? -HALF_PI : HALF_PI; } else { coords.y = this.E / Math.sqrt((1 + Up) / (1 - Up)); coords.y = phi2z(this.e, Math.pow(coords.y, 1 / this.B)); if (coords.y === Infinity) { throw new Error(); } coords.x = -this.rB * Math.atan2((Sp * this.cosgam - Vp * this.singam), Math.cos(this.BrA * u)); } coords.x += this.lam0; return coords; } var names$10 = ["Hotine_Oblique_Mercator", "Hotine Oblique Mercator", "Hotine_Oblique_Mercator_Azimuth_Natural_Origin", "Hotine_Oblique_Mercator_Two_Point_Natural_Origin", "Hotine_Oblique_Mercator_Azimuth_Center", "Oblique_Mercator", "omerc"]; var omerc = { init: init$9, forward: forward$8, inverse: inverse$8, names: names$10 }; function init$10() { //double lat0; /* the reference latitude */ //double long0; /* the reference longitude */ //double lat1; /* first standard parallel */ //double lat2; /* second standard parallel */ //double r_maj; /* major axis */ //double r_min; /* minor axis */ //double false_east; /* x offset in meters */ //double false_north; /* y offset in meters */ //the above value can be set with proj4.defs //example: proj4.defs("EPSG:2154","+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"); if (!this.lat2) { this.lat2 = this.lat1; } //if lat2 is not defined if (!this.k0) { this.k0 = 1; } this.x0 = this.x0 || 0; this.y0 = this.y0 || 0; // Standard Parallels cannot be equal and on opposite sides of the equator if (Math.abs(this.lat1 + this.lat2) < EPSLN) { return; } var temp = this.b / this.a; this.e = Math.sqrt(1 - temp * temp); var sin1 = Math.sin(this.lat1); var cos1 = Math.cos(this.lat1); var ms1 = msfnz(this.e, sin1, cos1); var ts1 = tsfnz(this.e, this.lat1, sin1); var sin2 = Math.sin(this.lat2); var cos2 = Math.cos(this.lat2); var ms2 = msfnz(this.e, sin2, cos2); var ts2 = tsfnz(this.e, this.lat2, sin2); var ts0 = tsfnz(this.e, this.lat0, Math.sin(this.lat0)); if (Math.abs(this.lat1 - this.lat2) > EPSLN) { this.ns = Math.log(ms1 / ms2) / Math.log(ts1 / ts2); } else { this.ns = sin1; } if (isNaN(this.ns)) { this.ns = sin1; } this.f0 = ms1 / (this.ns * Math.pow(ts1, this.ns)); this.rh = this.a * this.f0 * Math.pow(ts0, this.ns); if (!this.title) { this.title = "Lambert Conformal Conic"; } } // Lambert Conformal conic forward equations--mapping lat,long to x,y // ----------------------------------------------------------------- function forward$9(p) { var lon = p.x; var lat = p.y; // singular cases : if (Math.abs(2 * Math.abs(lat) - Math.PI) <= EPSLN) { lat = sign(lat) * (HALF_PI - 2 * EPSLN); } var con = Math.abs(Math.abs(lat) - HALF_PI); var ts, rh1; if (con > EPSLN) { ts = tsfnz(this.e, lat, Math.sin(lat)); rh1 = this.a * this.f0 * Math.pow(ts, this.ns); } else { con = lat * this.ns; if (con <= 0) { return null; } rh1 = 0; } var theta = this.ns * adjust_lon(lon - this.long0); p.x = this.k0 * (rh1 * Math.sin(theta)) + this.x0; p.y = this.k0 * (this.rh - rh1 * Math.cos(theta)) + this.y0; return p; } // Lambert Conformal Conic inverse equations--mapping x,y to lat/long // ----------------------------------------------------------------- function inverse$9(p) { var rh1, con, ts; var lat, lon; var x = (p.x - this.x0) / this.k0; var y = (this.rh - (p.y - this.y0) / this.k0); if (this.ns > 0) { rh1 = Math.sqrt(x * x + y * y); con = 1; } else { rh1 = -Math.sqrt(x * x + y * y); con = -1; } var theta = 0; if (rh1 !== 0) { theta = Math.atan2((con * x), (con * y)); } if ((rh1 !== 0) || (this.ns > 0)) { con = 1 / this.ns; ts = Math.pow((rh1 / (this.a * this.f0)), con); lat = phi2z(this.e, ts); if (lat === -9999) { return null; } } else { lat = -HALF_PI; } lon = adjust_lon(theta / this.ns + this.long0); p.x = lon; p.y = lat; return p; } var names$11 = [ "Lambert Tangential Conformal Conic Projection", "Lambert_Conformal_Conic", "Lambert_Conformal_Conic_1SP", "Lambert_Conformal_Conic_2SP", "lcc", "Lambert Conic Conformal (1SP)", "Lambert Conic Conformal (2SP)" ]; var lcc = { init: init$10, forward: forward$9, inverse: inverse$9, names: names$11 }; function init$11() { this.a = 6377397.155; this.es = 0.006674372230614; this.e = Math.sqrt(this.es); if (!this.lat0) { this.lat0 = 0.863937979737193; } if (!this.long0) { this.long0 = 0.7417649320975901 - 0.308341501185665; } /* if scale not set default to 0.9999 */ if (!this.k0) { this.k0 = 0.9999; } this.s45 = 0.785398163397448; /* 45 */ this.s90 = 2 * this.s45; this.fi0 = this.lat0; this.e2 = this.es; this.e = Math.sqrt(this.e2); this.alfa = Math.sqrt(1 + (this.e2 * Math.pow(Math.cos(this.fi0), 4)) / (1 - this.e2)); this.uq = 1.04216856380474; this.u0 = Math.asin(Math.sin(this.fi0) / this.alfa); this.g = Math.pow((1 + this.e * Math.sin(this.fi0)) / (1 - this.e * Math.sin(this.fi0)), this.alfa * this.e / 2); this.k = Math.tan(this.u0 / 2 + this.s45) / Math.pow(Math.tan(this.fi0 / 2 + this.s45), this.alfa) * this.g; this.k1 = this.k0; this.n0 = this.a * Math.sqrt(1 - this.e2) / (1 - this.e2 * Math.pow(Math.sin(this.fi0), 2)); this.s0 = 1.37008346281555; this.n = Math.sin(this.s0); this.ro0 = this.k1 * this.n0 / Math.tan(this.s0); this.ad = this.s90 - this.uq; } /* ellipsoid */ /* calculate xy from lat/lon */ /* Constants, identical to inverse transform function */ function forward$10(p) { var gfi, u, deltav, s, d, eps, ro; var lon = p.x; var lat = p.y; var delta_lon = adjust_lon(lon - this.long0); /* Transformation */ gfi = Math.pow(((1 + this.e * Math.sin(lat)) / (1 - this.e * Math.sin(lat))), (this.alfa * this.e / 2)); u = 2 * (Math.atan(this.k * Math.pow(Math.tan(lat / 2 + this.s45), this.alfa) / gfi) - this.s45); deltav = -delta_lon * this.alfa; s = Math.asin(Math.cos(this.ad) * Math.sin(u) + Math.sin(this.ad) * Math.cos(u) * Math.cos(deltav)); d = Math.asin(Math.cos(u) * Math.sin(deltav) / Math.cos(s)); eps = this.n * d; ro = this.ro0 * Math.pow(Math.tan(this.s0 / 2 + this.s45), this.n) / Math.pow(Math.tan(s / 2 + this.s45), this.n); p.y = ro * Math.cos(eps) / 1; p.x = ro * Math.sin(eps) / 1; if (!this.czech) { p.y *= -1; p.x *= -1; } return (p); } /* calculate lat/lon from xy */ function inverse$10(p) { var u, deltav, s, d, eps, ro, fi1; var ok; /* Transformation */ /* revert y, x*/ var tmp = p.x; p.x = p.y; p.y = tmp; if (!this.czech) { p.y *= -1; p.x *= -1; } ro = Math.sqrt(p.x * p.x + p.y * p.y); eps = Math.atan2(p.y, p.x); d = eps / Math.sin(this.s0); s = 2 * (Math.atan(Math.pow(this.ro0 / ro, 1 / this.n) * Math.tan(this.s0 / 2 + this.s45)) - this.s45); u = Math.asin(Math.cos(this.ad) * Math.sin(s) - Math.sin(this.ad) * Math.cos(s) * Math.cos(d)); deltav = Math.asin(Math.cos(s) * Math.sin(d) / Math.cos(u)); p.x = this.long0 - deltav / this.alfa; fi1 = u; ok = 0; var iter = 0; do { p.y = 2 * (Math.atan(Math.pow(this.k, - 1 / this.alfa) * Math.pow(Math.tan(u / 2 + this.s45), 1 / this.alfa) * Math.pow((1 + this.e * Math.sin(fi1)) / (1 - this.e * Math.sin(fi1)), this.e / 2)) - this.s45); if (Math.abs(fi1 - p.y) < 0.0000000001) { ok = 1; } fi1 = p.y; iter += 1; } while (ok === 0 && iter < 15); if (iter >= 15) { return null; } return (p); } var names$12 = ["Krovak", "krovak"]; var krovak = { init: init$11, forward: forward$10, inverse: inverse$10, names: names$12 }; var mlfn = function(e0, e1, e2, e3, phi) { return (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi)); }; var e0fn = function(x) { return (1 - 0.25 * x * (1 + x / 16 * (3 + 1.25 * x))); }; var e1fn = function(x) { return (0.375 * x * (1 + 0.25 * x * (1 + 0.46875 * x))); }; var e2fn = function(x) { return (0.05859375 * x * x * (1 + 0.75 * x)); }; var e3fn = function(x) { return (x * x * x * (35 / 3072)); }; var gN = function(a, e, sinphi) { var temp = e * sinphi; return a / Math.sqrt(1 - temp * temp); }; var adjust_lat = function(x) { return (Math.abs(x) < HALF_PI) ? x : (x - (sign(x) * Math.PI)); }; var imlfn = function(ml, e0, e1, e2, e3) { var phi; var dphi; phi = ml / e0; for (var i = 0; i < 15; i++) { dphi = (ml - (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi))) / (e0 - 2 * e1 * Math.cos(2 * phi) + 4 * e2 * Math.cos(4 * phi) - 6 * e3 * Math.cos(6 * phi)); phi += dphi; if (Math.abs(dphi) <= 0.0000000001) { return phi; } } //..reportError("IMLFN-CONV:Latitude failed to converge after 15 iterations"); return NaN; }; function init$12() { if (!this.sphere) { this.e0 = e0fn(this.es); this.e1 = e1fn(this.es); this.e2 = e2fn(this.es); this.e3 = e3fn(this.es); this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0); } } /* Cassini forward equations--mapping lat,long to x,y -----------------------------------------------------------------------*/ function forward$11(p) { /* Forward equations -----------------*/ var x, y; var lam = p.x; var phi = p.y; lam = adjust_lon(lam - this.long0); if (this.sphere) { x = this.a * Math.asin(Math.cos(phi) * Math.sin(lam)); y = this.a * (Math.atan2(Math.tan(phi), Math.cos(lam)) - this.lat0); } else { //ellipsoid var sinphi = Math.sin(phi); var cosphi = Math.cos(phi); var nl = gN(this.a, this.e, sinphi); var tl = Math.tan(phi) * Math.tan(phi); var al = lam * Math.cos(phi); var asq = al * al; var cl = this.es * cosphi * cosphi / (1 - this.es); var ml = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi); x = nl * al * (1 - asq * tl * (1 / 6 - (8 - tl + 8 * cl) * asq / 120)); y = ml - this.ml0 + nl * sinphi / cosphi * asq * (0.5 + (5 - tl + 6 * cl) * asq / 24); } p.x = x + this.x0; p.y = y + this.y0; return p; } /* Inverse equations -----------------*/ function inverse$11(p) { p.x -= this.x0; p.y -= this.y0; var x = p.x / this.a; var y = p.y / this.a; var phi, lam; if (this.sphere) { var dd = y + this.lat0; phi = Math.asin(Math.sin(dd) * Math.cos(x)); lam = Math.atan2(Math.tan(x), Math.cos(dd)); } else { /* ellipsoid */ var ml1 = this.ml0 / this.a + y; var phi1 = imlfn(ml1, this.e0, this.e1, this.e2, this.e3); if (Math.abs(Math.abs(phi1) - HALF_PI) <= EPSLN) { p.x = this.long0; p.y = HALF_PI; if (y < 0) { p.y *= -1; } return p; } var nl1 = gN(this.a, this.e, Math.sin(phi1)); var rl1 = nl1 * nl1 * nl1 / this.a / this.a * (1 - this.es); var tl1 = Math.pow(Math.tan(phi1), 2); var dl = x * this.a / nl1; var dsq = dl * dl; phi = phi1 - nl1 * Math.tan(phi1) / rl1 * dl * dl * (0.5 - (1 + 3 * tl1) * dl * dl / 24); lam = dl * (1 - dsq * (tl1 / 3 + (1 + 3 * tl1) * tl1 * dsq / 15)) / Math.cos(phi1); } p.x = adjust_lon(lam + this.long0); p.y = adjust_lat(phi); return p; } var names$13 = ["Cassini", "Cassini_Soldner", "cass"]; var cass = { init: init$12, forward: forward$11, inverse: inverse$11, names: names$13 }; var qsfnz = function(eccent, sinphi) { var con; if (eccent > 1.0e-7) { con = eccent * sinphi; return ((1 - eccent * eccent) * (sinphi / (1 - con * con) - (0.5 / eccent) * Math.log((1 - con) / (1 + con)))); } else { return (2 * sinphi); } }; /* reference "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder, The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355. */ var S_POLE = 1; var N_POLE = 2; var EQUIT = 3; var OBLIQ = 4; /* Initialize the Lambert Azimuthal Equal Area projection ------------------------------------------------------*/ function init$13() { var t = Math.abs(this.lat0); if (Math.abs(t - HALF_PI) < EPSLN) { this.mode = this.lat0 < 0 ? this.S_POLE : this.N_POLE; } else if (Math.abs(t) < EPSLN) { this.mode = this.EQUIT; } else { this.mode = this.OBLIQ; } if (this.es > 0) { var sinphi; this.qp = qsfnz(this.e, 1); this.mmf = 0.5 / (1 - this.es); this.apa = authset(this.es); switch (this.mode) { case this.N_POLE: this.dd = 1; break; case this.S_POLE: this.dd = 1; break; case this.EQUIT: this.rq = Math.sqrt(0.5 * this.qp); this.dd = 1 / this.rq; this.xmf = 1; this.ymf = 0.5 * this.qp; break; case this.OBLIQ: this.rq = Math.sqrt(0.5 * this.qp); sinphi = Math.sin(this.lat0); this.sinb1 = qsfnz(this.e, sinphi) / this.qp; this.cosb1 = Math.sqrt(1 - this.sinb1 * this.sinb1); this.dd = Math.cos(this.lat0) / (Math.sqrt(1 - this.es * sinphi * sinphi) * this.rq * this.cosb1); this.ymf = (this.xmf = this.rq) / this.dd; this.xmf *= this.dd; break; } } else { if (this.mode === this.OBLIQ) { this.sinph0 = Math.sin(this.lat0); this.cosph0 = Math.cos(this.lat0); } } } /* Lambert Azimuthal Equal Area forward equations--mapping lat,long to x,y -----------------------------------------------------------------------*/ function forward$12(p) { /* Forward equations -----------------*/ var x, y, coslam, sinlam, sinphi, q, sinb, cosb, b, cosphi; var lam = p.x; var phi = p.y; lam = adjust_lon(lam - this.long0); if (this.sphere) { sinphi = Math.sin(phi); cosphi = Math.cos(phi); coslam = Math.cos(lam); if (this.mode === this.OBLIQ || this.mode === this.EQUIT) { y = (this.mode === this.EQUIT) ? 1 + cosphi * coslam : 1 + this.sinph0 * sinphi + this.cosph0 * cosphi * coslam; if (y <= EPSLN) { return null; } y = Math.sqrt(2 / y); x = y * cosphi * Math.sin(lam); y *= (this.mode === this.EQUIT) ? sinphi : this.cosph0 * sinphi - this.sinph0 * cosphi * coslam; } else if (this.mode === this.N_POLE || this.mode === this.S_POLE) { if (this.mode === this.N_POLE) { coslam = -coslam; } if (Math.abs(phi + this.lat0) < EPSLN) { return null; } y = FORTPI - phi * 0.5; y = 2 * ((this.mode === this.S_POLE) ? Math.cos(y) : Math.sin(y)); x = y * Math.sin(lam); y *= coslam; } } else { sinb = 0; cosb = 0; b = 0; coslam = Math.cos(lam); sinlam = Math.sin(lam); sinphi = Math.sin(phi); q = qsfnz(this.e, sinphi); if (this.mode === this.OBLIQ || this.mode === this.EQUIT) { sinb = q / this.qp; cosb = Math.sqrt(1 - sinb * sinb); } switch (this.mode) { case this.OBLIQ: b = 1 + this.sinb1 * sinb + this.cosb1 * cosb * coslam; break; case this.EQUIT: b = 1 + cosb * coslam; break; case this.N_POLE: b = HALF_PI + phi; q = this.qp - q; break; case this.S_POLE: b = phi - HALF_PI; q = this.qp + q; break; } if (Math.abs(b) < EPSLN) { return null; } switch (this.mode) { case this.OBLIQ: case this.EQUIT: b = Math.sqrt(2 / b); if (this.mode === this.OBLIQ) { y = this.ymf * b * (this.cosb1 * sinb - this.sinb1 * cosb * coslam); } else { y = (b = Math.sqrt(2 / (1 + cosb * coslam))) * sinb * this.ymf; } x = this.xmf * b * cosb * sinlam; break; case this.N_POLE: case this.S_POLE: if (q >= 0) { x = (b = Math.sqrt(q)) * sinlam; y = coslam * ((this.mode === this.S_POLE) ? b : -b); } else { x = y = 0; } break; } } p.x = this.a * x + this.x0; p.y = this.a * y + this.y0; return p; } /* Inverse equations -----------------*/ function inverse$12(p) { p.x -= this.x0; p.y -= this.y0; var x = p.x / this.a; var y = p.y / this.a; var lam, phi, cCe, sCe, q, rho, ab; if (this.sphere) { var cosz = 0, rh, sinz = 0; rh = Math.sqrt(x * x + y * y); phi = rh * 0.5; if (phi > 1) { return null; } phi = 2 * Math.asin(phi); if (this.mode === this.OBLIQ || this.mode === this.EQUIT) { sinz = Math.sin(phi); cosz = Math.cos(phi); } switch (this.mode) { case this.EQUIT: phi = (Math.abs(rh) <= EPSLN) ? 0 : Math.asin(y * sinz / rh); x *= sinz; y = cosz * rh; break; case this.OBLIQ: phi = (Math.abs(rh) <= EPSLN) ? this.lat0 : Math.asin(cosz * this.sinph0 + y * sinz * this.cosph0 / rh); x *= sinz * this.cosph0; y = (cosz - Math.sin(phi) * this.sinph0) * rh; break; case this.N_POLE: y = -y; phi = HALF_PI - phi; break; case this.S_POLE: phi -= HALF_PI; break; } lam = (y === 0 && (this.mode === this.EQUIT || this.mode === this.OBLIQ)) ? 0 : Math.atan2(x, y); } else { ab = 0; if (this.mode === this.OBLIQ || this.mode === this.EQUIT) { x /= this.dd; y *= this.dd; rho = Math.sqrt(x * x + y * y); if (rho < EPSLN) { p.x = this.long0; p.y = this.lat0; return p; } sCe = 2 * Math.asin(0.5 * rho / this.rq); cCe = Math.cos(sCe); x *= (sCe = Math.sin(sCe)); if (this.mode === this.OBLIQ) { ab = cCe * this.sinb1 + y * sCe * this.cosb1 / rho; q = this.qp * ab; y = rho * this.cosb1 * cCe - y * this.sinb1 * sCe; } else { ab = y * sCe / rho; q = this.qp * ab; y = rho * cCe; } } else if (this.mode === this.N_POLE || this.mode === this.S_POLE) { if (this.mode === this.N_POLE) { y = -y; } q = (x * x + y * y); if (!q) { p.x = this.long0; p.y = this.lat0; return p; } ab = 1 - q / this.qp; if (this.mode === this.S_POLE) { ab = -ab; } } lam = Math.atan2(x, y); phi = authlat(Math.asin(ab), this.apa); } p.x = adjust_lon(this.long0 + lam); p.y = phi; return p; } /* determine latitude from authalic latitude */ var P00 = 0.33333333333333333333; var P01 = 0.17222222222222222222; var P02 = 0.10257936507936507936; var P10 = 0.06388888888888888888; var P11 = 0.06640211640211640211; var P20 = 0.01641501294219154443; function authset(es) { var t; var APA = []; APA[0] = es * P00; t = es * es; APA[0] += t * P01; APA[1] = t * P10; t *= es; APA[0] += t * P02; APA[1] += t * P11; APA[2] = t * P20; return APA; } function authlat(beta, APA) { var t = beta + beta; return (beta + APA[0] * Math.sin(t) + APA[1] * Math.sin(t + t) + APA[2] * Math.sin(t + t + t)); } var names$14 = ["Lambert Azimuthal Equal Area", "Lambert_Azimuthal_Equal_Area", "laea"]; var laea = { init: init$13, forward: forward$12, inverse: inverse$12, names: names$14, S_POLE: S_POLE, N_POLE: N_POLE, EQUIT: EQUIT, OBLIQ: OBLIQ }; var asinz = function(x) { if (Math.abs(x) > 1) { x = (x > 1) ? 1 : -1; } return Math.asin(x); }; function init$14() { if (Math.abs(this.lat1 + this.lat2) < EPSLN) { return; } this.temp = this.b / this.a; this.es = 1 - Math.pow(this.temp, 2); this.e3 = Math.sqrt(this.es); this.sin_po = Math.sin(this.lat1); this.cos_po = Math.cos(this.lat1); this.t1 = this.sin_po; this.con = this.sin_po; this.ms1 = msfnz(this.e3, this.sin_po, this.cos_po); this.qs1 = qsfnz(this.e3, this.sin_po); this.sin_po = Math.sin(this.lat2); this.cos_po = Math.cos(this.lat2); this.t2 = this.sin_po; this.ms2 = msfnz(this.e3, this.sin_po, this.cos_po); this.qs2 = qsfnz(this.e3, this.sin_po); this.sin_po = Math.sin(this.lat0); this.cos_po = Math.cos(this.lat0); this.t3 = this.sin_po; this.qs0 = qsfnz(this.e3, this.sin_po); if (Math.abs(this.lat1 - this.lat2) > EPSLN) { this.ns0 = (this.ms1 * this.ms1 - this.ms2 * this.ms2) / (this.qs2 - this.qs1); } else { this.ns0 = this.con; } this.c = this.ms1 * this.ms1 + this.ns0 * this.qs1; this.rh = this.a * Math.sqrt(this.c - this.ns0 * this.qs0) / this.ns0; } /* Albers Conical Equal Area forward equations--mapping lat,long to x,y -------------------------------------------------------------------*/ function forward$13(p) { var lon = p.x; var lat = p.y; this.sin_phi = Math.sin(lat); this.cos_phi = Math.cos(lat); var qs = qsfnz(this.e3, this.sin_phi); var rh1 = this.a * Math.sqrt(this.c - this.ns0 * qs) / this.ns0; var theta = this.ns0 * adjust_lon(lon - this.long0); var x = rh1 * Math.sin(theta) + this.x0; var y = this.rh - rh1 * Math.cos(theta) + this.y0; p.x = x; p.y = y; return p; } function inverse$13(p) { var rh1, qs, con, theta, lon, lat; p.x -= this.x0; p.y = this.rh - p.y + this.y0; if (this.ns0 >= 0) { rh1 = Math.sqrt(p.x * p.x + p.y * p.y); con = 1; } else { rh1 = -Math.sqrt(p.x * p.x + p.y * p.y); con = -1; } theta = 0; if (rh1 !== 0) { theta = Math.atan2(con * p.x, con * p.y); } con = rh1 * this.ns0 / this.a; if (this.sphere) { lat = Math.asin((this.c - con * con) / (2 * this.ns0)); } else { qs = (this.c - con * con) / this.ns0; lat = this.phi1z(this.e3, qs); } lon = adjust_lon(theta / this.ns0 + this.long0); p.x = lon; p.y = lat; return p; } /* Function to compute phi1, the latitude for the inverse of the Albers Conical Equal-Area projection. -------------------------------------------*/ function phi1z(eccent, qs) { var sinphi, cosphi, con, com, dphi; var phi = asinz(0.5 * qs); if (eccent < EPSLN) { return phi; } var eccnts = eccent * eccent; for (var i = 1; i <= 25; i++) { sinphi = Math.sin(phi); cosphi = Math.cos(phi); con = eccent * sinphi; com = 1 - con * con; dphi = 0.5 * com * com / cosphi * (qs / (1 - eccnts) - sinphi / com + 0.5 / eccent * Math.log((1 - con) / (1 + con))); phi = phi + dphi; if (Math.abs(dphi) <= 1e-7) { return phi; } } return null; } var names$15 = ["Albers_Conic_Equal_Area", "Albers", "aea"]; var aea = { init: init$14, forward: forward$13, inverse: inverse$13, names: names$15, phi1z: phi1z }; /* reference: Wolfram Mathworld "Gnomonic Projection" http://mathworld.wolfram.com/GnomonicProjection.html Accessed: 12th November 2009 */ function init$15() { /* Place parameters in static storage for common use -------------------------------------------------*/ this.sin_p14 = Math.sin(this.lat0); this.cos_p14 = Math.cos(this.lat0); // Approximation for projecting points to the horizon (infinity) this.infinity_dist = 1000 * this.a; this.rc = 1; } /* Gnomonic forward equations--mapping lat,long to x,y ---------------------------------------------------*/ function forward$14(p) { var sinphi, cosphi; /* sin and cos value */ var dlon; /* delta longitude value */ var coslon; /* cos of longitude */ var ksp; /* scale factor */ var g; var x, y; var lon = p.x; var lat = p.y; /* Forward equations -----------------*/ dlon = adjust_lon(lon - this.long0); sinphi = Math.sin(lat); cosphi = Math.cos(lat); coslon = Math.cos(dlon); g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon; ksp = 1; if ((g > 0) || (Math.abs(g) <= EPSLN)) { x = this.x0 + this.a * ksp * cosphi * Math.sin(dlon) / g; y = this.y0 + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon) / g; } else { // Point is in the opposing hemisphere and is unprojectable // We still need to return a reasonable point, so we project // to infinity, on a bearing // equivalent to the northern hemisphere equivalent // This is a reasonable approximation for short shapes and lines that // straddle the horizon. x = this.x0 + this.infinity_dist * cosphi * Math.sin(dlon); y = this.y0 + this.infinity_dist * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon); } p.x = x; p.y = y; return p; } function inverse$14(p) { var rh; /* Rho */ var sinc, cosc; var c; var lon, lat; /* Inverse equations -----------------*/ p.x = (p.x - this.x0) / this.a; p.y = (p.y - this.y0) / this.a; p.x /= this.k0; p.y /= this.k0; if ((rh = Math.sqrt(p.x * p.x + p.y * p.y))) { c = Math.atan2(rh, this.rc); sinc = Math.sin(c); cosc = Math.cos(c); lat = asinz(cosc * this.sin_p14 + (p.y * sinc * this.cos_p14) / rh); lon = Math.atan2(p.x * sinc, rh * this.cos_p14 * cosc - p.y * this.sin_p14 * sinc); lon = adjust_lon(this.long0 + lon); } else { lat = this.phic0; lon = 0; } p.x = lon; p.y = lat; return p; } var names$16 = ["gnom"]; var gnom = { init: init$15, forward: forward$14, inverse: inverse$14, names: names$16 }; var iqsfnz = function(eccent, q) { var temp = 1 - (1 - eccent * eccent) / (2 * eccent) * Math.log((1 - eccent) / (1 + eccent)); if (Math.abs(Math.abs(q) - temp) < 1.0E-6) { if (q < 0) { return (-1 * HALF_PI); } else { return HALF_PI; } } //var phi = 0.5* q/(1-eccent*eccent); var phi = Math.asin(0.5 * q); var dphi; var sin_phi; var cos_phi; var con; for (var i = 0; i < 30; i++) { sin_phi = Math.sin(phi); cos_phi = Math.cos(phi); con = eccent * sin_phi; dphi = Math.pow(1 - con * con, 2) / (2 * cos_phi) * (q / (1 - eccent * eccent) - sin_phi / (1 - con * con) + 0.5 / eccent * Math.log((1 - con) / (1 + con))); phi += dphi; if (Math.abs(dphi) <= 0.0000000001) { return phi; } } //console.log("IQSFN-CONV:Latitude failed to converge after 30 iterations"); return NaN; }; /* reference: "Cartographic Projection Procedures for the UNIX Environment- A User's Manual" by Gerald I. Evenden, USGS Open File Report 90-284and Release 4 Interim Reports (2003) */ function init$16() { //no-op if (!this.sphere) { this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts)); } } /* Cylindrical Equal Area forward equations--mapping lat,long to x,y ------------------------------------------------------------*/ function forward$15(p) { var lon = p.x; var lat = p.y; var x, y; /* Forward equations -----------------*/ var dlon = adjust_lon(lon - this.long0); if (this.sphere) { x = this.x0 + this.a * dlon * Math.cos(this.lat_ts); y = this.y0 + this.a * Math.sin(lat) / Math.cos(this.lat_ts); } else { var qs = qsfnz(this.e, Math.sin(lat)); x = this.x0 + this.a * this.k0 * dlon; y = this.y0 + this.a * qs * 0.5 / this.k0; } p.x = x; p.y = y; return p; } /* Cylindrical Equal Area inverse equations--mapping x,y to lat/long ------------------------------------------------------------*/ function inverse$15(p) { p.x -= this.x0; p.y -= this.y0; var lon, lat; if (this.sphere) { lon = adjust_lon(this.long0 + (p.x / this.a) / Math.cos(this.lat_ts)); lat = Math.asin((p.y / this.a) * Math.cos(this.lat_ts)); } else { lat = iqsfnz(this.e, 2 * p.y * this.k0 / this.a); lon = adjust_lon(this.long0 + p.x / (this.a * this.k0)); } p.x = lon; p.y = lat; return p; } var names$17 = ["cea"]; var cea = { init: init$16, forward: forward$15, inverse: inverse$15, names: names$17 }; function init$17() { this.x0 = this.x0 || 0; this.y0 = this.y0 || 0; this.lat0 = this.lat0 || 0; this.long0 = this.long0 || 0; this.lat_ts = this.lat_ts || 0; this.title = this.title || "Equidistant Cylindrical (Plate Carre)"; this.rc = Math.cos(this.lat_ts); } // forward equations--mapping lat,long to x,y // ----------------------------------------------------------------- function forward$16(p) { var lon = p.x; var lat = p.y; var dlon = adjust_lon(lon - this.long0); var dlat = adjust_lat(lat - this.lat0); p.x = this.x0 + (this.a * dlon * this.rc); p.y = this.y0 + (this.a * dlat); return p; } // inverse equations--mapping x,y to lat/long // ----------------------------------------------------------------- function inverse$16(p) { var x = p.x; var y = p.y; p.x = adjust_lon(this.long0 + ((x - this.x0) / (this.a * this.rc))); p.y = adjust_lat(this.lat0 + ((y - this.y0) / (this.a))); return p; } var names$18 = ["Equirectangular", "Equidistant_Cylindrical", "eqc"]; var eqc = { init: init$17, forward: forward$16, inverse: inverse$16, names: names$18 }; var MAX_ITER$2 = 20; function init$18() { /* Place parameters in static storage for common use -------------------------------------------------*/ this.temp = this.b / this.a; this.es = 1 - Math.pow(this.temp, 2); // devait etre dans tmerc.js mais n y est pas donc je commente sinon retour de valeurs nulles this.e = Math.sqrt(this.es); this.e0 = e0fn(this.es); this.e1 = e1fn(this.es); this.e2 = e2fn(this.es); this.e3 = e3fn(this.es); this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0); //si que des zeros le calcul ne se fait pas } /* Polyconic forward equations--mapping lat,long to x,y ---------------------------------------------------*/ function forward$17(p) { var lon = p.x; var lat = p.y; var x, y, el; var dlon = adjust_lon(lon - this.long0); el = dlon * Math.sin(lat); if (this.sphere) { if (Math.abs(lat) <= EPSLN) { x = this.a * dlon; y = -1 * this.a * this.lat0; } else { x = this.a * Math.sin(el) / Math.tan(lat); y = this.a * (adjust_lat(lat - this.lat0) + (1 - Math.cos(el)) / Math.tan(lat)); } } else { if (Math.abs(lat) <= EPSLN) { x = this.a * dlon; y = -1 * this.ml0; } else { var nl = gN(this.a, this.e, Math.sin(lat)) / Math.tan(lat); x = nl * Math.sin(el); y = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, lat) - this.ml0 + nl * (1 - Math.cos(el)); } } p.x = x + this.x0; p.y = y + this.y0; return p; } /* Inverse equations -----------------*/ function inverse$17(p) { var lon, lat, x, y, i; var al, bl; var phi, dphi; x = p.x - this.x0; y = p.y - this.y0; if (this.sphere) { if (Math.abs(y + this.a * this.lat0) <= EPSLN) { lon = adjust_lon(x / this.a + this.long0); lat = 0; } else { al = this.lat0 + y / this.a; bl = x * x / this.a / this.a + al * al; phi = al; var tanphi; for (i = MAX_ITER$2; i; --i) { tanphi = Math.tan(phi); dphi = -1 * (al * (phi * tanphi + 1) - phi - 0.5 * (phi * phi + bl) * tanphi) / ((phi - al) / tanphi - 1); phi += dphi; if (Math.abs(dphi) <= EPSLN) { lat = phi; break; } } lon = adjust_lon(this.long0 + (Math.asin(x * Math.tan(phi) / this.a)) / Math.sin(lat)); } } else { if (Math.abs(y + this.ml0) <= EPSLN) { lat = 0; lon = adjust_lon(this.long0 + x / this.a); } else { al = (this.ml0 + y) / this.a; bl = x * x / this.a / this.a + al * al; phi = al; var cl, mln, mlnp, ma; var con; for (i = MAX_ITER$2; i; --i) { con = this.e * Math.sin(phi); cl = Math.sqrt(1 - con * con) * Math.tan(phi); mln = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi); mlnp = this.e0 - 2 * this.e1 * Math.cos(2 * phi) + 4 * this.e2 * Math.cos(4 * phi) - 6 * this.e3 * Math.cos(6 * phi); ma = mln / this.a; dphi = (al * (cl * ma + 1) - ma - 0.5 * cl * (ma * ma + bl)) / (this.es * Math.sin(2 * phi) * (ma * ma + bl - 2 * al * ma) / (4 * cl) + (al - ma) * (cl * mlnp - 2 / Math.sin(2 * phi)) - mlnp); phi -= dphi; if (Math.abs(dphi) <= EPSLN) { lat = phi; break; } } //lat=phi4z(this.e,this.e0,this.e1,this.e2,this.e3,al,bl,0,0); cl = Math.sqrt(1 - this.es * Math.pow(Math.sin(lat), 2)) * Math.tan(lat); lon = adjust_lon(this.long0 + Math.asin(x * cl / this.a) / Math.sin(lat)); } } p.x = lon; p.y = lat; return p; } var names$19 = ["Polyconic", "poly"]; var poly = { init: init$18, forward: forward$17, inverse: inverse$17, names: names$19 }; /* reference Department of Land and Survey Technical Circular 1973/32 http://www.linz.govt.nz/docs/miscellaneous/nz-map-definition.pdf OSG Technical Report 4.1 http://www.linz.govt.nz/docs/miscellaneous/nzmg.pdf */ /** * iterations: Number of iterations to refine inverse transform. * 0 -> km accuracy * 1 -> m accuracy -- suitable for most mapping applications * 2 -> mm accuracy */ function init$19() { this.A = []; this.A[1] = 0.6399175073; this.A[2] = -0.1358797613; this.A[3] = 0.063294409; this.A[4] = -0.02526853; this.A[5] = 0.0117879; this.A[6] = -0.0055161; this.A[7] = 0.0026906; this.A[8] = -0.001333; this.A[9] = 0.00067; this.A[10] = -0.00034; this.B_re = []; this.B_im = []; this.B_re[1] = 0.7557853228; this.B_im[1] = 0; this.B_re[2] = 0.249204646; this.B_im[2] = 0.003371507; this.B_re[3] = -0.001541739; this.B_im[3] = 0.041058560; this.B_re[4] = -0.10162907; this.B_im[4] = 0.01727609; this.B_re[5] = -0.26623489; this.B_im[5] = -0.36249218; this.B_re[6] = -0.6870983; this.B_im[6] = -1.1651967; this.C_re = []; this.C_im = []; this.C_re[1] = 1.3231270439; this.C_im[1] = 0; this.C_re[2] = -0.577245789; this.C_im[2] = -0.007809598; this.C_re[3] = 0.508307513; this.C_im[3] = -0.112208952; this.C_re[4] = -0.15094762; this.C_im[4] = 0.18200602; this.C_re[5] = 1.01418179; this.C_im[5] = 1.64497696; this.C_re[6] = 1.9660549; this.C_im[6] = 2.5127645; this.D = []; this.D[1] = 1.5627014243; this.D[2] = 0.5185406398; this.D[3] = -0.03333098; this.D[4] = -0.1052906; this.D[5] = -0.0368594; this.D[6] = 0.007317; this.D[7] = 0.01220; this.D[8] = 0.00394; this.D[9] = -0.0013; } /** New Zealand Map Grid Forward - long/lat to x/y long/lat in radians */ function forward$18(p) { var n; var lon = p.x; var lat = p.y; var delta_lat = lat - this.lat0; var delta_lon = lon - this.long0; // 1. Calculate d_phi and d_psi ... // and d_lambda // For this algorithm, delta_latitude is in seconds of arc x 10-5, so we need to scale to those units. Longitude is radians. var d_phi = delta_lat / SEC_TO_RAD * 1E-5; var d_lambda = delta_lon; var d_phi_n = 1; // d_phi^0 var d_psi = 0; for (n = 1; n <= 10; n++) { d_phi_n = d_phi_n * d_phi; d_psi = d_psi + this.A[n] * d_phi_n; } // 2. Calculate theta var th_re = d_psi; var th_im = d_lambda; // 3. Calculate z var th_n_re = 1; var th_n_im = 0; // theta^0 var th_n_re1; var th_n_im1; var z_re = 0; var z_im = 0; for (n = 1; n <= 6; n++) { th_n_re1 = th_n_re * th_re - th_n_im * th_im; th_n_im1 = th_n_im * th_re + th_n_re * th_im; th_n_re = th_n_re1; th_n_im = th_n_im1; z_re = z_re + this.B_re[n] * th_n_re - this.B_im[n] * th_n_im; z_im = z_im + this.B_im[n] * th_n_re + this.B_re[n] * th_n_im; } // 4. Calculate easting and northing p.x = (z_im * this.a) + this.x0; p.y = (z_re * this.a) + this.y0; return p; } /** New Zealand Map Grid Inverse - x/y to long/lat */ function inverse$18(p) { var n; var x = p.x; var y = p.y; var delta_x = x - this.x0; var delta_y = y - this.y0; // 1. Calculate z var z_re = delta_y / this.a; var z_im = delta_x / this.a; // 2a. Calculate theta - first approximation gives km accuracy var z_n_re = 1; var z_n_im = 0; // z^0 var z_n_re1; var z_n_im1; var th_re = 0; var th_im = 0; for (n = 1; n <= 6; n++) { z_n_re1 = z_n_re * z_re - z_n_im * z_im; z_n_im1 = z_n_im * z_re + z_n_re * z_im; z_n_re = z_n_re1; z_n_im = z_n_im1; th_re = th_re + this.C_re[n] * z_n_re - this.C_im[n] * z_n_im; th_im = th_im + this.C_im[n] * z_n_re + this.C_re[n] * z_n_im; } // 2b. Iterate to refine the accuracy of the calculation // 0 iterations gives km accuracy // 1 iteration gives m accuracy -- good enough for most mapping applications // 2 iterations bives mm accuracy for (var i = 0; i < this.iterations; i++) { var th_n_re = th_re; var th_n_im = th_im; var th_n_re1; var th_n_im1; var num_re = z_re; var num_im = z_im; for (n = 2; n <= 6; n++) { th_n_re1 = th_n_re * th_re - th_n_im * th_im; th_n_im1 = th_n_im * th_re + th_n_re * th_im; th_n_re = th_n_re1; th_n_im = th_n_im1; num_re = num_re + (n - 1) * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im); num_im = num_im + (n - 1) * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im); } th_n_re = 1; th_n_im = 0; var den_re = this.B_re[1]; var den_im = this.B_im[1]; for (n = 2; n <= 6; n++) { th_n_re1 = th_n_re * th_re - th_n_im * th_im; th_n_im1 = th_n_im * th_re + th_n_re * th_im; th_n_re = th_n_re1; th_n_im = th_n_im1; den_re = den_re + n * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im); den_im = den_im + n * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im); } // Complex division var den2 = den_re * den_re + den_im * den_im; th_re = (num_re * den_re + num_im * den_im) / den2; th_im = (num_im * den_re - num_re * den_im) / den2; } // 3. Calculate d_phi ... // and d_lambda var d_psi = th_re; var d_lambda = th_im; var d_psi_n = 1; // d_psi^0 var d_phi = 0; for (n = 1; n <= 9; n++) { d_psi_n = d_psi_n * d_psi; d_phi = d_phi + this.D[n] * d_psi_n; } // 4. Calculate latitude and longitude // d_phi is calcuated in second of arc * 10^-5, so we need to scale back to radians. d_lambda is in radians. var lat = this.lat0 + (d_phi * SEC_TO_RAD * 1E5); var lon = this.long0 + d_lambda; p.x = lon; p.y = lat; return p; } var names$20 = ["New_Zealand_Map_Grid", "nzmg"]; var nzmg = { init: init$19, forward: forward$18, inverse: inverse$18, names: names$20 }; /* reference "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder, The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355. */ /* Initialize the Miller Cylindrical projection -------------------------------------------*/ function init$20() { //no-op } /* Miller Cylindrical forward equations--mapping lat,long to x,y ------------------------------------------------------------*/ function forward$19(p) { var lon = p.x; var lat = p.y; /* Forward equations -----------------*/ var dlon = adjust_lon(lon - this.long0); var x = this.x0 + this.a * dlon; var y = this.y0 + this.a * Math.log(Math.tan((Math.PI / 4) + (lat / 2.5))) * 1.25; p.x = x; p.y = y; return p; } /* Miller Cylindrical inverse equations--mapping x,y to lat/long ------------------------------------------------------------*/ function inverse$19(p) { p.x -= this.x0; p.y -= this.y0; var lon = adjust_lon(this.long0 + p.x / this.a); var lat = 2.5 * (Math.atan(Math.exp(0.8 * p.y / this.a)) - Math.PI / 4); p.x = lon; p.y = lat; return p; } var names$21 = ["Miller_Cylindrical", "mill"]; var mill = { init: init$20, forward: forward$19, inverse: inverse$19, names: names$21 }; var MAX_ITER$3 = 20; function init$21() { /* Place parameters in static storage for common use -------------------------------------------------*/ if (!this.sphere) { this.en = pj_enfn(this.es); } else { this.n = 1; this.m = 0; this.es = 0; this.C_y = Math.sqrt((this.m + 1) / this.n); this.C_x = this.C_y / (this.m + 1); } } /* Sinusoidal forward equations--mapping lat,long to x,y -----------------------------------------------------*/ function forward$20(p) { var x, y; var lon = p.x; var lat = p.y; /* Forward equations -----------------*/ lon = adjust_lon(lon - this.long0); if (this.sphere) { if (!this.m) { lat = this.n !== 1 ? Math.asin(this.n * Math.sin(lat)) : lat; } else { var k = this.n * Math.sin(lat); for (var i = MAX_ITER$3; i; --i) { var V = (this.m * lat + Math.sin(lat) - k) / (this.m + Math.cos(lat)); lat -= V; if (Math.abs(V) < EPSLN) { break; } } } x = this.a * this.C_x * lon * (this.m + Math.cos(lat)); y = this.a * this.C_y * lat; } else { var s = Math.sin(lat); var c = Math.cos(lat); y = this.a * pj_mlfn(lat, s, c, this.en); x = this.a * lon * c / Math.sqrt(1 - this.es * s * s); } p.x = x; p.y = y; return p; } function inverse$20(p) { var lat, temp, lon, s; p.x -= this.x0; lon = p.x / this.a; p.y -= this.y0; lat = p.y / this.a; if (this.sphere) { lat /= this.C_y; lon = lon / (this.C_x * (this.m + Math.cos(lat))); if (this.m) { lat = asinz((this.m * lat + Math.sin(lat)) / this.n); } else if (this.n !== 1) { lat = asinz(Math.sin(lat) / this.n); } lon = adjust_lon(lon + this.long0); lat = adjust_lat(lat); } else { lat = pj_inv_mlfn(p.y / this.a, this.es, this.en); s = Math.abs(lat); if (s < HALF_PI) { s = Math.sin(lat); temp = this.long0 + p.x * Math.sqrt(1 - this.es * s * s) / (this.a * Math.cos(lat)); //temp = this.long0 + p.x / (this.a * Math.cos(lat)); lon = adjust_lon(temp); } else if ((s - EPSLN) < HALF_PI) { lon = this.long0; } } p.x = lon; p.y = lat; return p; } var names$22 = ["Sinusoidal", "sinu"]; var sinu = { init: init$21, forward: forward$20, inverse: inverse$20, names: names$22 }; function init$22() {} /* Mollweide forward equations--mapping lat,long to x,y ----------------------------------------------------*/ function forward$21(p) { /* Forward equations -----------------*/ var lon = p.x; var lat = p.y; var delta_lon = adjust_lon(lon - this.long0); var theta = lat; var con = Math.PI * Math.sin(lat); /* Iterate using the Newton-Raphson method to find theta -----------------------------------------------------*/ while (true) { var delta_theta = -(theta + Math.sin(theta) - con) / (1 + Math.cos(theta)); theta += delta_theta; if (Math.abs(delta_theta) < EPSLN) { break; } } theta /= 2; /* If the latitude is 90 deg, force the x coordinate to be "0 + false easting" this is done here because of precision problems with "cos(theta)" --------------------------------------------------------------------------*/ if (Math.PI / 2 - Math.abs(lat) < EPSLN) { delta_lon = 0; } var x = 0.900316316158 * this.a * delta_lon * Math.cos(theta) + this.x0; var y = 1.4142135623731 * this.a * Math.sin(theta) + this.y0; p.x = x; p.y = y; return p; } function inverse$21(p) { var theta; var arg; /* Inverse equations -----------------*/ p.x -= this.x0; p.y -= this.y0; arg = p.y / (1.4142135623731 * this.a); /* Because of division by zero problems, 'arg' can not be 1. Therefore a number very close to one is used instead. -------------------------------------------------------------------*/ if (Math.abs(arg) > 0.999999999999) { arg = 0.999999999999; } theta = Math.asin(arg); var lon = adjust_lon(this.long0 + (p.x / (0.900316316158 * this.a * Math.cos(theta)))); if (lon < (-Math.PI)) { lon = -Math.PI; } if (lon > Math.PI) { lon = Math.PI; } arg = (2 * theta + Math.sin(2 * theta)) / Math.PI; if (Math.abs(arg) > 1) { arg = 1; } var lat = Math.asin(arg); p.x = lon; p.y = lat; return p; } var names$23 = ["Mollweide", "moll"]; var moll = { init: init$22, forward: forward$21, inverse: inverse$21, names: names$23 }; function init$23() { /* Place parameters in static storage for common use -------------------------------------------------*/ // Standard Parallels cannot be equal and on opposite sides of the equator if (Math.abs(this.lat1 + this.lat2) < EPSLN) { return; } this.lat2 = this.lat2 || this.lat1; this.temp = this.b / this.a; this.es = 1 - Math.pow(this.temp, 2); this.e = Math.sqrt(this.es); this.e0 = e0fn(this.es); this.e1 = e1fn(this.es); this.e2 = e2fn(this.es); this.e3 = e3fn(this.es); this.sinphi = Math.sin(this.lat1); this.cosphi = Math.cos(this.lat1); this.ms1 = msfnz(this.e, this.sinphi, this.cosphi); this.ml1 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat1); if (Math.abs(this.lat1 - this.lat2) < EPSLN) { this.ns = this.sinphi; } else { this.sinphi = Math.sin(this.lat2); this.cosphi = Math.cos(this.lat2); this.ms2 = msfnz(this.e, this.sinphi, this.cosphi); this.ml2 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat2); this.ns = (this.ms1 - this.ms2) / (this.ml2 - this.ml1); } this.g = this.ml1 + this.ms1 / this.ns; this.ml0 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0); this.rh = this.a * (this.g - this.ml0); } /* Equidistant Conic forward equations--mapping lat,long to x,y -----------------------------------------------------------*/ function forward$22(p) { var lon = p.x; var lat = p.y; var rh1; /* Forward equations -----------------*/ if (this.sphere) { rh1 = this.a * (this.g - lat); } else { var ml = mlfn(this.e0, this.e1, this.e2, this.e3, lat); rh1 = this.a * (this.g - ml); } var theta = this.ns * adjust_lon(lon - this.long0); var x = this.x0 + rh1 * Math.sin(theta); var y = this.y0 + this.rh - rh1 * Math.cos(theta); p.x = x; p.y = y; return p; } /* Inverse equations -----------------*/ function inverse$22(p) { p.x -= this.x0; p.y = this.rh - p.y + this.y0; var con, rh1, lat, lon; if (this.ns >= 0) { rh1 = Math.sqrt(p.x * p.x + p.y * p.y); con = 1; } else { rh1 = -Math.sqrt(p.x * p.x + p.y * p.y); con = -1; } var theta = 0; if (rh1 !== 0) { theta = Math.atan2(con * p.x, con * p.y); } if (this.sphere) { lon = adjust_lon(this.long0 + theta / this.ns); lat = adjust_lat(this.g - rh1 / this.a); p.x = lon; p.y = lat; return p; } else { var ml = this.g - rh1 / this.a; lat = imlfn(ml, this.e0, this.e1, this.e2, this.e3); lon = adjust_lon(this.long0 + theta / this.ns); p.x = lon; p.y = lat; return p; } } var names$24 = ["Equidistant_Conic", "eqdc"]; var eqdc = { init: init$23, forward: forward$22, inverse: inverse$22, names: names$24 }; /* Initialize the Van Der Grinten projection ----------------------------------------*/ function init$24() { //this.R = 6370997; //Radius of earth this.R = this.a; } function forward$23(p) { var lon = p.x; var lat = p.y; /* Forward equations -----------------*/ var dlon = adjust_lon(lon - this.long0); var x, y; if (Math.abs(lat) <= EPSLN) { x = this.x0 + this.R * dlon; y = this.y0; } var theta = asinz(2 * Math.abs(lat / Math.PI)); if ((Math.abs(dlon) <= EPSLN) || (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN)) { x = this.x0; if (lat >= 0) { y = this.y0 + Math.PI * this.R * Math.tan(0.5 * theta); } else { y = this.y0 + Math.PI * this.R * -Math.tan(0.5 * theta); } // return(OK); } var al = 0.5 * Math.abs((Math.PI / dlon) - (dlon / Math.PI)); var asq = al * al; var sinth = Math.sin(theta); var costh = Math.cos(theta); var g = costh / (sinth + costh - 1); var gsq = g * g; var m = g * (2 / sinth - 1); var msq = m * m; var con = Math.PI * this.R * (al * (g - msq) + Math.sqrt(asq * (g - msq) * (g - msq) - (msq + asq) * (gsq - msq))) / (msq + asq); if (dlon < 0) { con = -con; } x = this.x0 + con; //con = Math.abs(con / (Math.PI * this.R)); var q = asq + g; con = Math.PI * this.R * (m * q - al * Math.sqrt((msq + asq) * (asq + 1) - q * q)) / (msq + asq); if (lat >= 0) { //y = this.y0 + Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con); y = this.y0 + con; } else { //y = this.y0 - Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con); y = this.y0 - con; } p.x = x; p.y = y; return p; } /* Van Der Grinten inverse equations--mapping x,y to lat/long ---------------------------------------------------------*/ function inverse$23(p) { var lon, lat; var xx, yy, xys, c1, c2, c3; var a1; var m1; var con; var th1; var d; /* inverse equations -----------------*/ p.x -= this.x0; p.y -= this.y0; con = Math.PI * this.R; xx = p.x / con; yy = p.y / con; xys = xx * xx + yy * yy; c1 = -Math.abs(yy) * (1 + xys); c2 = c1 - 2 * yy * yy + xx * xx; c3 = -2 * c1 + 1 + 2 * yy * yy + xys * xys; d = yy * yy / c3 + (2 * c2 * c2 * c2 / c3 / c3 / c3 - 9 * c1 * c2 / c3 / c3) / 27; a1 = (c1 - c2 * c2 / 3 / c3) / c3; m1 = 2 * Math.sqrt(-a1 / 3); con = ((3 * d) / a1) / m1; if (Math.abs(con) > 1) { if (con >= 0) { con = 1; } else { con = -1; } } th1 = Math.acos(con) / 3; if (p.y >= 0) { lat = (-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI; } else { lat = -(-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI; } if (Math.abs(xx) < EPSLN) { lon = this.long0; } else { lon = adjust_lon(this.long0 + Math.PI * (xys - 1 + Math.sqrt(1 + 2 * (xx * xx - yy * yy) + xys * xys)) / 2 / xx); } p.x = lon; p.y = lat; return p; } var names$25 = ["Van_der_Grinten_I", "VanDerGrinten", "vandg"]; var vandg = { init: init$24, forward: forward$23, inverse: inverse$23, names: names$25 }; function init$25() { this.sin_p12 = Math.sin(this.lat0); this.cos_p12 = Math.cos(this.lat0); } function forward$24(p) { var lon = p.x; var lat = p.y; var sinphi = Math.sin(p.y); var cosphi = Math.cos(p.y); var dlon = adjust_lon(lon - this.long0); var e0, e1, e2, e3, Mlp, Ml, tanphi, Nl1, Nl, psi, Az, G, H, GH, Hs, c, kp, cos_c, s, s2, s3, s4, s5; if (this.sphere) { if (Math.abs(this.sin_p12 - 1) <= EPSLN) { //North Pole case p.x = this.x0 + this.a * (HALF_PI - lat) * Math.sin(dlon); p.y = this.y0 - this.a * (HALF_PI - lat) * Math.cos(dlon); return p; } else if (Math.abs(this.sin_p12 + 1) <= EPSLN) { //South Pole case p.x = this.x0 + this.a * (HALF_PI + lat) * Math.sin(dlon); p.y = this.y0 + this.a * (HALF_PI + lat) * Math.cos(dlon); return p; } else { //default case cos_c = this.sin_p12 * sinphi + this.cos_p12 * cosphi * Math.cos(dlon); c = Math.acos(cos_c); kp = c ? c / Math.sin(c) : 1; p.x = this.x0 + this.a * kp * cosphi * Math.sin(dlon); p.y = this.y0 + this.a * kp * (this.cos_p12 * sinphi - this.sin_p12 * cosphi * Math.cos(dlon)); return p; } } else { e0 = e0fn(this.es); e1 = e1fn(this.es); e2 = e2fn(this.es); e3 = e3fn(this.es); if (Math.abs(this.sin_p12 - 1) <= EPSLN) { //North Pole case Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI); Ml = this.a * mlfn(e0, e1, e2, e3, lat); p.x = this.x0 + (Mlp - Ml) * Math.sin(dlon); p.y = this.y0 - (Mlp - Ml) * Math.cos(dlon); return p; } else if (Math.abs(this.sin_p12 + 1) <= EPSLN) { //South Pole case Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI); Ml = this.a * mlfn(e0, e1, e2, e3, lat); p.x = this.x0 + (Mlp + Ml) * Math.sin(dlon); p.y = this.y0 + (Mlp + Ml) * Math.cos(dlon); return p; } else { //Default case tanphi = sinphi / cosphi; Nl1 = gN(this.a, this.e, this.sin_p12); Nl = gN(this.a, this.e, sinphi); psi = Math.atan((1 - this.es) * tanphi + this.es * Nl1 * this.sin_p12 / (Nl * cosphi)); Az = Math.atan2(Math.sin(dlon), this.cos_p12 * Math.tan(psi) - this.sin_p12 * Math.cos(dlon)); if (Az === 0) { s = Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi)); } else if (Math.abs(Math.abs(Az) - Math.PI) <= EPSLN) { s = -Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi)); } else { s = Math.asin(Math.sin(dlon) * Math.cos(psi) / Math.sin(Az)); } G = this.e * this.sin_p12 / Math.sqrt(1 - this.es); H = this.e * this.cos_p12 * Math.cos(Az) / Math.sqrt(1 - this.es); GH = G * H; Hs = H * H; s2 = s * s; s3 = s2 * s; s4 = s3 * s; s5 = s4 * s; c = Nl1 * s * (1 - s2 * Hs * (1 - Hs) / 6 + s3 / 8 * GH * (1 - 2 * Hs) + s4 / 120 * (Hs * (4 - 7 * Hs) - 3 * G * G * (1 - 7 * Hs)) - s5 / 48 * GH); p.x = this.x0 + c * Math.sin(Az); p.y = this.y0 + c * Math.cos(Az); return p; } } } function inverse$24(p) { p.x -= this.x0; p.y -= this.y0; var rh, z, sinz, cosz, lon, lat, con, e0, e1, e2, e3, Mlp, M, N1, psi, Az, cosAz, tmp, A, B, D, Ee, F, sinpsi; if (this.sphere) { rh = Math.sqrt(p.x * p.x + p.y * p.y); if (rh > (2 * HALF_PI * this.a)) { return; } z = rh / this.a; sinz = Math.sin(z); cosz = Math.cos(z); lon = this.long0; if (Math.abs(rh) <= EPSLN) { lat = this.lat0; } else { lat = asinz(cosz * this.sin_p12 + (p.y * sinz * this.cos_p12) / rh); con = Math.abs(this.lat0) - HALF_PI; if (Math.abs(con) <= EPSLN) { if (this.lat0 >= 0) { lon = adjust_lon(this.long0 + Math.atan2(p.x, - p.y)); } else { lon = adjust_lon(this.long0 - Math.atan2(-p.x, p.y)); } } else { /*con = cosz - this.sin_p12 * Math.sin(lat); if ((Math.abs(con) < EPSLN) && (Math.abs(p.x) < EPSLN)) { //no-op, just keep the lon value as is } else { var temp = Math.atan2((p.x * sinz * this.cos_p12), (con * rh)); lon = adjust_lon(this.long0 + Math.atan2((p.x * sinz * this.cos_p12), (con * rh))); }*/ lon = adjust_lon(this.long0 + Math.atan2(p.x * sinz, rh * this.cos_p12 * cosz - p.y * this.sin_p12 * sinz)); } } p.x = lon; p.y = lat; return p; } else { e0 = e0fn(this.es); e1 = e1fn(this.es); e2 = e2fn(this.es); e3 = e3fn(this.es); if (Math.abs(this.sin_p12 - 1) <= EPSLN) { //North pole case Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI); rh = Math.sqrt(p.x * p.x + p.y * p.y); M = Mlp - rh; lat = imlfn(M / this.a, e0, e1, e2, e3); lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y)); p.x = lon; p.y = lat; return p; } else if (Math.abs(this.sin_p12 + 1) <= EPSLN) { //South pole case Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI); rh = Math.sqrt(p.x * p.x + p.y * p.y); M = rh - Mlp; lat = imlfn(M / this.a, e0, e1, e2, e3); lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y)); p.x = lon; p.y = lat; return p; } else { //default case rh = Math.sqrt(p.x * p.x + p.y * p.y); Az = Math.atan2(p.x, p.y); N1 = gN(this.a, this.e, this.sin_p12); cosAz = Math.cos(Az); tmp = this.e * this.cos_p12 * cosAz; A = -tmp * tmp / (1 - this.es); B = 3 * this.es * (1 - A) * this.sin_p12 * this.cos_p12 * cosAz / (1 - this.es); D = rh / N1; Ee = D - A * (1 + A) * Math.pow(D, 3) / 6 - B * (1 + 3 * A) * Math.pow(D, 4) / 24; F = 1 - A * Ee * Ee / 2 - D * Ee * Ee * Ee / 6; psi = Math.asin(this.sin_p12 * Math.cos(Ee) + this.cos_p12 * Math.sin(Ee) * cosAz); lon = adjust_lon(this.long0 + Math.asin(Math.sin(Az) * Math.sin(Ee) / Math.cos(psi))); sinpsi = Math.sin(psi); lat = Math.atan2((sinpsi - this.es * F * this.sin_p12) * Math.tan(psi), sinpsi * (1 - this.es)); p.x = lon; p.y = lat; return p; } } } var names$26 = ["Azimuthal_Equidistant", "aeqd"]; var aeqd = { init: init$25, forward: forward$24, inverse: inverse$24, names: names$26 }; function init$26() { //double temp; /* temporary variable */ /* Place parameters in static storage for common use -------------------------------------------------*/ this.sin_p14 = Math.sin(this.lat0); this.cos_p14 = Math.cos(this.lat0); } /* Orthographic forward equations--mapping lat,long to x,y ---------------------------------------------------*/ function forward$25(p) { var sinphi, cosphi; /* sin and cos value */ var dlon; /* delta longitude value */ var coslon; /* cos of longitude */ var ksp; /* scale factor */ var g, x, y; var lon = p.x; var lat = p.y; /* Forward equations -----------------*/ dlon = adjust_lon(lon - this.long0); sinphi = Math.sin(lat); cosphi = Math.cos(lat); coslon = Math.cos(dlon); g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon; ksp = 1; if ((g > 0) || (Math.abs(g) <= EPSLN)) { x = this.a * ksp * cosphi * Math.sin(dlon); y = this.y0 + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon); } p.x = x; p.y = y; return p; } function inverse$25(p) { var rh; /* height above ellipsoid */ var z; /* angle */ var sinz, cosz; /* sin of z and cos of z */ var con; var lon, lat; /* Inverse equations -----------------*/ p.x -= this.x0; p.y -= this.y0; rh = Math.sqrt(p.x * p.x + p.y * p.y); z = asinz(rh / this.a); sinz = Math.sin(z); cosz = Math.cos(z); lon = this.long0; if (Math.abs(rh) <= EPSLN) { lat = this.lat0; p.x = lon; p.y = lat; return p; } lat = asinz(cosz * this.sin_p14 + (p.y * sinz * this.cos_p14) / rh); con = Math.abs(this.lat0) - HALF_PI; if (Math.abs(con) <= EPSLN) { if (this.lat0 >= 0) { lon = adjust_lon(this.long0 + Math.atan2(p.x, - p.y)); } else { lon = adjust_lon(this.long0 - Math.atan2(-p.x, p.y)); } p.x = lon; p.y = lat; return p; } lon = adjust_lon(this.long0 + Math.atan2((p.x * sinz), rh * this.cos_p14 * cosz - p.y * this.sin_p14 * sinz)); p.x = lon; p.y = lat; return p; } var names$27 = ["ortho"]; var ortho = { init: init$26, forward: forward$25, inverse: inverse$25, names: names$27 }; // QSC projection rewritten from the original PROJ4 // https://github.com/OSGeo/proj.4/blob/master/src/PJ_qsc.c /* constants */ var FACE_ENUM = { FRONT: 1, RIGHT: 2, BACK: 3, LEFT: 4, TOP: 5, BOTTOM: 6 }; var AREA_ENUM = { AREA_0: 1, AREA_1: 2, AREA_2: 3, AREA_3: 4 }; function init$27() { this.x0 = this.x0 || 0; this.y0 = this.y0 || 0; this.lat0 = this.lat0 || 0; this.long0 = this.long0 || 0; this.lat_ts = this.lat_ts || 0; this.title = this.title || "Quadrilateralized Spherical Cube"; /* Determine the cube face from the center of projection. */ if (this.lat0 >= HALF_PI - FORTPI / 2.0) { this.face = FACE_ENUM.TOP; } else if (this.lat0 <= -(HALF_PI - FORTPI / 2.0)) { this.face = FACE_ENUM.BOTTOM; } else if (Math.abs(this.long0) <= FORTPI) { this.face = FACE_ENUM.FRONT; } else if (Math.abs(this.long0) <= HALF_PI + FORTPI) { this.face = this.long0 > 0.0 ? FACE_ENUM.RIGHT : FACE_ENUM.LEFT; } else { this.face = FACE_ENUM.BACK; } /* Fill in useful values for the ellipsoid <-> sphere shift * described in [LK12]. */ if (this.es !== 0) { this.one_minus_f = 1 - (this.a - this.b) / this.a; this.one_minus_f_squared = this.one_minus_f * this.one_minus_f; } } // QSC forward equations--mapping lat,long to x,y // ----------------------------------------------------------------- function forward$26(p) { var xy = {x: 0, y: 0}; var lat, lon; var theta, phi; var t, mu; /* nu; */ var area = {value: 0}; // move lon according to projection's lon p.x -= this.long0; /* Convert the geodetic latitude to a geocentric latitude. * This corresponds to the shift from the ellipsoid to the sphere * described in [LK12]. */ if (this.es !== 0) {//if (P->es != 0) { lat = Math.atan(this.one_minus_f_squared * Math.tan(p.y)); } else { lat = p.y; } /* Convert the input lat, lon into theta, phi as used by QSC. * This depends on the cube face and the area on it. * For the top and bottom face, we can compute theta and phi * directly from phi, lam. For the other faces, we must use * unit sphere cartesian coordinates as an intermediate step. */ lon = p.x; //lon = lp.lam; if (this.face === FACE_ENUM.TOP) { phi = HALF_PI - lat; if (lon >= FORTPI && lon <= HALF_PI + FORTPI) { area.value = AREA_ENUM.AREA_0; theta = lon - HALF_PI; } else if (lon > HALF_PI + FORTPI || lon <= -(HALF_PI + FORTPI)) { area.value = AREA_ENUM.AREA_1; theta = (lon > 0.0 ? lon - SPI : lon + SPI); } else if (lon > -(HALF_PI + FORTPI) && lon <= -FORTPI) { area.value = AREA_ENUM.AREA_2; theta = lon + HALF_PI; } else { area.value = AREA_ENUM.AREA_3; theta = lon; } } else if (this.face === FACE_ENUM.BOTTOM) { phi = HALF_PI + lat; if (lon >= FORTPI && lon <= HALF_PI + FORTPI) { area.value = AREA_ENUM.AREA_0; theta = -lon + HALF_PI; } else if (lon < FORTPI && lon >= -FORTPI) { area.value = AREA_ENUM.AREA_1; theta = -lon; } else if (lon < -FORTPI && lon >= -(HALF_PI + FORTPI)) { area.value = AREA_ENUM.AREA_2; theta = -lon - HALF_PI; } else { area.value = AREA_ENUM.AREA_3; theta = (lon > 0.0 ? -lon + SPI : -lon - SPI); } } else { var q, r, s; var sinlat, coslat; var sinlon, coslon; if (this.face === FACE_ENUM.RIGHT) { lon = qsc_shift_lon_origin(lon, +HALF_PI); } else if (this.face === FACE_ENUM.BACK) { lon = qsc_shift_lon_origin(lon, +SPI); } else if (this.face === FACE_ENUM.LEFT) { lon = qsc_shift_lon_origin(lon, -HALF_PI); } sinlat = Math.sin(lat); coslat = Math.cos(lat); sinlon = Math.sin(lon); coslon = Math.cos(lon); q = coslat * coslon; r = coslat * sinlon; s = sinlat; if (this.face === FACE_ENUM.FRONT) { phi = Math.acos(q); theta = qsc_fwd_equat_face_theta(phi, s, r, area); } else if (this.face === FACE_ENUM.RIGHT) { phi = Math.acos(r); theta = qsc_fwd_equat_face_theta(phi, s, -q, area); } else if (this.face === FACE_ENUM.BACK) { phi = Math.acos(-q); theta = qsc_fwd_equat_face_theta(phi, s, -r, area); } else if (this.face === FACE_ENUM.LEFT) { phi = Math.acos(-r); theta = qsc_fwd_equat_face_theta(phi, s, q, area); } else { /* Impossible */ phi = theta = 0; area.value = AREA_ENUM.AREA_0; } } /* Compute mu and nu for the area of definition. * For mu, see Eq. (3-21) in [OL76], but note the typos: * compare with Eq. (3-14). For nu, see Eq. (3-38). */ mu = Math.atan((12 / SPI) * (theta + Math.acos(Math.sin(theta) * Math.cos(FORTPI)) - HALF_PI)); t = Math.sqrt((1 - Math.cos(phi)) / (Math.cos(mu) * Math.cos(mu)) / (1 - Math.cos(Math.atan(1 / Math.cos(theta))))); /* Apply the result to the real area. */ if (area.value === AREA_ENUM.AREA_1) { mu += HALF_PI; } else if (area.value === AREA_ENUM.AREA_2) { mu += SPI; } else if (area.value === AREA_ENUM.AREA_3) { mu += 1.5 * SPI; } /* Now compute x, y from mu and nu */ xy.x = t * Math.cos(mu); xy.y = t * Math.sin(mu); xy.x = xy.x * this.a + this.x0; xy.y = xy.y * this.a + this.y0; p.x = xy.x; p.y = xy.y; return p; } // QSC inverse equations--mapping x,y to lat/long // ----------------------------------------------------------------- function inverse$26(p) { var lp = {lam: 0, phi: 0}; var mu, nu, cosmu, tannu; var tantheta, theta, cosphi, phi; var t; var area = {value: 0}; /* de-offset */ p.x = (p.x - this.x0) / this.a; p.y = (p.y - this.y0) / this.a; /* Convert the input x, y to the mu and nu angles as used by QSC. * This depends on the area of the cube face. */ nu = Math.atan(Math.sqrt(p.x * p.x + p.y * p.y)); mu = Math.atan2(p.y, p.x); if (p.x >= 0.0 && p.x >= Math.abs(p.y)) { area.value = AREA_ENUM.AREA_0; } else if (p.y >= 0.0 && p.y >= Math.abs(p.x)) { area.value = AREA_ENUM.AREA_1; mu -= HALF_PI; } else if (p.x < 0.0 && -p.x >= Math.abs(p.y)) { area.value = AREA_ENUM.AREA_2; mu = (mu < 0.0 ? mu + SPI : mu - SPI); } else { area.value = AREA_ENUM.AREA_3; mu += HALF_PI; } /* Compute phi and theta for the area of definition. * The inverse projection is not described in the original paper, but some * good hints can be found here (as of 2011-12-14): * http://fits.gsfc.nasa.gov/fitsbits/saf.93/saf.9302 * (search for "Message-Id: <9302181759.AA25477 at fits.cv.nrao.edu>") */ t = (SPI / 12) * Math.tan(mu); tantheta = Math.sin(t) / (Math.cos(t) - (1 / Math.sqrt(2))); theta = Math.atan(tantheta); cosmu = Math.cos(mu); tannu = Math.tan(nu); cosphi = 1 - cosmu * cosmu * tannu * tannu * (1 - Math.cos(Math.atan(1 / Math.cos(theta)))); if (cosphi < -1) { cosphi = -1; } else if (cosphi > +1) { cosphi = +1; } /* Apply the result to the real area on the cube face. * For the top and bottom face, we can compute phi and lam directly. * For the other faces, we must use unit sphere cartesian coordinates * as an intermediate step. */ if (this.face === FACE_ENUM.TOP) { phi = Math.acos(cosphi); lp.phi = HALF_PI - phi; if (area.value === AREA_ENUM.AREA_0) { lp.lam = theta + HALF_PI; } else if (area.value === AREA_ENUM.AREA_1) { lp.lam = (theta < 0.0 ? theta + SPI : theta - SPI); } else if (area.value === AREA_ENUM.AREA_2) { lp.lam = theta - HALF_PI; } else /* area.value == AREA_ENUM.AREA_3 */ { lp.lam = theta; } } else if (this.face === FACE_ENUM.BOTTOM) { phi = Math.acos(cosphi); lp.phi = phi - HALF_PI; if (area.value === AREA_ENUM.AREA_0) { lp.lam = -theta + HALF_PI; } else if (area.value === AREA_ENUM.AREA_1) { lp.lam = -theta; } else if (area.value === AREA_ENUM.AREA_2) { lp.lam = -theta - HALF_PI; } else /* area.value == AREA_ENUM.AREA_3 */ { lp.lam = (theta < 0.0 ? -theta - SPI : -theta + SPI); } } else { /* Compute phi and lam via cartesian unit sphere coordinates. */ var q, r, s; q = cosphi; t = q * q; if (t >= 1) { s = 0; } else { s = Math.sqrt(1 - t) * Math.sin(theta); } t += s * s; if (t >= 1) { r = 0; } else { r = Math.sqrt(1 - t); } /* Rotate q,r,s into the correct area. */ if (area.value === AREA_ENUM.AREA_1) { t = r; r = -s; s = t; } else if (area.value === AREA_ENUM.AREA_2) { r = -r; s = -s; } else if (area.value === AREA_ENUM.AREA_3) { t = r; r = s; s = -t; } /* Rotate q,r,s into the correct cube face. */ if (this.face === FACE_ENUM.RIGHT) { t = q; q = -r; r = t; } else if (this.face === FACE_ENUM.BACK) { q = -q; r = -r; } else if (this.face === FACE_ENUM.LEFT) { t = q; q = r; r = -t; } /* Now compute phi and lam from the unit sphere coordinates. */ lp.phi = Math.acos(-s) - HALF_PI; lp.lam = Math.atan2(r, q); if (this.face === FACE_ENUM.RIGHT) { lp.lam = qsc_shift_lon_origin(lp.lam, -HALF_PI); } else if (this.face === FACE_ENUM.BACK) { lp.lam = qsc_shift_lon_origin(lp.lam, -SPI); } else if (this.face === FACE_ENUM.LEFT) { lp.lam = qsc_shift_lon_origin(lp.lam, +HALF_PI); } } /* Apply the shift from the sphere to the ellipsoid as described * in [LK12]. */ if (this.es !== 0) { var invert_sign; var tanphi, xa; invert_sign = (lp.phi < 0 ? 1 : 0); tanphi = Math.tan(lp.phi); xa = this.b / Math.sqrt(tanphi * tanphi + this.one_minus_f_squared); lp.phi = Math.atan(Math.sqrt(this.a * this.a - xa * xa) / (this.one_minus_f * xa)); if (invert_sign) { lp.phi = -lp.phi; } } lp.lam += this.long0; p.x = lp.lam; p.y = lp.phi; return p; } /* Helper function for forward projection: compute the theta angle * and determine the area number. */ function qsc_fwd_equat_face_theta(phi, y, x, area) { var theta; if (phi < EPSLN) { area.value = AREA_ENUM.AREA_0; theta = 0.0; } else { theta = Math.atan2(y, x); if (Math.abs(theta) <= FORTPI) { area.value = AREA_ENUM.AREA_0; } else if (theta > FORTPI && theta <= HALF_PI + FORTPI) { area.value = AREA_ENUM.AREA_1; theta -= HALF_PI; } else if (theta > HALF_PI + FORTPI || theta <= -(HALF_PI + FORTPI)) { area.value = AREA_ENUM.AREA_2; theta = (theta >= 0.0 ? theta - SPI : theta + SPI); } else { area.value = AREA_ENUM.AREA_3; theta += HALF_PI; } } return theta; } /* Helper function: shift the longitude. */ function qsc_shift_lon_origin(lon, offset) { var slon = lon + offset; if (slon < -SPI) { slon += TWO_PI; } else if (slon > +SPI) { slon -= TWO_PI; } return slon; } var names$28 = ["Quadrilateralized Spherical Cube", "Quadrilateralized_Spherical_Cube", "qsc"]; var qsc = { init: init$27, forward: forward$26, inverse: inverse$26, names: names$28 }; // Robinson projection // Based on https://github.com/OSGeo/proj.4/blob/master/src/PJ_robin.c // Polynomial coeficients from http://article.gmane.org/gmane.comp.gis.proj-4.devel/6039 var COEFS_X = [ [1.0000, 2.2199e-17, -7.15515e-05, 3.1103e-06], [0.9986, -0.000482243, -2.4897e-05, -1.3309e-06], [0.9954, -0.00083103, -4.48605e-05, -9.86701e-07], [0.9900, -0.00135364, -5.9661e-05, 3.6777e-06], [0.9822, -0.00167442, -4.49547e-06, -5.72411e-06], [0.9730, -0.00214868, -9.03571e-05, 1.8736e-08], [0.9600, -0.00305085, -9.00761e-05, 1.64917e-06], [0.9427, -0.00382792, -6.53386e-05, -2.6154e-06], [0.9216, -0.00467746, -0.00010457, 4.81243e-06], [0.8962, -0.00536223, -3.23831e-05, -5.43432e-06], [0.8679, -0.00609363, -0.000113898, 3.32484e-06], [0.8350, -0.00698325, -6.40253e-05, 9.34959e-07], [0.7986, -0.00755338, -5.00009e-05, 9.35324e-07], [0.7597, -0.00798324, -3.5971e-05, -2.27626e-06], [0.7186, -0.00851367, -7.01149e-05, -8.6303e-06], [0.6732, -0.00986209, -0.000199569, 1.91974e-05], [0.6213, -0.010418, 8.83923e-05, 6.24051e-06], [0.5722, -0.00906601, 0.000182, 6.24051e-06], [0.5322, -0.00677797, 0.000275608, 6.24051e-06] ]; var COEFS_Y = [ [-5.20417e-18, 0.0124, 1.21431e-18, -8.45284e-11], [0.0620, 0.0124, -1.26793e-09, 4.22642e-10], [0.1240, 0.0124, 5.07171e-09, -1.60604e-09], [0.1860, 0.0123999, -1.90189e-08, 6.00152e-09], [0.2480, 0.0124002, 7.10039e-08, -2.24e-08], [0.3100, 0.0123992, -2.64997e-07, 8.35986e-08], [0.3720, 0.0124029, 9.88983e-07, -3.11994e-07], [0.4340, 0.0123893, -3.69093e-06, -4.35621e-07], [0.4958, 0.0123198, -1.02252e-05, -3.45523e-07], [0.5571, 0.0121916, -1.54081e-05, -5.82288e-07], [0.6176, 0.0119938, -2.41424e-05, -5.25327e-07], [0.6769, 0.011713, -3.20223e-05, -5.16405e-07], [0.7346, 0.0113541, -3.97684e-05, -6.09052e-07], [0.7903, 0.0109107, -4.89042e-05, -1.04739e-06], [0.8435, 0.0103431, -6.4615e-05, -1.40374e-09], [0.8936, 0.00969686, -6.4636e-05, -8.547e-06], [0.9394, 0.00840947, -0.000192841, -4.2106e-06], [0.9761, 0.00616527, -0.000256, -4.2106e-06], [1.0000, 0.00328947, -0.000319159, -4.2106e-06] ]; var FXC = 0.8487; var FYC = 1.3523; var C1 = R2D/5; // rad to 5-degree interval var RC1 = 1/C1; var NODES = 18; var poly3_val = function(coefs, x) { return coefs[0] + x * (coefs[1] + x * (coefs[2] + x * coefs[3])); }; var poly3_der = function(coefs, x) { return coefs[1] + x * (2 * coefs[2] + x * 3 * coefs[3]); }; function newton_rapshon(f_df, start, max_err, iters) { var x = start; for (; iters; --iters) { var upd = f_df(x); x -= upd; if (Math.abs(upd) < max_err) { break; } } return x; } function init$28() { this.x0 = this.x0 || 0; this.y0 = this.y0 || 0; this.long0 = this.long0 || 0; this.es = 0; this.title = this.title || "Robinson"; } function forward$27(ll) { var lon = adjust_lon(ll.x - this.long0); var dphi = Math.abs(ll.y); var i = Math.floor(dphi * C1); if (i < 0) { i = 0; } else if (i >= NODES) { i = NODES - 1; } dphi = R2D * (dphi - RC1 * i); var xy = { x: poly3_val(COEFS_X[i], dphi) * lon, y: poly3_val(COEFS_Y[i], dphi) }; if (ll.y < 0) { xy.y = -xy.y; } xy.x = xy.x * this.a * FXC + this.x0; xy.y = xy.y * this.a * FYC + this.y0; return xy; } function inverse$27(xy) { var ll = { x: (xy.x - this.x0) / (this.a * FXC), y: Math.abs(xy.y - this.y0) / (this.a * FYC) }; if (ll.y >= 1) { // pathologic case ll.x /= COEFS_X[NODES][0]; ll.y = xy.y < 0 ? -HALF_PI : HALF_PI; } else { // find table interval var i = Math.floor(ll.y * NODES); if (i < 0) { i = 0; } else if (i >= NODES) { i = NODES - 1; } for (;;) { if (COEFS_Y[i][0] > ll.y) { --i; } else if (COEFS_Y[i+1][0] <= ll.y) { ++i; } else { break; } } // linear interpolation in 5 degree interval var coefs = COEFS_Y[i]; var t = 5 * (ll.y - coefs[0]) / (COEFS_Y[i+1][0] - coefs[0]); // find t so that poly3_val(coefs, t) = ll.y t = newton_rapshon(function(x) { return (poly3_val(coefs, x) - ll.y) / poly3_der(coefs, x); }, t, EPSLN, 100); ll.x /= poly3_val(COEFS_X[i], t); ll.y = (5 * i + t) * D2R; if (xy.y < 0) { ll.y = -ll.y; } } ll.x = adjust_lon(ll.x + this.long0); return ll; } var names$29 = ["Robinson", "robin"]; var robin = { init: init$28, forward: forward$27, inverse: inverse$27, names: names$29 }; function init$29() { this.name = 'geocent'; } function forward$28(p) { var point = geodeticToGeocentric(p, this.es, this.a); return point; } function inverse$28(p) { var point = geocentricToGeodetic(p, this.es, this.a, this.b); return point; } var names$30 = ["Geocentric", 'geocentric', "geocent", "Geocent"]; var geocent = { init: init$29, forward: forward$28, inverse: inverse$28, names: names$30 }; var mode = { N_POLE: 0, S_POLE: 1, EQUIT: 2, OBLIQ: 3 }; var params = { h: { def: 100000, num: true }, // default is Karman line, no default in PROJ.7 azi: { def: 0, num: true, degrees: true }, // default is North tilt: { def: 0, num: true, degrees: true }, // default is Nadir long0: { def: 0, num: true }, // default is Greenwich, conversion to rad is automatic lat0: { def: 0, num: true } // default is Equator, conversion to rad is automatic }; function init$30() { Object.keys(params).forEach(function (p) { if (typeof this[p] === "undefined") { this[p] = params[p].def; } else if (params[p].num && isNaN(this[p])) { throw new Error("Invalid parameter value, must be numeric " + p + " = " + this[p]); } else if (params[p].num) { this[p] = parseFloat(this[p]); } if (params[p].degrees) { this[p] = this[p] * D2R; } }.bind(this)); if (Math.abs((Math.abs(this.lat0) - HALF_PI)) < EPSLN) { this.mode = this.lat0 < 0 ? mode.S_POLE : mode.N_POLE; } else if (Math.abs(this.lat0) < EPSLN) { this.mode = mode.EQUIT; } else { this.mode = mode.OBLIQ; this.sinph0 = Math.sin(this.lat0); this.cosph0 = Math.cos(this.lat0); } this.pn1 = this.h / this.a; // Normalize relative to the Earth's radius if (this.pn1 <= 0 || this.pn1 > 1e10) { throw new Error("Invalid height"); } this.p = 1 + this.pn1; this.rp = 1 / this.p; this.h1 = 1 / this.pn1; this.pfact = (this.p + 1) * this.h1; this.es = 0; var omega = this.tilt; var gamma = this.azi; this.cg = Math.cos(gamma); this.sg = Math.sin(gamma); this.cw = Math.cos(omega); this.sw = Math.sin(omega); } function forward$29(p) { p.x -= this.long0; var sinphi = Math.sin(p.y); var cosphi = Math.cos(p.y); var coslam = Math.cos(p.x); var x, y; switch (this.mode) { case mode.OBLIQ: y = this.sinph0 * sinphi + this.cosph0 * cosphi * coslam; break; case mode.EQUIT: y = cosphi * coslam; break; case mode.S_POLE: y = -sinphi; break; case mode.N_POLE: y = sinphi; break; } y = this.pn1 / (this.p - y); x = y * cosphi * Math.sin(p.x); switch (this.mode) { case mode.OBLIQ: y *= this.cosph0 * sinphi - this.sinph0 * cosphi * coslam; break; case mode.EQUIT: y *= sinphi; break; case mode.N_POLE: y *= -(cosphi * coslam); break; case mode.S_POLE: y *= cosphi * coslam; break; } // Tilt var yt, ba; yt = y * this.cg + x * this.sg; ba = 1 / (yt * this.sw * this.h1 + this.cw); x = (x * this.cg - y * this.sg) * this.cw * ba; y = yt * ba; p.x = x * this.a; p.y = y * this.a; return p; } function inverse$29(p) { p.x /= this.a; p.y /= this.a; var r = { x: p.x, y: p.y }; // Un-Tilt var bm, bq, yt; yt = 1 / (this.pn1 - p.y * this.sw); bm = this.pn1 * p.x * yt; bq = this.pn1 * p.y * this.cw * yt; p.x = bm * this.cg + bq * this.sg; p.y = bq * this.cg - bm * this.sg; var rh = hypot(p.x, p.y); if (Math.abs(rh) < EPSLN) { r.x = 0; r.y = p.y; } else { var cosz, sinz; sinz = 1 - rh * rh * this.pfact; sinz = (this.p - Math.sqrt(sinz)) / (this.pn1 / rh + rh / this.pn1); cosz = Math.sqrt(1 - sinz * sinz); switch (this.mode) { case mode.OBLIQ: r.y = Math.asin(cosz * this.sinph0 + p.y * sinz * this.cosph0 / rh); p.y = (cosz - this.sinph0 * Math.sin(r.y)) * rh; p.x *= sinz * this.cosph0; break; case mode.EQUIT: r.y = Math.asin(p.y * sinz / rh); p.y = cosz * rh; p.x *= sinz; break; case mode.N_POLE: r.y = Math.asin(cosz); p.y = -p.y; break; case mode.S_POLE: r.y = -Math.asin(cosz); break; } r.x = Math.atan2(p.x, p.y); } p.x = r.x + this.long0; p.y = r.y; return p; } var names$31 = ["Tilted_Perspective", "tpers"]; var tpers = { init: init$30, forward: forward$29, inverse: inverse$29, names: names$31 }; function init$31() { this.flip_axis = (this.sweep === 'x' ? 1 : 0); this.h = Number(this.h); this.radius_g_1 = this.h / this.a; if (this.radius_g_1 <= 0 || this.radius_g_1 > 1e10) { throw new Error(); } this.radius_g = 1.0 + this.radius_g_1; this.C = this.radius_g * this.radius_g - 1.0; if (this.es !== 0.0) { var one_es = 1.0 - this.es; var rone_es = 1 / one_es; this.radius_p = Math.sqrt(one_es); this.radius_p2 = one_es; this.radius_p_inv2 = rone_es; this.shape = 'ellipse'; // Use as a condition in the forward and inverse functions. } else { this.radius_p = 1.0; this.radius_p2 = 1.0; this.radius_p_inv2 = 1.0; this.shape = 'sphere'; // Use as a condition in the forward and inverse functions. } if (!this.title) { this.title = "Geostationary Satellite View"; } } function forward$30(p) { var lon = p.x; var lat = p.y; var tmp, v_x, v_y, v_z; lon = lon - this.long0; if (this.shape === 'ellipse') { lat = Math.atan(this.radius_p2 * Math.tan(lat)); var r = this.radius_p / hypot(this.radius_p * Math.cos(lat), Math.sin(lat)); v_x = r * Math.cos(lon) * Math.cos(lat); v_y = r * Math.sin(lon) * Math.cos(lat); v_z = r * Math.sin(lat); if (((this.radius_g - v_x) * v_x - v_y * v_y - v_z * v_z * this.radius_p_inv2) < 0.0) { p.x = Number.NaN; p.y = Number.NaN; return p; } tmp = this.radius_g - v_x; if (this.flip_axis) { p.x = this.radius_g_1 * Math.atan(v_y / hypot(v_z, tmp)); p.y = this.radius_g_1 * Math.atan(v_z / tmp); } else { p.x = this.radius_g_1 * Math.atan(v_y / tmp); p.y = this.radius_g_1 * Math.atan(v_z / hypot(v_y, tmp)); } } else if (this.shape === 'sphere') { tmp = Math.cos(lat); v_x = Math.cos(lon) * tmp; v_y = Math.sin(lon) * tmp; v_z = Math.sin(lat); tmp = this.radius_g - v_x; if (this.flip_axis) { p.x = this.radius_g_1 * Math.atan(v_y / hypot(v_z, tmp)); p.y = this.radius_g_1 * Math.atan(v_z / tmp); } else { p.x = this.radius_g_1 * Math.atan(v_y / tmp); p.y = this.radius_g_1 * Math.atan(v_z / hypot(v_y, tmp)); } } p.x = p.x * this.a; p.y = p.y * this.a; return p; } function inverse$30(p) { var v_x = -1.0; var v_y = 0.0; var v_z = 0.0; var a, b, det, k; p.x = p.x / this.a; p.y = p.y / this.a; if (this.shape === 'ellipse') { if (this.flip_axis) { v_z = Math.tan(p.y / this.radius_g_1); v_y = Math.tan(p.x / this.radius_g_1) * hypot(1.0, v_z); } else { v_y = Math.tan(p.x / this.radius_g_1); v_z = Math.tan(p.y / this.radius_g_1) * hypot(1.0, v_y); } var v_zp = v_z / this.radius_p; a = v_y * v_y + v_zp * v_zp + v_x * v_x; b = 2 * this.radius_g * v_x; det = (b * b) - 4 * a * this.C; if (det < 0.0) { p.x = Number.NaN; p.y = Number.NaN; return p; } k = (-b - Math.sqrt(det)) / (2.0 * a); v_x = this.radius_g + k * v_x; v_y *= k; v_z *= k; p.x = Math.atan2(v_y, v_x); p.y = Math.atan(v_z * Math.cos(p.x) / v_x); p.y = Math.atan(this.radius_p_inv2 * Math.tan(p.y)); } else if (this.shape === 'sphere') { if (this.flip_axis) { v_z = Math.tan(p.y / this.radius_g_1); v_y = Math.tan(p.x / this.radius_g_1) * Math.sqrt(1.0 + v_z * v_z); } else { v_y = Math.tan(p.x / this.radius_g_1); v_z = Math.tan(p.y / this.radius_g_1) * Math.sqrt(1.0 + v_y * v_y); } a = v_y * v_y + v_z * v_z + v_x * v_x; b = 2 * this.radius_g * v_x; det = (b * b) - 4 * a * this.C; if (det < 0.0) { p.x = Number.NaN; p.y = Number.NaN; return p; } k = (-b - Math.sqrt(det)) / (2.0 * a); v_x = this.radius_g + k * v_x; v_y *= k; v_z *= k; p.x = Math.atan2(v_y, v_x); p.y = Math.atan(v_z * Math.cos(p.x) / v_x); } p.x = p.x + this.long0; return p; } var names$32 = ["Geostationary Satellite View", "Geostationary_Satellite", "geos"]; var geos = { init: init$31, forward: forward$30, inverse: inverse$30, names: names$32, }; var includedProjections = function(proj4){ proj4.Proj.projections.add(tmerc); proj4.Proj.projections.add(etmerc); proj4.Proj.projections.add(utm); proj4.Proj.projections.add(sterea); proj4.Proj.projections.add(stere); proj4.Proj.projections.add(somerc); proj4.Proj.projections.add(omerc); proj4.Proj.projections.add(lcc); proj4.Proj.projections.add(krovak); proj4.Proj.projections.add(cass); proj4.Proj.projections.add(laea); proj4.Proj.projections.add(aea); proj4.Proj.projections.add(gnom); proj4.Proj.projections.add(cea); proj4.Proj.projections.add(eqc); proj4.Proj.projections.add(poly); proj4.Proj.projections.add(nzmg); proj4.Proj.projections.add(mill); proj4.Proj.projections.add(sinu); proj4.Proj.projections.add(moll); proj4.Proj.projections.add(eqdc); proj4.Proj.projections.add(vandg); proj4.Proj.projections.add(aeqd); proj4.Proj.projections.add(ortho); proj4.Proj.projections.add(qsc); proj4.Proj.projections.add(robin); proj4.Proj.projections.add(geocent); proj4.Proj.projections.add(tpers); proj4.Proj.projections.add(geos); }; proj4$1.defaultDatum = 'WGS84'; //default datum proj4$1.Proj = Projection; proj4$1.WGS84 = new proj4$1.Proj('WGS84'); proj4$1.Point = Point; proj4$1.toPoint = toPoint; proj4$1.defs = defs; proj4$1.nadgrid = nadgrid; proj4$1.transform = transform; proj4$1.mgrs = mgrs; proj4$1.version = '2.9.0'; includedProjections(proj4$1); return proj4$1; }))); /***/ }), /***/ 107: /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { (function (global, factory) { true ? factory() : 0; }(this, (function () { 'use strict'; /** * @this {Promise} */ function finallyConstructor(callback) { var constructor = this.constructor; return this.then( function(value) { // @ts-ignore return constructor.resolve(callback()).then(function() { return value; }); }, function(reason) { // @ts-ignore return constructor.resolve(callback()).then(function() { // @ts-ignore return constructor.reject(reason); }); } ); } function allSettled(arr) { var P = this; return new P(function(resolve, reject) { if (!(arr && typeof arr.length !== 'undefined')) { return reject( new TypeError( typeof arr + ' ' + arr + ' is not iterable(cannot read property Symbol(Symbol.iterator))' ) ); } var args = Array.prototype.slice.call(arr); if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call( val, function(val) { res(i, val); }, function(e) { args[i] = { status: 'rejected', reason: e }; if (--remaining === 0) { resolve(args); } } ); return; } } args[i] = { status: 'fulfilled', value: val }; if (--remaining === 0) { resolve(args); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); } // Store setTimeout reference so promise-polyfill will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var setTimeoutFunc = setTimeout; function isArray(x) { return Boolean(x && typeof x.length !== 'undefined'); } function noop() {} // Polyfill for Function.prototype.bind function bind(fn, thisArg) { return function() { fn.apply(thisArg, arguments); }; } /** * @constructor * @param {Function} fn */ function Promise(fn) { if (!(this instanceof Promise)) throw new TypeError('Promises must be constructed via new'); if (typeof fn !== 'function') throw new TypeError('not a function'); /** @type {!number} */ this._state = 0; /** @type {!boolean} */ this._handled = false; /** @type {Promise|undefined} */ this._value = undefined; /** @type {!Array} */ this._deferreds = []; doResolve(fn, this); } function handle(self, deferred) { while (self._state === 3) { self = self._value; } if (self._state === 0) { self._deferreds.push(deferred); return; } self._handled = true; Promise._immediateFn(function() { var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; if (cb === null) { (self._state === 1 ? resolve : reject)(deferred.promise, self._value); return; } var ret; try { ret = cb(self._value); } catch (e) { reject(deferred.promise, e); return; } resolve(deferred.promise, ret); }); } function resolve(self, newValue) { try { // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.'); if ( newValue && (typeof newValue === 'object' || typeof newValue === 'function') ) { var then = newValue.then; if (newValue instanceof Promise) { self._state = 3; self._value = newValue; finale(self); return; } else if (typeof then === 'function') { doResolve(bind(then, newValue), self); return; } } self._state = 1; self._value = newValue; finale(self); } catch (e) { reject(self, e); } } function reject(self, newValue) { self._state = 2; self._value = newValue; finale(self); } function finale(self) { if (self._state === 2 && self._deferreds.length === 0) { Promise._immediateFn(function() { if (!self._handled) { Promise._unhandledRejectionFn(self._value); } }); } for (var i = 0, len = self._deferreds.length; i < len; i++) { handle(self, self._deferreds[i]); } self._deferreds = null; } /** * @constructor */ function Handler(onFulfilled, onRejected, promise) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.promise = promise; } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, self) { var done = false; try { fn( function(value) { if (done) return; done = true; resolve(self, value); }, function(reason) { if (done) return; done = true; reject(self, reason); } ); } catch (ex) { if (done) return; done = true; reject(self, ex); } } Promise.prototype['catch'] = function(onRejected) { return this.then(null, onRejected); }; Promise.prototype.then = function(onFulfilled, onRejected) { // @ts-ignore var prom = new this.constructor(noop); handle(this, new Handler(onFulfilled, onRejected, prom)); return prom; }; Promise.prototype['finally'] = finallyConstructor; Promise.all = function(arr) { return new Promise(function(resolve, reject) { if (!isArray(arr)) { return reject(new TypeError('Promise.all accepts an array')); } var args = Array.prototype.slice.call(arr); if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call( val, function(val) { res(i, val); }, reject ); return; } } args[i] = val; if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); }; Promise.allSettled = allSettled; Promise.resolve = function(value) { if (value && typeof value === 'object' && value.constructor === Promise) { return value; } return new Promise(function(resolve) { resolve(value); }); }; Promise.reject = function(value) { return new Promise(function(resolve, reject) { reject(value); }); }; Promise.race = function(arr) { return new Promise(function(resolve, reject) { if (!isArray(arr)) { return reject(new TypeError('Promise.race accepts an array')); } for (var i = 0, len = arr.length; i < len; i++) { Promise.resolve(arr[i]).then(resolve, reject); } }); }; // Use polyfill for setImmediate for performance gains Promise._immediateFn = // @ts-ignore (typeof setImmediate === 'function' && function(fn) { // @ts-ignore setImmediate(fn); }) || function(fn) { setTimeoutFunc(fn, 0); }; Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) { if (typeof console !== 'undefined' && console) { console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console } }; /** @suppress {undefinedVars} */ var globalNS = (function() { // the only reliable means to get the global object is // `Function('return this')()` // However, this causes CSP violations in Chrome apps. if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof __webpack_require__.g !== 'undefined') { return __webpack_require__.g; } throw new Error('unable to locate global object'); })(); // Expose the polyfill if Promise is undefined or set to a // non-function value. The latter can be due to a named HTMLElement // being exposed by browsers for legacy reasons. // https://github.com/taylorhakes/promise-polyfill/issues/114 if (typeof globalNS['Promise'] !== 'function') { globalNS['Promise'] = Promise; } else { if (!globalNS.Promise.prototype['finally']) { globalNS.Promise.prototype['finally'] = finallyConstructor; } if (!globalNS.Promise.allSettled) { globalNS.Promise.allSettled = allSettled; } } }))); /***/ }), /***/ 901: /***/ (function(module) { // https://github.com/mbostock/slice-source Version 0.4.1. Copyright 2016 Mike Bostock. (function (global, factory) { true ? module.exports = factory() : 0; }(this, (function () { 'use strict'; var empty = new Uint8Array(0); function slice_cancel() { return this._source.cancel(); } function concat(a, b) { if (!a.length) return b; if (!b.length) return a; var c = new Uint8Array(a.length + b.length); c.set(a); c.set(b, a.length); return c; } function slice_read() { var that = this, array = that._array.subarray(that._index); return that._source.read().then(function(result) { that._array = empty; that._index = 0; return result.done ? (array.length > 0 ? {done: false, value: array} : {done: true, value: undefined}) : {done: false, value: concat(array, result.value)}; }); } function slice_slice(length) { if ((length |= 0) < 0) throw new Error("invalid length"); var that = this, index = this._array.length - this._index; // If the request fits within the remaining buffer, resolve it immediately. if (this._index + length <= this._array.length) { return Promise.resolve(this._array.subarray(this._index, this._index += length)); } // Otherwise, read chunks repeatedly until the request is fulfilled. var array = new Uint8Array(length); array.set(this._array.subarray(this._index)); return (function read() { return that._source.read().then(function(result) { // When done, it’s possible the request wasn’t fully fullfilled! // If so, the pre-allocated array is too big and needs slicing. if (result.done) { that._array = empty; that._index = 0; return index > 0 ? array.subarray(0, index) : null; } // If this chunk fulfills the request, return the resulting array. if (index + result.value.length >= length) { that._array = result.value; that._index = length - index; array.set(result.value.subarray(0, length - index), index); return array; } // Otherwise copy this chunk into the array, then read the next chunk. array.set(result.value, index); index += result.value.length; return read(); }); })(); } function slice(source) { return typeof source.slice === "function" ? source : new SliceSource(typeof source.read === "function" ? source : source.getReader()); } function SliceSource(source) { this._source = source; this._array = empty; this._index = 0; } SliceSource.prototype.read = slice_read; SliceSource.prototype.slice = slice_slice; SliceSource.prototype.cancel = slice_cancel; return slice; }))); /***/ }), /***/ 982: /***/ ((__unused_webpack_module, exports) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } /** An error subclass which is thrown when there are too many pending push or next operations on a single repeater. */ var RepeaterOverflowError = /** @class */ (function (_super) { __extends(RepeaterOverflowError, _super); function RepeaterOverflowError(message) { var _this = _super.call(this, message) || this; Object.defineProperty(_this, "name", { value: "RepeaterOverflowError", enumerable: false, }); if (typeof Object.setPrototypeOf === "function") { Object.setPrototypeOf(_this, _this.constructor.prototype); } else { _this.__proto__ = _this.constructor.prototype; } if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(_this, _this.constructor); } return _this; } return RepeaterOverflowError; }(Error)); /** A buffer which allows you to push a set amount of values to the repeater without pushes waiting or throwing errors. */ var FixedBuffer = /** @class */ (function () { function FixedBuffer(capacity) { if (capacity < 0) { throw new RangeError("Capacity may not be less than 0"); } this._c = capacity; this._q = []; } Object.defineProperty(FixedBuffer.prototype, "empty", { get: function () { return this._q.length === 0; }, enumerable: false, configurable: true }); Object.defineProperty(FixedBuffer.prototype, "full", { get: function () { return this._q.length >= this._c; }, enumerable: false, configurable: true }); FixedBuffer.prototype.add = function (value) { if (this.full) { throw new Error("Buffer full"); } else { this._q.push(value); } }; FixedBuffer.prototype.remove = function () { if (this.empty) { throw new Error("Buffer empty"); } return this._q.shift(); }; return FixedBuffer; }()); // TODO: Use a circular buffer here. /** Sliding buffers allow you to push a set amount of values to the repeater without pushes waiting or throwing errors. If the number of values exceeds the capacity set in the constructor, the buffer will discard the earliest values added. */ var SlidingBuffer = /** @class */ (function () { function SlidingBuffer(capacity) { if (capacity < 1) { throw new RangeError("Capacity may not be less than 1"); } this._c = capacity; this._q = []; } Object.defineProperty(SlidingBuffer.prototype, "empty", { get: function () { return this._q.length === 0; }, enumerable: false, configurable: true }); Object.defineProperty(SlidingBuffer.prototype, "full", { get: function () { return false; }, enumerable: false, configurable: true }); SlidingBuffer.prototype.add = function (value) { while (this._q.length >= this._c) { this._q.shift(); } this._q.push(value); }; SlidingBuffer.prototype.remove = function () { if (this.empty) { throw new Error("Buffer empty"); } return this._q.shift(); }; return SlidingBuffer; }()); /** Dropping buffers allow you to push a set amount of values to the repeater without the push function waiting or throwing errors. If the number of values exceeds the capacity set in the constructor, the buffer will discard the latest values added. */ var DroppingBuffer = /** @class */ (function () { function DroppingBuffer(capacity) { if (capacity < 1) { throw new RangeError("Capacity may not be less than 1"); } this._c = capacity; this._q = []; } Object.defineProperty(DroppingBuffer.prototype, "empty", { get: function () { return this._q.length === 0; }, enumerable: false, configurable: true }); Object.defineProperty(DroppingBuffer.prototype, "full", { get: function () { return false; }, enumerable: false, configurable: true }); DroppingBuffer.prototype.add = function (value) { if (this._q.length < this._c) { this._q.push(value); } }; DroppingBuffer.prototype.remove = function () { if (this.empty) { throw new Error("Buffer empty"); } return this._q.shift(); }; return DroppingBuffer; }()); /** Makes sure promise-likes don’t cause unhandled rejections. */ function swallow(value) { if (value != null && typeof value.then === "function") { value.then(NOOP, NOOP); } } /*** REPEATER STATES ***/ /** The following is an enumeration of all possible repeater states. These states are ordered, and a repeater may only advance to higher states. */ /** The initial state of the repeater. */ var Initial = 0; /** Repeaters advance to this state the first time the next method is called on the repeater. */ var Started = 1; /** Repeaters advance to this state when the stop function is called. */ var Stopped = 2; /** Repeaters advance to this state when there are no values left to be pulled from the repeater. */ var Done = 3; /** Repeaters advance to this state if an error is thrown into the repeater. */ var Rejected = 4; /** The maximum number of push or next operations which may exist on a single repeater. */ var MAX_QUEUE_LENGTH = 1024; var NOOP = function () { }; /** A helper function used to mimic the behavior of async generators where the final iteration is consumed. */ function consumeExecution(r) { var err = r.err; var execution = Promise.resolve(r.execution).then(function (value) { if (err != null) { throw err; } return value; }); r.err = undefined; r.execution = execution.then(function () { return undefined; }, function () { return undefined; }); return r.pending === undefined ? execution : r.pending.then(function () { return execution; }); } /** A helper function for building iterations from values. Promises are unwrapped, so that iterations never have their value property set to a promise. */ function createIteration(r, value) { var done = r.state >= Done; return Promise.resolve(value).then(function (value) { if (!done && r.state >= Rejected) { return consumeExecution(r).then(function (value) { return ({ value: value, done: true, }); }); } return { value: value, done: done }; }); } /** * This function is bound and passed to the executor as the stop argument. * * Advances state to Stopped. */ function stop(r, err) { var e_1, _a; if (r.state >= Stopped) { return; } r.state = Stopped; r.onnext(); r.onstop(); if (r.err == null) { r.err = err; } if (r.pushes.length === 0 && (typeof r.buffer === "undefined" || r.buffer.empty)) { finish(r); } else { try { for (var _b = __values(r.pushes), _d = _b.next(); !_d.done; _d = _b.next()) { var push_1 = _d.value; push_1.resolve(); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } } } /** * The difference between stopping a repeater vs finishing a repeater is that stopping a repeater allows next to continue to drain values from the push queue and buffer, while finishing a repeater will clear all pending values and end iteration immediately. Once, a repeater is finished, all iterations will have the done property set to true. * * Advances state to Done. */ function finish(r) { var e_2, _a; if (r.state >= Done) { return; } if (r.state < Stopped) { stop(r); } r.state = Done; r.buffer = undefined; try { for (var _b = __values(r.nexts), _d = _b.next(); !_d.done; _d = _b.next()) { var next = _d.value; var execution = r.pending === undefined ? consumeExecution(r) : r.pending.then(function () { return consumeExecution(r); }); next.resolve(createIteration(r, execution)); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_d && !_d.done && (_a = _b.return)) _a.call(_b); } finally { if (e_2) throw e_2.error; } } r.pushes = []; r.nexts = []; } /** * Called when a promise passed to push rejects, or when a push call is unhandled. * * Advances state to Rejected. */ function reject(r) { if (r.state >= Rejected) { return; } if (r.state < Done) { finish(r); } r.state = Rejected; } /** This function is bound and passed to the executor as the push argument. */ function push(r, value) { swallow(value); if (r.pushes.length >= MAX_QUEUE_LENGTH) { throw new RepeaterOverflowError("No more than " + MAX_QUEUE_LENGTH + " pending calls to push are allowed on a single repeater."); } else if (r.state >= Stopped) { return Promise.resolve(undefined); } var valueP = r.pending === undefined ? Promise.resolve(value) : r.pending.then(function () { return value; }); valueP = valueP.catch(function (err) { if (r.state < Stopped) { r.err = err; } reject(r); return undefined; // void :( }); var nextP; if (r.nexts.length) { var next_1 = r.nexts.shift(); next_1.resolve(createIteration(r, valueP)); if (r.nexts.length) { nextP = Promise.resolve(r.nexts[0].value); } else { nextP = new Promise(function (resolve) { return (r.onnext = resolve); }); } } else if (typeof r.buffer !== "undefined" && !r.buffer.full) { r.buffer.add(valueP); nextP = Promise.resolve(undefined); } else { nextP = new Promise(function (resolve) { return r.pushes.push({ resolve: resolve, value: valueP }); }); } // If an error is thrown into the repeater via the next or throw methods, we give the repeater a chance to handle this by rejecting the promise returned from push. If the push call is not immediately handled we throw the next iteration of the repeater. // To check that the promise returned from push is floating, we modify the then and catch methods of the returned promise so that they flip the floating flag. The push function actually does not return a promise, because modern engines do not call the then and catch methods on native promises. By making next a plain old javascript object, we ensure that the then and catch methods will be called. var floating = true; var next = {}; var unhandled = nextP.catch(function (err) { if (floating) { throw err; } return undefined; // void :( }); next.then = function (onfulfilled, onrejected) { floating = false; return Promise.prototype.then.call(nextP, onfulfilled, onrejected); }; next.catch = function (onrejected) { floating = false; return Promise.prototype.catch.call(nextP, onrejected); }; next.finally = nextP.finally.bind(nextP); r.pending = valueP .then(function () { return unhandled; }) .catch(function (err) { r.err = err; reject(r); }); return next; } /** * Creates the stop callable promise which is passed to the executor */ function createStop(r) { var stop1 = stop.bind(null, r); var stopP = new Promise(function (resolve) { return (r.onstop = resolve); }); stop1.then = stopP.then.bind(stopP); stop1.catch = stopP.catch.bind(stopP); stop1.finally = stopP.finally.bind(stopP); return stop1; } /** * Calls the executor passed into the constructor. This function is called the first time the next method is called on the repeater. * * Advances state to Started. */ function execute(r) { if (r.state >= Started) { return; } r.state = Started; var push1 = push.bind(null, r); var stop1 = createStop(r); r.execution = new Promise(function (resolve) { return resolve(r.executor(push1, stop1)); }); // TODO: We should consider stopping all repeaters when the executor settles. r.execution.catch(function () { return stop(r); }); } var records = new WeakMap(); // NOTE: While repeaters implement and are assignable to the AsyncGenerator interface, and you can use the types interchangeably, we don’t use typescript’s implements syntax here because this would make supporting earlier versions of typescript trickier. This is because TypeScript version 3.6 changed the iterator types by adding the TReturn and TNext type parameters. var Repeater = /** @class */ (function () { function Repeater(executor, buffer) { records.set(this, { executor: executor, buffer: buffer, err: undefined, state: Initial, pushes: [], nexts: [], pending: undefined, execution: undefined, onnext: NOOP, onstop: NOOP, }); } Repeater.prototype.next = function (value) { swallow(value); var r = records.get(this); if (r === undefined) { throw new Error("WeakMap error"); } if (r.nexts.length >= MAX_QUEUE_LENGTH) { throw new RepeaterOverflowError("No more than " + MAX_QUEUE_LENGTH + " pending calls to next are allowed on a single repeater."); } if (r.state <= Initial) { execute(r); } r.onnext(value); if (typeof r.buffer !== "undefined" && !r.buffer.empty) { var result = createIteration(r, r.buffer.remove()); if (r.pushes.length) { var push_2 = r.pushes.shift(); r.buffer.add(push_2.value); r.onnext = push_2.resolve; } return result; } else if (r.pushes.length) { var push_3 = r.pushes.shift(); r.onnext = push_3.resolve; return createIteration(r, push_3.value); } else if (r.state >= Stopped) { finish(r); return createIteration(r, consumeExecution(r)); } return new Promise(function (resolve) { return r.nexts.push({ resolve: resolve, value: value }); }); }; Repeater.prototype.return = function (value) { swallow(value); var r = records.get(this); if (r === undefined) { throw new Error("WeakMap error"); } finish(r); // We override the execution because return should always return the value passed in. r.execution = Promise.resolve(r.execution).then(function () { return value; }); return createIteration(r, consumeExecution(r)); }; Repeater.prototype.throw = function (err) { var r = records.get(this); if (r === undefined) { throw new Error("WeakMap error"); } if (r.state <= Initial || r.state >= Stopped || (typeof r.buffer !== "undefined" && !r.buffer.empty)) { finish(r); // If r.err is already set, that mean the repeater has already produced an error, so we throw that error rather than the error passed in, because doing so might be more informative for the caller. if (r.err == null) { r.err = err; } return createIteration(r, consumeExecution(r)); } return this.next(Promise.reject(err)); }; Repeater.prototype[Symbol.asyncIterator] = function () { return this; }; // TODO: Remove these static methods from the class. Repeater.race = race; Repeater.merge = merge; Repeater.zip = zip; Repeater.latest = latest; return Repeater; }()); /*** COMBINATOR FUNCTIONS ***/ // TODO: move these combinators to their own file. function getIterators(values, options) { var e_3, _a; var iters = []; var _loop_1 = function (value) { if (value != null && typeof value[Symbol.asyncIterator] === "function") { iters.push(value[Symbol.asyncIterator]()); } else if (value != null && typeof value[Symbol.iterator] === "function") { iters.push(value[Symbol.iterator]()); } else { iters.push((function valueToAsyncIterator() { return __asyncGenerator(this, arguments, function valueToAsyncIterator_1() { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!options.yieldValues) return [3 /*break*/, 3]; return [4 /*yield*/, __await(value)]; case 1: return [4 /*yield*/, _a.sent()]; case 2: _a.sent(); _a.label = 3; case 3: if (!options.returnValues) return [3 /*break*/, 5]; return [4 /*yield*/, __await(value)]; case 4: return [2 /*return*/, _a.sent()]; case 5: return [2 /*return*/]; } }); }); })()); } }; try { for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) { var value = values_1_1.value; _loop_1(value); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1); } finally { if (e_3) throw e_3.error; } } return iters; } // NOTE: whenever you see any variables called `advance` or `advances`, know that it is a hack to get around the fact that `Promise.race` leaks memory. These variables are intended to be set to the resolve function of a promise which is constructed and awaited as an alternative to Promise.race. For more information, see this comment in the Node.js issue tracker: https://github.com/nodejs/node/issues/17469#issuecomment-685216777. function race(contenders) { var _this = this; var iters = getIterators(contenders, { returnValues: true }); return new Repeater(function (push, stop) { return __awaiter(_this, void 0, void 0, function () { var advance, stopped, finalIteration, iteration, i_1, _loop_2; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!iters.length) { stop(); return [2 /*return*/]; } stopped = false; stop.then(function () { advance(); stopped = true; }); _a.label = 1; case 1: _a.trys.push([1, , 5, 7]); iteration = void 0; i_1 = 0; _loop_2 = function () { var j, iters_1, iters_1_1, iter; var e_4, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: j = i_1; try { for (iters_1 = (e_4 = void 0, __values(iters)), iters_1_1 = iters_1.next(); !iters_1_1.done; iters_1_1 = iters_1.next()) { iter = iters_1_1.value; Promise.resolve(iter.next()).then(function (iteration) { if (iteration.done) { stop(); if (finalIteration === undefined) { finalIteration = iteration; } } else if (i_1 === j) { // This iterator has won, advance i and resolve the promise. i_1++; advance(iteration); } }, function (err) { return stop(err); }); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (iters_1_1 && !iters_1_1.done && (_a = iters_1.return)) _a.call(iters_1); } finally { if (e_4) throw e_4.error; } } return [4 /*yield*/, new Promise(function (resolve) { return (advance = resolve); })]; case 1: iteration = _b.sent(); if (!(iteration !== undefined)) return [3 /*break*/, 3]; return [4 /*yield*/, push(iteration.value)]; case 2: _b.sent(); _b.label = 3; case 3: return [2 /*return*/]; } }); }; _a.label = 2; case 2: if (!!stopped) return [3 /*break*/, 4]; return [5 /*yield**/, _loop_2()]; case 3: _a.sent(); return [3 /*break*/, 2]; case 4: return [2 /*return*/, finalIteration && finalIteration.value]; case 5: stop(); return [4 /*yield*/, Promise.race(iters.map(function (iter) { return iter.return && iter.return(); }))]; case 6: _a.sent(); return [7 /*endfinally*/]; case 7: return [2 /*return*/]; } }); }); }); } function merge(contenders) { var _this = this; var iters = getIterators(contenders, { yieldValues: true }); return new Repeater(function (push, stop) { return __awaiter(_this, void 0, void 0, function () { var advances, stopped, finalIteration; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!iters.length) { stop(); return [2 /*return*/]; } advances = []; stopped = false; stop.then(function () { var e_5, _a; stopped = true; try { for (var advances_1 = __values(advances), advances_1_1 = advances_1.next(); !advances_1_1.done; advances_1_1 = advances_1.next()) { var advance = advances_1_1.value; advance(); } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (advances_1_1 && !advances_1_1.done && (_a = advances_1.return)) _a.call(advances_1); } finally { if (e_5) throw e_5.error; } } }); _a.label = 1; case 1: _a.trys.push([1, , 3, 4]); return [4 /*yield*/, Promise.all(iters.map(function (iter, i) { return __awaiter(_this, void 0, void 0, function () { var iteration, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, , 6, 9]); _b.label = 1; case 1: if (!!stopped) return [3 /*break*/, 5]; Promise.resolve(iter.next()).then(function (iteration) { return advances[i](iteration); }, function (err) { return stop(err); }); return [4 /*yield*/, new Promise(function (resolve) { advances[i] = resolve; })]; case 2: iteration = _b.sent(); if (!(iteration !== undefined)) return [3 /*break*/, 4]; if (iteration.done) { finalIteration = iteration; return [2 /*return*/]; } return [4 /*yield*/, push(iteration.value)]; case 3: _b.sent(); _b.label = 4; case 4: return [3 /*break*/, 1]; case 5: return [3 /*break*/, 9]; case 6: _a = iter.return; if (!_a) return [3 /*break*/, 8]; return [4 /*yield*/, iter.return()]; case 7: _a = (_b.sent()); _b.label = 8; case 8: return [7 /*endfinally*/]; case 9: return [2 /*return*/]; } }); }); }))]; case 2: _a.sent(); return [2 /*return*/, finalIteration && finalIteration.value]; case 3: stop(); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }); } function zip(contenders) { var _this = this; var iters = getIterators(contenders, { returnValues: true }); return new Repeater(function (push, stop) { return __awaiter(_this, void 0, void 0, function () { var advance, stopped, iterations, values; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!iters.length) { stop(); return [2 /*return*/, []]; } stopped = false; stop.then(function () { advance(); stopped = true; }); _a.label = 1; case 1: _a.trys.push([1, , 6, 8]); _a.label = 2; case 2: if (!!stopped) return [3 /*break*/, 5]; Promise.all(iters.map(function (iter) { return iter.next(); })).then(function (iterations) { return advance(iterations); }, function (err) { return stop(err); }); return [4 /*yield*/, new Promise(function (resolve) { return (advance = resolve); })]; case 3: iterations = _a.sent(); if (iterations === undefined) { return [2 /*return*/]; } values = iterations.map(function (iteration) { return iteration.value; }); if (iterations.some(function (iteration) { return iteration.done; })) { return [2 /*return*/, values]; } return [4 /*yield*/, push(values)]; case 4: _a.sent(); return [3 /*break*/, 2]; case 5: return [3 /*break*/, 8]; case 6: stop(); return [4 /*yield*/, Promise.all(iters.map(function (iter) { return iter.return && iter.return(); }))]; case 7: _a.sent(); return [7 /*endfinally*/]; case 8: return [2 /*return*/]; } }); }); }); } function latest(contenders) { var _this = this; var iters = getIterators(contenders, { yieldValues: true, returnValues: true, }); return new Repeater(function (push, stop) { return __awaiter(_this, void 0, void 0, function () { var advance, advances, stopped, iterations_1, values_2; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!iters.length) { stop(); return [2 /*return*/, []]; } advances = []; stopped = false; stop.then(function () { var e_6, _a; advance(); try { for (var advances_2 = __values(advances), advances_2_1 = advances_2.next(); !advances_2_1.done; advances_2_1 = advances_2.next()) { var advance1 = advances_2_1.value; advance1(); } } catch (e_6_1) { e_6 = { error: e_6_1 }; } finally { try { if (advances_2_1 && !advances_2_1.done && (_a = advances_2.return)) _a.call(advances_2); } finally { if (e_6) throw e_6.error; } } stopped = true; }); _a.label = 1; case 1: _a.trys.push([1, , 5, 7]); Promise.all(iters.map(function (iter) { return iter.next(); })).then(function (iterations) { return advance(iterations); }, function (err) { return stop(err); }); return [4 /*yield*/, new Promise(function (resolve) { return (advance = resolve); })]; case 2: iterations_1 = _a.sent(); if (iterations_1 === undefined) { return [2 /*return*/]; } values_2 = iterations_1.map(function (iteration) { return iteration.value; }); if (iterations_1.every(function (iteration) { return iteration.done; })) { return [2 /*return*/, values_2]; } // We continuously yield and mutate the same values array so we shallow copy it each time it is pushed. return [4 /*yield*/, push(values_2.slice())]; case 3: // We continuously yield and mutate the same values array so we shallow copy it each time it is pushed. _a.sent(); return [4 /*yield*/, Promise.all(iters.map(function (iter, i) { return __awaiter(_this, void 0, void 0, function () { var iteration; return __generator(this, function (_a) { switch (_a.label) { case 0: if (iterations_1[i].done) { return [2 /*return*/, iterations_1[i].value]; } _a.label = 1; case 1: if (!!stopped) return [3 /*break*/, 4]; Promise.resolve(iter.next()).then(function (iteration) { return advances[i](iteration); }, function (err) { return stop(err); }); return [4 /*yield*/, new Promise(function (resolve) { return (advances[i] = resolve); })]; case 2: iteration = _a.sent(); if (iteration === undefined) { return [2 /*return*/, iterations_1[i].value]; } else if (iteration.done) { return [2 /*return*/, iteration.value]; } values_2[i] = iteration.value; return [4 /*yield*/, push(values_2.slice())]; case 3: _a.sent(); return [3 /*break*/, 1]; case 4: return [2 /*return*/]; } }); }); }))]; case 4: return [2 /*return*/, _a.sent()]; case 5: stop(); return [4 /*yield*/, Promise.all(iters.map(function (iter) { return iter.return && iter.return(); }))]; case 6: _a.sent(); return [7 /*endfinally*/]; case 7: return [2 /*return*/]; } }); }); }); } __webpack_unused_export__ = DroppingBuffer; __webpack_unused_export__ = FixedBuffer; __webpack_unused_export__ = MAX_QUEUE_LENGTH; exports.ZN = Repeater; __webpack_unused_export__ = RepeaterOverflowError; __webpack_unused_export__ = SlidingBuffer; //# sourceMappingURL=repeater.js.map /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ id: moduleId, /******/ loaded: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/node module decorator */ /******/ (() => { /******/ __webpack_require__.nmd = (module) => { /******/ module.paths = []; /******/ if (!module.children) module.children = []; /******/ return module; /******/ }; /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be in strict mode. (() => { "use strict"; // UNUSED EXPORTS: AddressMatchService, AggregationParameter, AggregationTypes, AlongLineDirection, AnalystAreaUnit, AnalystSizeUnit, AreaSolarRadiationParameters, ArrayStatistic, AttributesPopContainer, BaiduMap, Bounds, Browser, BucketAggParameter, BucketAggType, BufferAnalystParameters, BufferDistance, BufferEndType, BufferRadiusUnit, BufferSetting, BuffersAnalystJobsParameter, BurstPipelineAnalystParameters, CartoCSS, ChangeTileVersion, ChartQueryFilterParameter, ChartQueryParameters, ChartService, ChartType, ChartView, ChartViewModel, CityTabsPage, ClientType, ClipAnalystMode, ClipParameter, CloverShape, ColorDictionary, ColorGradientType, ColorSpaceType, ColorsPickerUtil, CommonContainer, CommonServiceBase, CommonTheme, CommonUtil, ComponentsUtil, ComputeWeightMatrixParameters, CreateDatasetParameters, Credential, DataFlow, DataFlowService, DataFormat, DataItemOrderBy, DataItemType, DataReturnMode, DataReturnOption, DatasetBufferAnalystParameters, DatasetInfo, DatasetOverlayAnalystParameters, DatasetService, DatasetSurfaceAnalystParameters, DatasetThiessenAnalystParameters, DatasourceConnectionInfo, DatasourceService, DeafultCanvasStyle, DensityKernelAnalystParameters, DirectionType, DropDownBox, EditFeaturesParameters, EditType, ElasticSearch, EngineType, EntityType, Event, Events, Exponent, FGB, FacilityAnalyst3DParameters, FacilityAnalystSinks3DParameters, FacilityAnalystSources3DParameters, FacilityAnalystStreamParameters, FacilityAnalystTracedown3DParameters, FacilityAnalystTraceup3DParameters, FacilityAnalystUpstream3DParameters, Feature, FeatureService, FeatureShapeFactory, FeatureTheme, FeatureThemeGraph, FeatureThemeRankSymbol, FeatureThemeVector, FeatureVector, FetchRequest, FieldParameters, FieldService, FieldStatisticsParameters, FieldsFilter, FileReaderUtil, FillGradientMode, FilterField, FilterParameter, FindClosestFacilitiesParameters, FindLocationParameters, FindMTSPPathsParameters, FindPathParameters, FindServiceAreasParameters, FindTSPPathsParameters, Format, GenerateSpatialDataParameters, GeoCodingParameter, GeoDecodingParameter, GeoFeature, GeoHashGridAggParameter, GeoJSONFormat, GeoRelationAnalystParameters, Geometry, GeometryBufferAnalystParameters, GeometryCollection, GeometryCurve, GeometryGeoText, GeometryLineString, GeometryLinearRing, GeometryMultiLineString, GeometryMultiPoint, GeometryMultiPolygon, GeometryOverlayAnalystParameters, GeometryPoint, GeometryPolygon, GeometryRectangle, GeometrySurfaceAnalystParameters, GeometryThiessenAnalystParameters, GeometryType, GeoprocessingService, GetFeatureMode, GetFeaturesByBoundsParameters, GetFeaturesByBufferParameters, GetFeaturesByGeometryParameters, GetFeaturesByIDsParameters, GetFeaturesBySQLParameters, GetFeaturesParametersBase, GetFeaturesServiceBase, GetGridCellInfosParameters, GraduatedMode, Graph, GraphAxesTextDisplayMode, Graphic, GraphicCanvasRenderer, GraphicWebGLRenderer, Grid, GridCellInfosService, GridType, HeatMap, HillshadeParameter, HitCloverShape, IManager, IManagerCreateNodeParam, IManagerServiceBase, IPortal, IPortalAddDataParam, IPortalAddResourceParam, IPortalDataConnectionInfoParam, IPortalDataMetaInfoParam, IPortalDataStoreInfoParam, IPortalQueryParam, IPortalQueryResult, IPortalRegisterServiceParam, IPortalResource, IPortalServiceBase, IPortalShareEntity, IPortalShareParam, IPortalUser, ImageCollectionService, ImageGFAspect, ImageGFHillShade, ImageGFOrtho, ImageGFSlope, ImageRenderingRule, ImageSearchParameter, ImageService, ImageStretchOption, ImageSuperMapRest, ImageTileSuperMapRest, IndexTabsPageContainer, InterpolationAlgorithmType, InterpolationAnalystParameters, InterpolationDensityAnalystParameters, InterpolationIDWAnalystParameters, InterpolationKrigingAnalystParameters, InterpolationRBFAnalystParameters, JSONFormat, JoinItem, JoinType, KernelDensityJobParameter, KeyServiceParameter, Label, LabelBackShape, LabelImageCell, LabelMatrixCell, LabelMixedTextStyle, LabelOverLengthMode, LabelSymbolCell, LabelThemeCell, Lang, LayerInfoService, LayerStatus, LayerType, LinkItem, Logo, LonLat, MapExtend, MapService, MapboxStyles, MappingParameters, Mapv, MapvCanvasLayer, MapvLayer, MathExpressionAnalysisParameters, MeasureMode, MeasureParameters, MeasureService, MessageBox, MetricsAggParameter, MetricsAggType, NDVIParameter, NavTabsPage, NetworkAnalyst3DService, NetworkAnalystService, NetworkAnalystServiceBase, Online, OnlineData, OnlineQueryDatasParameter, OnlineServiceBase, OrderBy, OrderType, OutputSetting, OutputType, OverlapDisplayedOptions, OverlayAnalystParameters, OverlayGeoJobParameter, OverlayGraphic, OverlayOperationType, PaginationContainer, PermissionType, Pixel, PixelFormat, PointWithMeasure, PopContainer, ProcessingService, ProcessingServiceBase, QueryByBoundsParameters, QueryByDistanceParameters, QueryByGeometryParameters, QueryBySQLParameters, QueryOption, QueryParameters, QueryService, Range, RangeMode, RankSymbol, RasterFunctionParameter, RasterFunctionType, ResourceType, Route, RouteCalculateMeasureParameters, RouteLocatorParameters, ScaleLine, SearchMode, SearchType, SecurityManager, Select, ServerColor, ServerFeature, ServerGeometry, ServerInfo, ServerStyle, ServerTextStyle, ServerTheme, ServerType, ServiceBase, ServiceStatus, SetDatasourceParameters, SetLayerInfoParameters, SetLayerStatusParameters, SetLayersInfoParameters, ShapeParameters, ShapeParametersCircle, ShapeParametersImage, ShapeParametersLabel, ShapeParametersLine, ShapeParametersPoint, ShapeParametersPolygon, ShapeParametersRectangle, ShapeParametersSector, SideType, SingleObjectQueryJobsParameter, Size, SmoothMethod, Sortby, SpatialAnalystBase, SpatialAnalystService, SpatialQueryMode, SpatialRelationType, StatisticAnalystMode, StatisticMode, StopQueryParameters, StyleMap, StyleUtils, SummaryAttributesJobsParameter, SummaryMeshJobParameter, SummaryRegionJobParameter, SummaryType, SuperMap, SuperMapCloud, SupplyCenter, SupplyCenterType, SurfaceAnalystMethod, SurfaceAnalystParameters, SurfaceAnalystParametersSetting, TemplateBase, TerrainCurvatureCalculationParameters, TextAlignment, Theme, ThemeDotDensity, ThemeFeature, ThemeGraduatedSymbol, ThemeGraduatedSymbolStyle, ThemeGraph, ThemeGraphAxes, ThemeGraphItem, ThemeGraphSize, ThemeGraphText, ThemeGraphTextFormat, ThemeGraphType, ThemeGridRange, ThemeGridRangeItem, ThemeGridUnique, ThemeGridUniqueItem, ThemeLabel, ThemeLabelAlongLine, ThemeLabelBackground, ThemeLabelItem, ThemeLabelText, ThemeLabelUniqueItem, ThemeMemoryData, ThemeOffset, ThemeParameters, ThemeRange, ThemeRangeItem, ThemeService, ThemeStyle, ThemeType, ThemeUnique, ThemeUniqueItem, ThiessenAnalystParameters, Tianditu, TileSuperMapRest, TimeControlBase, TimeFlowControl, TokenServiceParameter, TopologyValidatorJobsParameter, TopologyValidatorRule, TrafficTransferAnalystService, TransferLine, TransferPathParameters, TransferPreference, TransferSolutionParameters, TransferTactic, TransportationAnalystParameter, TransportationAnalystResultSetting, Turf, TurnType, UGCLayer, UGCLayerType, UGCMapLayer, UGCSubLayer, Unique, Unit, UpdateDatasetParameters, UpdateEdgeWeightParameters, UpdateTurnNodeWeightParameters, Util, VariogramMode, Vector, VectorClipJobsParameter, VectorTileStyles, VectorTileSuperMapRest, WKTFormat, WebExportFormatType, WebMap, WebPrintingJobContent, WebPrintingJobCustomItems, WebPrintingJobExportOptions, WebPrintingJobImage, WebPrintingJobLayers, WebPrintingJobLayoutOptions, WebPrintingJobLegendOptions, WebPrintingJobLittleMapOptions, WebPrintingJobNorthArrowOptions, WebPrintingJobParameters, WebPrintingJobScaleBarOptions, WebPrintingJobService, WebScaleOrientationType, WebScaleType, WebScaleUnit, conversionDegree, getMeterPerMapUnit, getWrapNum, initMap, isCORS, lineMap, lineStyle, pointMap, pointStyle, polygonMap, polygonStyle, setCORS, viewOptionsFromMapJSON ;// CONCATENATED MODULE: ./src/common/SuperMap.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ var SuperMap = window.SuperMap = window.SuperMap || {}; SuperMap.Components = window.SuperMap.Components || {}; ;// CONCATENATED MODULE: ./src/common/REST.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @enum DataFormat * @description 服务请求返回结果数据类型 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { DataFormat } from '{npm}'; * * const result = DataFormat.GEOJSON; * ``` */ var DataFormat = { /** GEOJSON */ GEOJSON: "GEOJSON", /** ISERVER */ ISERVER: "ISERVER", /** FGB */ FGB: "FGB" }; /** * @enum ServerType * @description 服务器类型 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ServerType } from '{npm}'; * * const result = ServerType.ISERVER; * ``` */ var ServerType = { /** ISERVER */ ISERVER: "ISERVER", /** IPORTAL */ IPORTAL: "IPORTAL", /** ONLINE */ ONLINE: "ONLINE" }; /** * @enum GeometryType * @description 几何对象枚举,定义了一系列几何对象类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { GeometryType } from '{npm}'; * * const result = GeometryType.LINE; * ``` */ var REST_GeometryType = { /** 线几何对象类型。 */ LINE: "LINE", /** 路由对象。 */ LINEM: "LINEM", /** 点几何对象类型。 */ POINT: "POINT", /** 面几何对象类型。 */ REGION: "REGION", /** EPS点几何对象。 */ POINTEPS: "POINTEPS", /** EPS线几何对象。 */ LINEEPS: "LINEEPS", /** EPS面几何对象。 */ REGIONEPS: "REGIONEPS", /** 椭圆。 */ ELLIPSE: "ELLIPSE", /** 圆。 */ CIRCLE: "CIRCLE", /** 文本几何对象类型。 */ TEXT: "TEXT", /** 矩形。 */ RECTANGLE: "RECTANGLE", /** 未定义。 */ UNKNOWN: "UNKNOWN", /** 复合几何对象类型。 */ GEOCOMPOUND:"GEOCOMPOUND" }; /** * @enum QueryOption * @description 查询结果类型枚举,描述查询结果返回类型,包括只返回属性、只返回几何实体以及返回属性和几何实体。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { QueryOption } from '{npm}'; * * const result = QueryOption.ATTRIBUTE; * ``` */ var QueryOption = { /** 属性。 */ ATTRIBUTE: "ATTRIBUTE", /** 属性和几何对象。 */ ATTRIBUTEANDGEOMETRY: "ATTRIBUTEANDGEOMETRY", /** 几何对象。 */ GEOMETRY: "GEOMETRY" }; /** * @enum JoinType * @description 关联查询时的关联类型常量。 * 该类定义了两个表之间的连接类型常量,决定了对两个表之间进行连接查询时,查询结果中得到的记录的情况。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { JoinType } from '{npm}'; * * const result = JoinType.INNERJOIN; * ``` */ var JoinType = { /** 内连接。 */ INNERJOIN: "INNERJOIN", /** 左连接。 */ LEFTJOIN: "LEFTJOIN" }; /** * @enum SpatialQueryMode * @description 空间查询模式枚举。该类定义了空间查询操作模式常量。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SpatialQueryMode } from '{npm}'; * * const result = SpatialQueryMode.CONTAIN; * ``` */ var SpatialQueryMode = { /** 包含空间查询模式。 */ CONTAIN: "CONTAIN", /** 交叉空间查询模式。 */ CROSS: "CROSS", /** 分离空间查询模式。 */ DISJOINT: "DISJOINT", /** 重合空间查询模式。 */ IDENTITY: "IDENTITY", /** 相交空间查询模式。 */ INTERSECT: "INTERSECT", /** 无空间查询。 */ NONE: "NONE", /** 叠加空间查询模式。 */ OVERLAP: "OVERLAP", /** 邻接空间查询模式。 */ TOUCH: "TOUCH", /** 被包含空间查询模式。 */ WITHIN: "WITHIN" }; /** * @enum SpatialRelationType * @description 数据集对象间的空间关系枚举。 * 该类定义了数据集对象间的空间关系类型常量。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SpatialRelationType } from '{npm}'; * * const result = {namespace}.SpatialRelationType.CONTAIN; * ``` */ var SpatialRelationType = { /** 包含关系。 */ CONTAIN: "CONTAIN", /** 相交关系。 */ INTERSECT: "INTERSECT", /** 被包含关系。 */ WITHIN: "WITHIN" }; /** * @enum MeasureMode * @type {string} * @description 量算模式枚举。 * @category BaseTypes Constant * 该类定义了两种测量模式:距离测量和面积测量。 * @usage * ``` * // 浏览器 * * * // ES6 Import * import { MeasureMode } from '{npm}'; * * const result = MeasureMode.DISTANCE; * ``` */ var MeasureMode = { /** 距离测量。 */ DISTANCE: "DISTANCE", /** 面积测量。 */ AREA: "AREA" }; /** * @enum Unit * @description 距离单位枚举。 * 该类定义了一系列距离单位类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { Unit } from '{npm}'; * * const result = Unit.METER; * ``` */ var Unit = { /** 米。 */ METER: "METER", /** 千米。 */ KILOMETER: "KILOMETER", /** 英里。 */ MILE: "MILE", /** 码。 */ YARD: "YARD", /** 度。 */ DEGREE: "DEGREE", /** 毫米。 */ MILLIMETER: "MILLIMETER", /** 厘米。 */ CENTIMETER: "CENTIMETER", /** 英寸。 */ INCH: "INCH", /** 分米。 */ DECIMETER: "DECIMETER", /** 英尺。 */ FOOT: "FOOT", /** 秒。 */ SECOND: "SECOND", /** 分。 */ MINUTE: "MINUTE", /** 弧度。 */ RADIAN: "RADIAN" }; /** * @enum BufferRadiusUnit * @description 缓冲区距离单位枚举。该类定义了一系列缓冲距离单位类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { BufferRadiusUnit } from '{npm}'; * * const result = BufferRadiusUnit.CENTIMETER; * ``` */ var BufferRadiusUnit = { /** 厘米。 */ CENTIMETER: "CENTIMETER", /** 分米。 */ DECIMETER: "DECIMETER", /** 英尺。 */ FOOT: "FOOT", /** 英寸。 */ INCH: "INCH", /** 千米。 */ KILOMETER: "KILOMETER", /** 米。 */ METER: "METER", /** 英里。 */ MILE: "MILE", /** 毫米。 */ MILLIMETER: "MILLIMETER", /** 码。 */ YARD: "YARD" } /** * @enum EngineType * @description 数据源引擎类型枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { EngineType } from '{npm}'; * * const result = EngineType.IMAGEPLUGINS; * ``` */ var EngineType = { /** 影像只读引擎类型,文件引擎,针对通用影像格式如 BMP,JPG,TIFF 以及超图自定义影像格式 SIT 等。 */ IMAGEPLUGINS: "IMAGEPLUGINS", /** OGC 引擎类型,针对于 Web 数据源,Web 引擎,目前支持的类型有 WMS,WFS,WCS。 */ OGC: "OGC", /** Oracle 引擎类型,针对 Oracle 数据源,数据库引擎。 */ ORACLEPLUS: "ORACLEPLUS", /** SDB 引擎类型,文件引擎,即 SDB 数据源。 */ SDBPLUS: "SDBPLUS", /** SQL Server 引擎类型,针对 SQL Server 数据源,数据库引擎。 */ SQLPLUS: "SQLPLUS", /** UDB 引擎类型,文件引擎。 */ UDB: "UDB" }; /** * @enum ThemeGraphTextFormat * @description 统计专题图文本显示格式枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ThemeGraphTextFormat } from '{npm}'; * * const result = ThemeGraphTextFormat.CAPTION; * ``` */ var ThemeGraphTextFormat = { /** 标题。以各子项的标题来进行标注。 */ CAPTION: "CAPTION", /** 标题 + 百分数。以各子项的标题和所占的百分比来进行标注。 */ CAPTION_PERCENT: "CAPTION_PERCENT", /** 标题 + 实际数值。以各子项的标题和真实数值来进行标注。 */ CAPTION_VALUE: "CAPTION_VALUE", /** 百分数。以各子项所占的百分比来进行标注。 */ PERCENT: "PERCENT", /** 实际数值。以各子项的真实数值来进行标注。 */ VALUE: "VALUE" }; /** * @enum ThemeGraphType * @description 统计专题图类型枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ThemeGraphType } from '{npm}'; * * const result = ThemeGraphType.AREA; * ``` */ var ThemeGraphType = { /** 面积图。 */ AREA: "AREA", /** 柱状图。 */ BAR: "BAR", /** 三维柱状图。 */ BAR3D: "BAR3D", /** 折线图。 */ LINE: "LINE", /** 饼图。 */ PIE: "PIE", /** 三维饼图。 */ PIE3D: "PIE3D", /** 点状图。 */ POINT: "POINT", /** 环状图。 */ RING: "RING", /** 玫瑰图。 */ ROSE: "ROSE", /** 三维玫瑰图。 */ ROSE3D: "ROSE3D", /** 堆叠柱状图。 */ STACK_BAR: "STACK_BAR", /** 三维堆叠柱状图。 */ STACK_BAR3D: "STACK_BAR3D", /** 阶梯图。 */ STEP: "STEP" }; /** * @enum GraphAxesTextDisplayMode * @description 统计专题图坐标轴文本显示模式。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { GraphAxesTextDisplayMode } from '{npm}'; * * const result = GraphAxesTextDisplayMode.ALL; * ``` */ var GraphAxesTextDisplayMode = { /** 显示全部文本。 */ ALL: "ALL", /** 不显示。 */ NONE: "NONE", /** 显示Y轴的文本。 */ YAXES: "YAXES" }; /** * @enum GraduatedMode * @description 专题图分级模式枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { GraduatedMode } from '{npm}'; * * const result = GraduatedMode.CONSTANT; * ``` */ var GraduatedMode = { /** 常量分级模式。 */ CONSTANT: "CONSTANT", /** 对数分级模式。 */ LOGARITHM: "LOGARITHM", /** 平方根分级模式。 */ SQUAREROOT: "SQUAREROOT" }; /** * @enum RangeMode * @description 范围分段专题图分段方式枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { RangeMode } from '{npm}'; * * const result = RangeMode.CUSTOMINTERVAL; * ``` */ var RangeMode = { /** 自定义分段法。 */ CUSTOMINTERVAL: "CUSTOMINTERVAL", /** 等距离分段法。 */ EQUALINTERVAL: "EQUALINTERVAL", /** 对数分段法。 */ LOGARITHM: "LOGARITHM", /** 等计数分段法。 */ QUANTILE: "QUANTILE", /** 平方根分段法。 */ SQUAREROOT: "SQUAREROOT", /** 标准差分段法。 */ STDDEVIATION: "STDDEVIATION" }; /** * @enum ThemeType * @description 专题图类型枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ThemeType } from '{npm}'; * * const result = ThemeType.DOTDENSITY; * ``` */ var ThemeType = { /** 点密度专题图。 */ DOTDENSITY: "DOTDENSITY", /** 等级符号专题图。 */ GRADUATEDSYMBOL: "GRADUATEDSYMBOL", /** 统计专题图。 */ GRAPH: "GRAPH", /** 标签专题图。 */ LABEL: "LABEL", /** 分段专题图。 */ RANGE: "RANGE", /** 単值专题图。 */ UNIQUE: "UNIQUE" }; /** * @enum ColorGradientType * @description 渐变颜色枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ColorGradientType } from '{npm}'; * * const result = ColorGradientType.BLACK_WHITE; * ``` */ var ColorGradientType = { /** 黑白渐变色。 */ BLACK_WHITE: "BLACKWHITE", /** 蓝黑渐变色。 */ BLUE_BLACK: "BLUEBLACK", /** 蓝红渐变色。 */ BLUE_RED: "BLUERED", /** 蓝白渐变色。 */ BLUE_WHITE: "BLUEWHITE", /** 青黑渐变色。 */ CYAN_BLACK: "CYANBLACK", /** 青蓝渐变色。 */ CYAN_BLUE: "CYANBLUE", /** 青绿渐变色。 */ CYAN_GREEN: "CYANGREEN", /** 青白渐变色。 */ CYAN_WHITE: "CYANWHITE", /** 绿黑渐变色。 */ GREEN_BLACK: "GREENBLACK", /** 绿蓝渐变色。 */ GREEN_BLUE: "GREENBLUE", /** 绿橙紫渐变色。 */ GREEN_ORANGE_VIOLET: "GREENORANGEVIOLET", /** 绿红渐变色。 */ GREEN_RED: "GREENRED", /** 蓝红渐变色。 */ GREEN_WHITE: "GREENWHITE", /** 粉黑渐变色。 */ PINK_BLACK: "PINKBLACK", /** 粉蓝渐变色。 */ PINK_BLUE: "PINKBLUE", /** 粉红渐变色。 */ PINK_RED: "PINKRED", /** 粉白渐变色。 */ PINK_WHITE: "PINKWHITE", /** 彩虹色。 */ RAIN_BOW: "RAINBOW", /** 红黑渐变色。 */ RED_BLACK: "REDBLACK", /** 红白渐变色。 */ RED_WHITE: "REDWHITE", /** 光谱渐变。 */ SPECTRUM: "SPECTRUM", /** 地形渐变,用于三维显示效果较好。 */ TERRAIN: "TERRAIN", /** 黄黑渐变色。 */ YELLOW_BLACK: "YELLOWBLACK", /** 黄蓝渐变色。 */ YELLOW_BLUE: "YELLOWBLUE", /** 黄绿渐变色。 */ YELLOW_GREEN: "YELLOWGREEN", /** 黄红渐变色。 */ YELLOW_RED: "YELLOWRED", /** 黄白渐变色。 */ YELLOW_WHITE: "YELLOWWHITE" }; /** * @enum TextAlignment * @description 文本对齐枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { TextAlignment } from '{npm}'; * * const result = TextAlignment.TOPLEFT; * ``` */ var TextAlignment = { /** 左上角对齐。 */ TOPLEFT: "TOPLEFT", /** 顶部居中对齐。 */ TOPCENTER: "TOPCENTER", /** 右上角对齐。 */ TOPRIGHT: "TOPRIGHT", /** 基准线左对齐。 */ BASELINELEFT: "BASELINELEFT", /** 基准线居中对齐。 */ BASELINECENTER: "BASELINECENTER", /** 基准线右对齐。 */ BASELINERIGHT: "BASELINERIGHT", /** 左下角对齐。 */ BOTTOMLEFT: "BOTTOMLEFT", /** 底部居中对齐。 */ BOTTOMCENTER: "BOTTOMCENTER", /** 右下角对齐。 */ BOTTOMRIGHT: "BOTTOMRIGHT", /** 左中对齐。 */ MIDDLELEFT: "MIDDLELEFT", /** 中心对齐。 */ MIDDLECENTER: "MIDDLECENTER", /** 右中对齐。 */ MIDDLERIGHT: "MIDDLERIGHT" }; /** * @enum FillGradientMode * @description 渐变填充风格的渐变类型枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { FillGradientMode } from '{npm}'; * * const result = FillGradientMode.NONE; * ``` */ var FillGradientMode = { /** 无渐变。 */ NONE: "NONE", /** 线性渐变填充。 */ LINEAR: "LINEAR", /** 辐射渐变填充。 */ RADIAL: "RADIAL", /** 圆锥渐变填充。 */ CONICAL: "CONICAL", /** 四角渐变填充。 */ SQUARE: "SQUARE" }; /** * @enum AlongLineDirection * @description 标签沿线标注方向枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { AlongLineDirection } from '{npm}'; * * const result = AlongLineDirection.NORMAL; * ``` */ var AlongLineDirection = { /** 沿线的法线方向放置标签。 */ NORMAL: "ALONG_LINE_NORMAL", /** 从下到上,从左到右放置。 */ LB_TO_RT: "LEFT_BOTTOM_TO_RIGHT_TOP", /** 从上到下,从左到右放置。 */ LT_TO_RB: "LEFT_TOP_TO_RIGHT_BOTTOM", /** 从下到上,从右到左放置。 */ RB_TO_LT: "RIGHT_BOTTOM_TO_LEFT_TOP", /** 从上到下,从右到左放置。 */ RT_TO_LB: "RIGHT_TOP_TO_LEFT_BOTTOM" }; /** * @enum LabelBackShape * @description 标签专题图中标签背景的形状枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { LabelBackShape } from '{npm}'; * * const result = LabelBackShape.DIAMOND; * ``` */ var LabelBackShape = { /** 菱形背景,即标签背景的形状为菱形。 */ DIAMOND: "DIAMOND", /** 椭圆形背景,即标签背景的行状为椭圆形。 */ ELLIPSE: "ELLIPSE", /** 符号背景,即标签背景的形状为设定的符号。 */ MARKER: "MARKER", /** 空背景,即不使用任何形状作为标签的背景。 */ NONE: "NONE", /** 矩形背景,即标签背景的形状为矩形。 */ RECT: "RECT", /** 圆角矩形背景,即标签背景的形状为圆角矩形。 */ ROUNDRECT: "ROUNDRECT", /** 三角形背景,即标签背景的形状为三角形。 */ TRIANGLE: "TRIANGLE" }; /** * @enum LabelOverLengthMode * @description 标签专题图中超长标签的处理模式枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { LabelOverLengthMode } from '{npm}'; * * const result = LabelOverLengthMode.NEWLINE; * ``` */ var LabelOverLengthMode = { /** 换行显示。 */ NEWLINE: "NEWLINE", /** 对超长标签不进行处理。 */ NONE: "NONE", /** 省略超出部分。 */ OMIT: "OMIT" }; /** * @enum DirectionType * @description 网络分析中方向枚举。 * 在行驶引导子项中使用。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { DirectionType } from '{npm}'; * * const result = DirectionType.EAST; * ``` */ var DirectionType = { /** 东。 */ EAST: "EAST", /** 无方向。 */ NONE: "NONE", /** 北。 */ NORTH: "NORTH", /** 南。 */ SOURTH: "SOURTH", /** 西。 */ WEST: "WEST" }; /** * @enum SideType * @description 行驶位置枚举。 * 表示在行驶在路的左边、右边或者路上的枚举,该类用在行驶导引子项类中。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SideType } from '{npm}'; * * const result = SideType.LEFT; * ``` */ var SideType = { /** 路的左侧。 */ LEFT: "LEFT", /** 在路上(即路的中间)。 */ MIDDLE: "MIDDLE", /** 无效值。 */ NONE: "NONE", /** 路的右侧。 */ RIGHT: "RIGHT" }; /** * @enum SupplyCenterType * @description 资源供给中心类型枚举。 * 该枚举定义了网络分析中资源中心点的类型,主要用于资源分配和选址分区。 * 资源供给中心点的类型包括非中心,固定中心和可选中心。固定中心用于资源分配分析;固定中心和可选中心用于选址分析;非中心在两种网络分析时都不予考虑。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SupplyCenterType } from '{npm}'; * * const result = SupplyCenterType.FIXEDCENTER; * ``` */ var SupplyCenterType = { /** 固定中心点。 */ FIXEDCENTER: "FIXEDCENTER", /** 非中心点。 */ NULL: "NULL", /** 可选中心点。 */ OPTIONALCENTER: "OPTIONALCENTER" }; /** * @enum TurnType * @description 转弯方向枚举。 * 用在行驶引导子项类中,表示转弯的方向。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { TurnType } from '{npm}'; * * const result = TurnType.AHEAD; * ``` */ var TurnType = { /** 向前直行。 */ AHEAD: "AHEAD", /** 掉头。 */ BACK: "BACK", /** 终点,不拐弯。 */ END: "END", /** 左转弯。 */ LEFT: "LEFT", /** 无效值。 */ NONE: "NONE", /** 右转弯。 */ RIGHT: "RIGHT" }; /** * @enum BufferEndType * @description 缓冲区分析BufferEnd类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { BufferEndType } from '{npm}'; * * const result = BufferEndType.FLAT; * ``` */ var BufferEndType = { /** 平头缓冲。 */ FLAT: "FLAT", /** 圆头缓冲。 */ ROUND: "ROUND" }; /** * @enum OverlayOperationType * @description 叠加分析类型枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { OverlayOperationType } from '{npm}'; * * const result = OverlayOperationType.CLIP; * ``` */ var OverlayOperationType = { /** 操作数据集(几何对象)裁剪被操作数据集(几何对象)。 */ CLIP: "CLIP", /** 在被操作数据集(几何对象)上擦除掉与操作数据集(几何对象)相重合的部分。 */ ERASE: "ERASE", /**对被操作数据集(几何对象)进行同一操作,即操作执行后,被操作数据集(几何对象)包含来自操作数据集(几何对象)的几何形状。 */ IDENTITY: "IDENTITY", /** 对两个数据集(几何对象)求交,返回两个数据集(几何对象)的交集。 */ INTERSECT: "INTERSECT", /** 对两个面数据集(几何对象)进行合并操作。 */ UNION: "UNION", /** 对两个面数据集(几何对象)进行更新操作。 */ UPDATE: "UPDATE", /** 对两个面数据集(几何对象)进行对称差操作。 */ XOR: "XOR" }; /** * @enum OutputType * @description 分布式分析输出类型枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { OutputType } from '{npm}'; * * const result = OutputType.INDEXEDHDFS; * ``` */ var OutputType = { /** INDEXEDHDFS */ INDEXEDHDFS: "INDEXEDHDFS", /** UDB */ UDB: "UDB", /** MONGODB */ MONGODB: "MONGODB", /** PG */ PG: "PG" }; /** * @enum SmoothMethod * @description 光滑方法枚举。 * 用于从Grid 或DEM数据生成等值线或等值面时对等值线或者等值面的边界线进行平滑处理的方法。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SmoothMethod } from '{npm}'; * * const result = SmoothMethod.BSPLINE; * ``` */ var SmoothMethod = { /** B 样条法。 */ BSPLINE: "BSPLINE", /** 磨角法。 */ POLISH: "POLISH" }; /** * @enum SurfaceAnalystMethod * @description 表面分析方法枚举。 * 通过对数据进行表面分析,能够挖掘原始数据所包含的信息,使某些细节明显化,易于分析。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SurfaceAnalystMethod } from '{npm}'; * * const result = SurfaceAnalystMethod.ISOLINE; * ``` */ var SurfaceAnalystMethod = { /** 等值线提取。 */ ISOLINE: "ISOLINE", /** 等值面提取。 */ ISOREGION: "ISOREGION" }; /** * @enum DataReturnMode * @description 数据返回模式枚举。 * 该枚举用于指定空间分析返回结果模式,包含返回数据集标识和记录集、只返回数据集标识(数据集名称@数据源名称)及只返回记录集三种模式。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { DataReturnMode } from '{npm}'; * * const result = DataReturnMode.DATASET_AND_RECORDSET; * ``` */ var DataReturnMode = { /** 返回结果数据集标识(数据集名称@数据源名称)和记录集(RecordSet)。 */ DATASET_AND_RECORDSET: "DATASET_AND_RECORDSET", /** 只返回数据集标识(数据集名称@数据源名称)。 */ DATASET_ONLY: "DATASET_ONLY", /** 只返回记录集(RecordSet)。 */ RECORDSET_ONLY: "RECORDSET_ONLY" }; /** * @enum EditType * @description 要素集更新模式枚举。 * 该枚举用于指定数据服务中要素集更新模式,包含添加要素集、更新要素集和删除要素集。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { EditType } from '{npm}'; * * const result = {namespace}.EditType.ADD; * ``` */ var EditType = { /** 增加操作。 */ ADD: "add", /** 修改操作。 */ UPDATE: "update", /** 删除操作。 */ DELETE: "delete" }; /** * @enum TransferTactic * @description 公交换乘策略枚举。 * 该枚举用于指定公交服务中要素集更新模式,包含添加要素集、更新要素集和删除要素集。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { TransferTactic } from '{npm}'; * * const result = TransferTactic.LESS_TIME; * ``` */ var TransferTactic = { /** 时间短。 */ LESS_TIME: "LESS_TIME", /** 少换乘。 */ LESS_TRANSFER: "LESS_TRANSFER", /** 少步行。 */ LESS_WALK: "LESS_WALK", /** 距离最短。 */ MIN_DISTANCE: "MIN_DISTANCE" }; /** * @enum TransferPreference * @description 公交换乘策略枚举。 * 该枚举用于指定交通换乘服务中设置地铁优先、公交优先、不乘地铁、无偏好等偏好设置。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { TransferPreference } from '{npm}'; * * const result = TransferPreference.BUS; * ``` */ var TransferPreference = { /** 公交汽车优先。 */ BUS: "BUS", /** 地铁优先。 */ SUBWAY: "SUBWAY", /** 不乘坐地铁。 */ NO_SUBWAY: "NO_SUBWAY", /** 无乘车偏好。 */ NONE: "NONE" }; /** * @enum GridType * @description 地图背景格网类型枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { GridType } from '{npm}'; * * const result = GridType.CROSS; * ``` */ var GridType = { /** 十字叉丝。 */ CROSS: "CROSS", /** 网格线。 */ GRID: "GRID", /** 点。 */ POINT: "POINT" }; /** * @enum ColorSpaceType * @description 色彩空间枚举。 * 由于成色原理的不同,决定了显示器、投影仪这类靠色光直接合成颜色的颜色设备和打印机、 * 印刷机这类靠使用颜料的印刷设备在生成颜色方式上的区别。 * 针对上述不同成色方式,SuperMap 提供两种色彩空间, * 分别为 RGB 和 CMYK。RGB 主要用于显示系统中,CMYK 主要用于印刷系统中。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ColorSpaceType } from '{npm}'; * * const result = ColorSpaceType.CMYK; * ``` */ var ColorSpaceType = { /** 该类型主要在印刷系统使用。 */ CMYK: "CMYK", /** 该类型主要在显示系统中使用。 */ RGB: "RGB" }; /** * @enum LayerType * @description 图层类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { LayerType } from '{npm}'; * * const result = LayerType.UGC; * ``` */ var LayerType = { /** SuperMap UGC 类型图层。如矢量图层、栅格(Grid)图层、影像图层。 */ UGC: "UGC", /** WMS 图层。 */ WMS: "WMS", /** WFS 图层。 */ WFS: "WFS", /** 自定义图层。 */ CUSTOM: "CUSTOM" }; /** * @enum UGCLayerType * @description SuperMap 图层类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { UGCLayerType } from '{npm}'; * * const result = UGCLayerType.THEME; * ``` */ var UGCLayerType = { /** 专题图层。 */ THEME: "THEME", /** 矢量图层。 */ VECTOR: "VECTOR", /** 栅格图层。 */ GRID: "GRID", /** 影像图层。 */ IMAGE: "IMAGE" }; /** * @enum StatisticMode * @description 字段统计方法类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { StatisticMode } from '{npm}'; * * const result = StatisticMode.AVERAGE; * ``` */ var StatisticMode = { /** 统计所选字段的平均值。 */ AVERAGE: "AVERAGE", /** 统计所选字段的最大值。 */ MAX: "MAX", /** 统计所选字段的最小值。 */ MIN: "MIN", /** 统计所选字段的标准差 */ STDDEVIATION: "STDDEVIATION", /** 统计所选字段的总和。 */ SUM: "SUM", /** 统计所选字段的方差。 */ VARIANCE: "VARIANCE" }; /** * @enum PixelFormat * @description 栅格与影像数据存储的像素格式枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { PixelFormat } from '{npm}'; * * const result = PixelFormat.BIT16; * ``` */ var PixelFormat = { /** 每个像元用16个比特(即2个字节)表示。 */ BIT16: "BIT16", /** 每个像元用32个比特(即4个字节)表示。 */ BIT32: "BIT32", /** 每个像元用64个比特(即8个字节)表示,只提供给栅格数据集使用。 */ BIT64: "BIT64", /** 每个像元用4个字节来表示,只提供给栅格数据集使用。 */ SINGLE: "SINGLE", /** 每个像元用8个字节来表示,只提供给栅格数据集使用。 */ DOUBLE: "DOUBLE", /** 每个像元用1个比特表示。 */ UBIT1: "UBIT1", /** 每个像元用4个比特来表示。 */ UBIT4: "UBIT4", /** 每个像元用8个比特(即1个字节)来表示。 */ UBIT8: "UBIT8", /** 每个像元用24个比特(即3个字节)来表示。 */ UBIT24: "UBIT24", /** 每个像元用32个比特(即4个字节)来表示。 */ UBIT32: "UBIT32" }; /** * @enum SearchMode * @description 内插时使用的样本点的查找方式枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SearchMode } from '{npm}'; * * const result = SearchMode.KDTREE_FIXED_COUNT; * ``` */ var SearchMode = { /** 使用 KDTREE 的固定点数方式查找参与内插分析的点。 */ KDTREE_FIXED_COUNT: "KDTREE_FIXED_COUNT", /** 使用 KDTREE 的定长方式查找参与内插分析的点。 */ KDTREE_FIXED_RADIUS: "KDTREE_FIXED_RADIUS", /** 不进行查找,使用所有的输入点进行内插分析。 */ NONE: "NONE", /** 使用 QUADTREE 方式查找参与内插分析的点,仅对样条(RBF)插值和普通克吕金(Kriging)有用。 */ QUADTREE: "QUADTREE" }; /** * @enum InterpolationAlgorithmType * @description 插值分析的算法的类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { InterpolationAlgorithmType } from '{npm}'; * * const result = InterpolationAlgorithmType.KRIGING; * ``` */ var InterpolationAlgorithmType = { /** 普通克吕金插值法。 */ KRIGING: "KRIGING", /** 简单克吕金插值法。 */ SimpleKriging: "SimpleKriging", /** 泛克吕金插值法。 */ UniversalKriging: "UniversalKriging" }; /** * @enum VariogramMode * @description 克吕金(Kriging)插值时的半变函数类型枚举。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { VariogramMode } from '{npm}'; * * const result = VariogramMode.EXPONENTIAL; * ``` */ var VariogramMode = { /** 指数函数。 */ EXPONENTIAL: "EXPONENTIAL", /** 高斯函数。 */ GAUSSIAN: "GAUSSIAN", /** 球型函数。 */ SPHERICAL: "SPHERICAL" }; /** * @enum Exponent * @description 定义了泛克吕金(UniversalKriging)插值时样点数据中趋势面方程的阶数。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { Exponent } from '{npm}'; * * const result = Exponent.EXP1; * ``` */ var Exponent = { /** 阶数为1。 */ EXP1: "EXP1", /** 阶数为2。 */ EXP2: "EXP2" }; /** * @enum ClientType * @description token申请的客户端标识类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ClientType } from '{npm}'; * * const result = ClientType.IP; * ``` */ var ClientType = { /** 指定的 IP 地址。 */ IP: "IP", /** 指定的 URL。 */ REFERER: "Referer", /** 发送申请令牌请求的客户端 IP。 */ REQUESTIP: "RequestIP", /** 不做任何验证。 */ NONE: "NONE", /** SERVER。 */ SERVER: "SERVER", /** WEB。 */ WEB: "WEB" }; /** * @enum ChartType * @description 客户端专题图图表类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ChartType } from '{npm}'; * * const result = ChartType.BAR; * ``` */ var ChartType = { /** 柱状图。 */ BAR: "Bar", /** 三维柱状图。 */ BAR3D: "Bar3D", /** 圆形图。 */ CIRCLE: "Circle", /** 饼图。 */ PIE: "Pie", /** 散点图。 */ POINT: "Point", /** 折线图。 */ LINE: "Line", /** 环状图。 */ RING: "Ring" }; /** * @enum ClipAnalystMode * @description 裁剪分析模式 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ClipAnalystMode } from '{npm}'; * * const result = ClipAnalystMode.CLIP; * ``` */ var ClipAnalystMode = { /** CLIP。 */ CLIP: "clip", /** INTERSECT。 */ INTERSECT: "intersect" }; /** * @enum AnalystAreaUnit * @description 分布式分析面积单位。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { AnalystAreaUnit } from '{npm}'; * * const result = AnalystAreaUnit.SQUAREMETER; * ``` */ var AnalystAreaUnit = { /** 平方米。 */ "SQUAREMETER": "SquareMeter", /** 平方千米。 */ "SQUAREKILOMETER": "SquareKiloMeter", /** 公顷。 */ "HECTARE": "Hectare", /** 公亩。 */ "ARE": "Are", /** 英亩。 */ "ACRE": "Acre", /** 平方英尺。 */ "SQUAREFOOT": "SquareFoot", /** 平方码。 */ "SQUAREYARD": "SquareYard", /** 平方英里。 */ "SQUAREMILE": "SquareMile" }; /** * @enum AnalystSizeUnit * @description 分布式分析单位。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { AnalystSizeUnit } from '{npm}'; * * const result = AnalystSizeUnit.METER; * ``` */ var AnalystSizeUnit = { /** 米。 */ "METER": "Meter", /** 千米。 */ "KILOMETER": "Kilometer", /** 码。 */ "YARD": "Yard", /** 英尺。 */ "FOOT": "Foot", /** 英里。 */ "MILE": "Mile" }; /** * @enum StatisticAnalystMode * @description 分布式分析统计模式。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { StatisticAnalystMode } from '{npm}'; * * const result = StatisticAnalystMode.MAX; * ``` */ var StatisticAnalystMode = { /** 统计所选字段的最大值。 */ "MAX": "max", /** 统计所选字段的最小值。 */ "MIN": "min", /** 统计所选字段的平均值。 */ "AVERAGE": "average", /** 统计所选字段的总和。 */ "SUM": "sum", /** 统计所选字段的方差。 */ "VARIANCE": "variance", /** 统计所选字段的标准差。 */ "STDDEVIATION": "stdDeviation" }; /** * @enum SummaryType * @description 分布式分析聚合类型。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SummaryType } from '{npm}'; * * const result = SummaryType.SUMMARYMESH; * ``` */ var SummaryType = { /** 格网聚合。 */ "SUMMARYMESH": "SUMMARYMESH", /** 多边形聚合。 */ "SUMMARYREGION": "SUMMARYREGION" }; /** * @enum TopologyValidatorRule * @description 拓扑检查模式枚举。该类定义了拓扑检查操作模式常量。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { TopologyValidatorRule } from '{npm}'; * * const result = TopologyValidatorRule.REGIONNOOVERLAP; * ``` */ var TopologyValidatorRule = { /** 面内无重叠,用于对面数据进行拓扑检查。 */ REGIONNOOVERLAP: "REGIONNOOVERLAP", /** 面与面无重叠,用于对面数据进行拓扑检查。 */ REGIONNOOVERLAPWITH: "REGIONNOOVERLAPWITH", /** 面被面包含,用于对面数据进行拓扑检查。 */ REGIONCONTAINEDBYREGION: "REGIONCONTAINEDBYREGION", /** 面被面覆盖,用于对面数据进行拓扑检查。 */ REGIONCOVEREDBYREGION: "REGIONCOVEREDBYREGION", /** 线与线无重叠,用于对线数据进行拓扑检查。 */ LINENOOVERLAP: "LINENOOVERLAP", /** 线内无重叠,用于对线数据进行拓扑检查。 */ LINENOOVERLAPWITH: "LINENOOVERLAPWITH", /** 点不相同,用于对点数据进行拓扑检查。 */ POINTNOIDENTICAL: "POINTNOIDENTICAL" }; /** * @enum BucketAggType * @description 格网聚合查询枚举类,该类定义了Elasticsearch数据服务中聚合查询模式常量 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { BucketAggType } from '{npm}'; * * const result = BucketAggType.GEOHASH_GRID; * ``` */ var BucketAggType = { /** 格网聚合类型。 */ GEOHASH_GRID: "geohash_grid" }; /** * @enum MetricsAggType * @description 指标聚合类型枚举类,该类定义了Elasticsearch数据服务中聚合查询模式常量。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { MetricsAggType } from '{npm}'; * * const result = MetricsAggType.AVG; * ``` */ var MetricsAggType = { /** 平均值聚合类型。 */ AVG:'avg', /** 最大值聚合类型。 */ MAX:'max', /** 最小值聚合类型。 */ MIN:'min', /** 求和聚合类型。 */ SUM:'sum' }; /** * @enum GetFeatureMode * @description feature 查询方式。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { GetFeatureMode } from '{npm}'; * * const result = GetFeatureMode.BOUNDS; * ``` */ var GetFeatureMode = { /** 通过范围查询来获取要素。 */ BOUNDS: "BOUNDS", /** 通过几何对象的缓冲区来获取要素。 */ BUFFER: "BUFFER", /** 通过 ID 来获取要素。 */ ID: "ID", /** 通过空间查询模式来获取要素。 */ SPATIAL: "SPATIAL", /** 通过 SQL 查询来获取要素。 */ SQL: 'SQL' } /** * @enum RasterFunctionType * @description 栅格分析方法。 * @category BaseTypes Constant * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { GetFeatureMode } from '{npm}'; * * const result = GetFeatureMode.NDVI; * ``` */ var RasterFunctionType = { /** 归一化植被指数。 */ NDVI: "NDVI", /** 阴影面分析。 */ HILLSHADE: "HILLSHADE" } /** * @enum ResourceType * @description iportal资源类型。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { GetFeatureMode } from '{npm}'; * * const result = GetFeatureMode.MAP; * ``` */ var ResourceType = { /** 地图。 */ MAP: "MAP", /** 服务。 */ SERVICE: "SERVICE", /** 场景。 */ SCENE: "SCENE", /** 数据。 */ DATA: "DATA", /** 洞察。 */ INSIGHTS_WORKSPACE: "INSIGHTS_WORKSPACE", /** 大屏。 */ MAP_DASHBOARD: "MAP_DASHBOARD" } /** * @enum OrderBy * @description iportal资源排序字段。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { OrderBy } from '{npm}'; * * const result = OrderBy.UPDATETIME; * ``` */ var OrderBy = { /** 按更新时间排序。 */ UPDATETIME: "UPDATETIME", /** 按热度(可能是访问量、下载量)排序。 */ HEATLEVEL: "HEATLEVEL", /** 按相关性排序。 */ RELEVANCE: "RELEVANCE" } /** * @enum OrderType * @description iportal资源升序还是降序过滤。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { OrderType } from '{npm}'; * * const result = OrderType.ASC; * ``` */ var OrderType = { /** 升序。 */ ASC: "ASC", /** 降序。 */ DESC: "DESC" } /** * @enum SearchType * @description iportal资源查询的范围进行过滤。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { SearchType } from '{npm}'; * * const result = SearchType.PUBLIC; * ``` */ var SearchType = { /** 公开资源。 */ PUBLIC: "PUBLIC", /** 我的资源。 */ MY_RES: "MY_RES", /** 我的群组资源。 */ MYGROUP_RES: "MYGROUP_RES", /** 我的部门资源。 */ MYDEPARTMENT_RES: "MYDEPARTMENT_RES", /** 分享给我的资源。 */ SHARETOME_RES: "SHARETOME_RES" } /** * @enum AggregationTypes * @description iportal资源聚合查询的类型。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { AggregationTypes } from '{npm}'; * * const result = AggregationTypes.TAG; * ``` */ var AggregationTypes = { /** 标签。 */ TAG: "TAG", /** 资源类型。 */ TYPE: "TYPE" } /** * @enum PermissionType * @description iportal资源权限类型。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { PermissionType } from '{npm}'; * * const result = PermissionType.SEARCH; * ``` */ var PermissionType = { /** 可检索。 */ SEARCH:"SEARCH", /** 可查看。 */ READ: "READ", /** 可编辑。 */ READWRITE: "READWRITE", /** 可删除。 */ DELETE: "DELETE", /** 可下载,包括可读、可检索。 */ DOWNLOAD:"DOWNLOAD" } /** * @enum EntityType * @description iportal资源实体类型。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { EntityType } from '{npm}'; * * const result = EntityType.DEPARTMENT; * ``` */ var EntityType = { /** 部门。 */ DEPARTMENT: "DEPARTMENT", /** 用户组。 */ GROUP: "GROUP", /** 群组。 */ IPORTALGROUP: "IPORTALGROUP", /** 角色。 */ ROLE: "ROLE", /** 用户。 */ USER: "USER" } /** * @enum DataItemType * @description iportal数据类型。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { DataItemType } from '{npm}'; * * const result = DataItemType.GEOJSON; * ``` */ var DataItemType = { /** geojson 数据。 */ GEOJSON: "GEOJSON", /** UGCV5_MVT。 */ UGCV5_MVT: "UGCV5_MVT", /** json数据。 */ JSON: "JSON", /** 音频文件。 */ AUDIO: "AUDIO", /** Color 颜色。 */ COLOR: "COLOR", /** ColorScheme 颜色方案。 */ COLORSCHEME: "COLORSCHEME", /** CSV 数据。 */ CSV: "CSV", /** EXCEL 数据。 */ EXCEL: "EXCEL", /** FillSymbol 填充符号库。 */ FILLSYMBOL: "FILLSYMBOL", /** 图片类型。 */ IMAGE: "IMAGE", /** LayerTemplate 图层模板。 */ LAYERTEMPLATE: "LAYERTEMPLATE", /** LayoutTemplate 布局模板。 */ LAYOUTTEMPLATE: "LAYOUTTEMPLATE", /** LineSymbol 线符号库。 */ LINESYMBOL: "LINESYMBOL", /** MapTemplate 地图模板。 */ MAPTEMPLATE: "MAPTEMPLATE", /** MarkerSymbol 点符号库。 */ MARKERSYMBOL: "MARKERSYMBOL", /** MBTILES。 */ MBTILES: "MBTILES", /** 照片。 */ PHOTOS: "PHOTOS", /** SHP 空间数据。 */ SHP: "SHP", /** SMTILES。 */ SMTILES: "SMTILES", /** SVTILES。 */ SVTILES: "SVTILES", /** ThemeTemplate 专题图模板。 */ THEMETEMPLATE: "THEMETEMPLATE", /** TPK。 */ TPK: "TPK", /** UDB 数据源。 */ UDB: "UDB", /** UGCV5。 */ UGCV5: "UGCV5", /** 其他类型(普通文件)。 */ UNKNOWN: "UNKNOWN", /** 视频文件。 */ VIDEO: "VIDEO", /** WorkEnviroment 工作环境。 */ WORKENVIRONMENT: "WORKENVIRONMENT", /** 工作空间。 */ WORKSPACE: "WORKSPACE" } /** * @enum WebExportFormatType * @description Web 打印输出的格式。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { WebExportFormatType } from '{npm}'; * * const result = WebExportFormatType.PNG; * ``` */ var WebExportFormatType = { /** PNG */ PNG: "PNG", /** PDF */ PDF: "PDF" } /** * @enum WebScaleOrientationType * @description Web 比例尺的方位样式。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { WebScaleOrientationType } from '{npm}'; * * const result = WebScaleOrientationType.HORIZONTALLABELSBELOW; * ``` */ var WebScaleOrientationType = { /** horizontal labels below. */ HORIZONTALLABELSBELOW: "HORIZONTALLABELSBELOW", /** horizontal labels above. */ HORIZONTALLABELSABOVE: "HORIZONTALLABELSABOVE", /** vertical labels left. */ VERTICALLABELSLEFT: "VERTICALLABELSLEFT", /** vertical labels right. */ VERTICALLABELSRIGHT: "VERTICALLABELSRIGHT" } /** * @enum WebScaleType * @description Web 比例尺的样式。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { WebScaleType } from '{npm}'; * * const result = WebScaleType.LINE; * ``` */ var WebScaleType = { /** line. */ LINE: "LINE", /** bar. */ BAR: "BAR", /** bar sub. */ BAR_SUB: "BAR_SUB" } /** * @enum WebScaleUnit * @description Web 比例尺的单位制。 * @category BaseTypes Constant * @version 10.0.1 * @type {string} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { WebScaleUnit } from '{npm}'; * * const result = WebScaleUnit.METER; * ``` */ var WebScaleUnit = { /** 米。 */ METER: "METER", /** 英尺。 */ FOOT: "FOOT", /** 度。 */ DEGREES: "DEGREES" } ;// CONCATENATED MODULE: ./src/common/commontypes/Size.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Size * @deprecatedclass SuperMap.Size * @category BaseTypes Style * @classdesc 此类描绘一对高宽值的实例。 * @param {number} [w=0.0] - 宽度。 * @param {number} [h=0.0] - 高度。 * * @example * var size = new Size(31,46); * @usage */ class Size { constructor(w, h) { /** * @member {number} [Size.prototype.w=0.0] * @description 宽度。 */ this.w = w ? parseFloat(w) : 0.0; /** * @member {number} [Size.prototype.h=0.0] * @description 高度。 */ this.h = w ? parseFloat(h) : 0.0; this.CLASS_NAME = "SuperMap.Size"; } /** * @function Size.prototype.toString * @description 返回字符串形式。 * @example * var size = new Size(10,5); * var str = size.toString(); * @returns {string} 例如:"w=10,h=5"。 */ toString() { return ("w=" + this.w + ",h=" + this.h); } /** * @function Size.prototype.clone * @description 克隆当前size对象。 * @example * var size = new Size(31,46); * var size2 = size.clone(); * @returns {Size} 新的与当前 size 对象有相同宽、高的 Size 对象。 */ clone() { return new Size(this.w, this.h); } /** * * @function Size.prototype.equals * @description 比较两个 size 对象是否相等。 * @example * var size = new Size(31,46); * var size2 = new Size(31,46); * var isEquals = size.equals(size2); * * @param {Size} sz - 用于比较相等的 Size 对象。 * @returns {boolean} 传入的 size 和当前 size 高宽相等,注意:如果传入的 size 为空则返回 false。 * */ equals(sz) { var equals = false; if (sz != null) { equals = ((this.w === sz.w && this.h === sz.h) || (isNaN(this.w) && isNaN(this.h) && isNaN(sz.w) && isNaN(sz.h))); } return equals; } /** * * @function Size.prototype.destroy * @description 销毁此对象。销毁后此对象的所有属性为 null,而不是初始值。 * @example * var size = new Size(31,46); * size.destroy(); */ destroy() { this.w = null; this.h = null; } } ;// CONCATENATED MODULE: ./src/common/commontypes/Pixel.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Pixel * @deprecatedclass SuperMap.Pixel * @category BaseTypes Geometry * @classdesc 用 x,y 坐标描绘屏幕坐标(像素点)。 * @param {number} [x=0.0] - x 坐标。 * @param {number} [y=0.0] - y 坐标。 * @param {Pixel.Mode} [mode=Pixel.Mode.LeftTop] - 坐标模式。 * * @example * //单独创建一个对象 * var pixcel = new Pixel(100,50); * * //依据 size 创建 * var size = new Size(21,25); * var offset = new Pixel(-(size.w/2), -size.h); * @usage */ class Pixel { constructor(x, y, mode) { /** * @member {number} [Pixel.prototype.x=0.0] * @description x 坐标。 */ this.x = x ? parseFloat(x) : 0.0; /** * @member {number} [Pixel.prototype.y=0.0] * @description y 坐标。 */ this.y = y ? parseFloat(y) : 0.0; /** * @member {Pixel.Mode} [Pixel.prototype.mode=Pixel.Mode.LeftTop] * @description 坐标模式,有左上、右上、右下、左下这几种模式,分别表示相对于左上角、右上角、右下角、左下角的坐标。 */ this.mode = mode; this.CLASS_NAME = 'SuperMap.Pixel'; } /** * @function Pixel.prototype.toString * @description 返回此对象的字符串形式。 * @example * * var pixcel = new Pixel(100,50); * var str = pixcel.toString(); * * @returns {string} 例如: "x=200.4,y=242.2" */ toString() { return 'x=' + this.x + ',y=' + this.y; } /** * @function Pixel.prototype.clone * @description 克隆当前的 pixel 对象。 * @example * var pixcel = new Pixel(100,50); * var pixcel2 = pixcel.clone(); * @returns {Pixel} 新的与当前 pixel 对象有相同 x、y 坐标的 pixel 对象。 */ clone() { return new Pixel(this.x, this.y, this.mode); } /** * @function Pixel.prototype.equals * @description 比较两 pixel 是否相等。 * @example * var pixcel = new Pixel(100,50); * var pixcel2 = new Pixel(100,50); * var isEquals = pixcel.equals(pixcel2); * * @param {Pixel} px - 用于比较相等的 pixel 对象。 * @returns {boolean} 如果传入的像素点和当前像素点相同返回 true,如果不同或传入参数为 NULL 则返回 false。 */ equals(px) { var equals = false; if (px != null) { equals = (this.x == px.x && this.y == px.y) || (isNaN(this.x) && isNaN(this.y) && isNaN(px.x) && isNaN(px.y)); } return equals; } /** * @function Pixel.prototype.distanceTo * @description 返回两个 pixel 的距离。 * @example * var pixcel = new Pixel(100,50); * var pixcel2 = new Pixel(110,30); * var distance = pixcel.distanceTo(pixcel2); * * @param {Pixel} px - 需要计算的 pixel。 * @returns {number} 作为参数传入的像素与当前像素点的距离。 */ distanceTo(px) { return Math.sqrt(Math.pow(this.x - px.x, 2) + Math.pow(this.y - px.y, 2)); } /** * @function Pixel.prototype.add * @description 在原来像素坐标基础上,x 值加上传入的 x 参数,y 值加上传入的 y 参数。 * @example * var pixcel = new Pixel(100,50); * //pixcel2是新的对象 * var pixcel2 = pixcel.add(20,30); * * @param {number} x - 传入的 x 值。 * @param {number} y - 传入的 y 值。 * @returns {Pixel} 新的 pixel 对象,该 pixel 是由当前的 pixel 与传入的 x,y 相加得到。 */ add(x, y) { if (x == null || y == null) { throw new TypeError('Pixel.add cannot receive null values'); } return new Pixel(this.x + x, this.y + y); } /** * @function Pixel.prototype.offset * @description 通过传入的 {@link Pixel} 参数对原屏幕坐标进行偏移。 * @example * var pixcel = new Pixel(100,50); * var pixcel2 = new Pixel(130,20); * //pixcel3 是新的对象 * var pixcel3 = pixcel.offset(pixcel2); * * @param {Pixel} px - 传入的 {@link Pixel} 对象。 * @returns {Pixel} 新的 pixel,该 pixel 是由当前的 pixel 对象的 x,y 值与传入的 Pixel 对象的 x,y 值相加得到。 */ offset(px) { var newPx = this.clone(); if (px) { newPx = this.add(px.x, px.y); } return newPx; } /** * * @function Pixel.prototype.destroy * @description 销毁此对象。销毁后此对象的所有属性为 null,而不是初始值。 * @example * var pixcel = new Pixel(100,50); * pixcel.destroy(); */ destroy() { this.x = null; this.y = null; this.mode = null; } } /** * @enum Mode * @memberOf Pixel * @readonly * @description 模式。 * @type {string} */ Pixel.Mode = { /** 左上模式。*/ LeftTop: 'lefttop', /** 右上模式。 */ RightTop: 'righttop', /** 右下模式。 */ RightBottom: 'rightbottom', /** 左下模式。 */ LeftBottom: 'leftbottom' }; ;// CONCATENATED MODULE: ./src/common/commontypes/BaseTypes.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @function inherit * @description 除了 C 和 P 两个必要参数外,可以传递任意数量的对象,这些对象都将继承C。 * @param {Object} C - 继承的类。 * @param {Object} P - 被继承的父类。 * @private */ var inheritExt = function (C, P) { var F = function () { }; F.prototype = P.prototype; C.prototype = new F; var i, l, o; for (i = 2, l = arguments.length; i < l; i++) { o = arguments[i]; if (typeof o === "function") { o = o.prototype; } Util.extend(C.prototype, o); } }; /** * @function mixinExt * @description 实现多重继承。 * @param {Class|Object} ...mixins - 继承的类。 * @private */ var mixinExt = function (...mixins) { class Mix { constructor(options) { for (var index = 0; index < mixins.length; index++) { copyProperties(this, new mixins[index](options)); } } } for (var index = 0; index < mixins.length; index++) { var mixin = mixins[index]; copyProperties(Mix, mixin); copyProperties(Mix.prototype, mixin.prototype); copyProperties(Mix.prototype, new mixin()); } return Mix; function copyProperties(target, source) { var ownKeys = Object.getOwnPropertyNames(source); if (Object.getOwnPropertySymbols) { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source)); } for (var index = 0; index < ownKeys.length; index++) { var key = ownKeys[index]; if (key !== "constructor" && key !== "prototype" && key !== "name" && key !== "length") { let desc = Object.getOwnPropertyDescriptor(source, key); if (window["ActiveXObject"]) { Object.defineProperty(target, key, desc || {}); } else { Object.defineProperty(target, key, desc); } } } } }; /** * @name String * @namespace * @category BaseTypes Util * @description 字符串操作的一系列常用扩展函数。 * @private */ var StringExt = { /** * @function StringExt.startsWith * @description 判断目标字符串是否以指定的子字符串开头。 * @param {string} str - 目标字符串。 * @param {string} sub - 查找的子字符串。 * @returns {boolean} 目标字符串以指定的子字符串开头,则返回 true;否则返回 false。 */ startsWith: function (str, sub) { return (str.indexOf(sub) == 0); }, /** * @function StringExt.contains * @description 判断目标字符串是否包含指定的子字符串。 * @param {string} str - 目标字符串。 * @param {string} sub - 查找的子字符串。 * @returns {boolean} 目标字符串中包含指定的子字符串,则返回 true;否则返回 false。 */ contains: function (str, sub) { return (str.indexOf(sub) != -1); }, /** * @function StringExt.trim * @description 删除一个字符串的开头和结尾处的所有空白字符。 * @param {string} str - (可能)存在空白字符填塞的字符串。 * @returns {string} 删除开头和结尾处空白字符后的字符串。 */ trim: function (str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }, /** * @function StringExt.camelize * @description 骆驼式("-")连字符的字符串处理。 * 例如:"chicken-head" becomes "chickenHead", * "-chicken-head" becomes "ChickenHead"。 * @param {string} str - 要处理的字符串,原始内容不应被修改。 * @returns {string} */ camelize: function (str) { var oStringList = str.split('-'); var camelizedString = oStringList[0]; for (var i = 1, len = oStringList.length; i < len; i++) { var s = oStringList[i]; camelizedString += s.charAt(0).toUpperCase() + s.substring(1); } return camelizedString; }, /** * @function StringExt.format * @description 提供带 ${token} 标记的字符串, 返回 context 对象属性中指定标记的属性值。 * @example * 示例: * (code) * 1、template = "${value,getValue}"; * context = {value: {getValue:function(){return Math.max.apply(null,argument);}}}; * args = [2,23,12,36,21]; * 返回值:36 * (end) * 示例: * (code) * 2、template = "$${{value,getValue}}"; * context = {value: {getValue:function(){return Math.max.apply(null,argument);}}}; * args = [2,23,12,36,21]; * 返回值:"${36}" * (end) * 示例: * (code) * 3、template = "${a,b}"; * context = {a: {b:"format"}}; * args = null; * 返回值:"format" * (end) * 示例: * (code) * 3、template = "${a,b}"; * context = null; * args = null; * 返回值:"${a.b}" * (end) * @param {string} template - 带标记的字符串将要被替换。参数 template 格式为"${token}",此处的 token 标记会替换为 context["token"] 属性的值。 * @param {Object} [context=window] - 带有属性的可选对象的属性用于匹配格式化字符串中的标记。如果该参数为空,将使用 window 对象。 * @param {Array.} [args] - 可选参数传递给在 context 对象上找到的函数。 * @returns {string} 从 context 对象属性中替换字符串标记位的字符串。 */ format: function (template, context, args) { if (!context) { context = window; } // Example matching: // str = ${foo.bar} // match = foo.bar var replacer = function (str, match) { var replacement; // Loop through all subs. Example: ${a.b.c} // 0 -> replacement = context[a]; // 1 -> replacement = context[a][b]; // 2 -> replacement = context[a][b][c]; var subs = match.split(/\.+/); for (var i = 0; i < subs.length; i++) { if (i == 0) { replacement = context; } replacement = replacement[subs[i]]; } if (typeof replacement === "function") { replacement = args ? replacement.apply(null, args) : replacement(); } // If replacement is undefined, return the string 'undefined'. // This is a workaround for a bugs in browsers not properly // dealing with non-participating groups in regular expressions: // http://blog.stevenlevithan.com/archives/npcg-javascript if (typeof replacement == 'undefined') { return 'undefined'; } else { return replacement; } }; return template.replace(StringExt.tokenRegEx, replacer); }, /** * @member {RegExp} [StringExt.tokenRegEx] * @description 寻找带 token 的字符串,默认为 tokenRegEx=/\$\{([\w.]+?)\}/g。 * @example * Examples: ${a}, ${a.b.c}, ${a-b}, ${5} */ tokenRegEx: /\$\{([\w.]+?)\}/g, /** * @member {RegExp} [StringExt.numberRegEx] * @description 判断一个字符串是否只包含一个数值,默认为 numberRegEx=/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/。 */ numberRegEx: /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/, /** * @function StringExt.isNumeric * @description 判断一个字符串是否只包含一个数值。 * @example * (code) * StringExt.isNumeric("6.02e23") // true * StringExt.isNumeric("12 dozen") // false * StringExt.isNumeric("4") // true * StringExt.isNumeric(" 4 ") // false * (end) * @returns {boolean} 字符串包含唯一的数值,返回 true;否则返回 false。 */ isNumeric: function (value) { return StringExt.numberRegEx.test(value); }, /** * @function StringExt.numericIf * @description 把一个看似数值型的字符串转化为一个数值。 * @returns {(number|string)} 如果能转换为数值则返回数值,否则返回字符串本身。 */ numericIf: function (value) { return StringExt.isNumeric(value) ? parseFloat(value) : value; } }; /** * @name Number * @namespace * @category BaseTypes Util * @description 数值操作的一系列常用扩展函数。 * @private */ var NumberExt = { /** * @member {string} [NumberExt.decimalSeparator='.'] * @description 格式化数字时默认的小数点分隔符。 * @constant */ decimalSeparator: ".", /** * @member {string} [NumberExt.thousandsSeparator=','] * @description 格式化数字时默认的千位分隔符。 * @constant */ thousandsSeparator: ",", /** * @function NumberExt.limitSigDigs * @description 限制浮点数的有效数字位数。 * @param {number} num - 浮点数。 * @param {number} sig - 有效位数。 * @returns {number} 将数字四舍五入到指定数量的有效位数。 */ limitSigDigs: function (num, sig) { var fig = 0; if (sig > 0) { fig = parseFloat(num.toPrecision(sig)); } return fig; }, /** * @function NumberExt.format * @description 数字格式化输出。 * @param {number} num - 数字。 * @param {number} [dec=0] - 数字的小数部分四舍五入到指定的位数。设置为 null 值时小数部分不变。 * @param {string} [tsep=','] - 千位分隔符。 * @param {string} [dsep='.'] - 小数点分隔符。 * @returns {string} 数字格式化后的字符串。 */ format: function (num, dec, tsep, dsep) { dec = (typeof dec != "undefined") ? dec : 0; tsep = (typeof tsep != "undefined") ? tsep : NumberExt.thousandsSeparator; dsep = (typeof dsep != "undefined") ? dsep : NumberExt.decimalSeparator; if (dec != null) { num = parseFloat(num.toFixed(dec)); } var parts = num.toString().split("."); if (parts.length === 1 && dec == null) { // integer where we do not want to touch the decimals dec = 0; } var integer = parts[0]; if (tsep) { var thousands = /(-?[0-9]+)([0-9]{3})/; while (thousands.test(integer)) { integer = integer.replace(thousands, "$1" + tsep + "$2"); } } var str; if (dec == 0) { str = integer; } else { var rem = parts.length > 1 ? parts[1] : "0"; if (dec != null) { rem = rem + new Array(dec - rem.length + 1).join("0"); } str = integer + dsep + rem; } return str; } }; if (!Number.prototype.limitSigDigs) { /** * APIMethod: Number.limitSigDigs * 限制浮点数的有效数字位数. * @param {number} sig -有效位数。 * @returns {number} 将数字四舍五入到指定数量的有效位数。 * 如果传入值 为 null、0、或者是负数, 返回值 0。 */ Number.prototype.limitSigDigs = function (sig) { return NumberExt.limitSigDigs(this, sig); }; } /** * @name Function * @namespace * @category BaseTypes Util * @description 函数操作的一系列常用扩展函数。 * @private */ var FunctionExt = { /** * @function FunctionExt.bind * @description 绑定函数到对象。方便创建 this 的作用域。 * @param {function} func - 输入函数。 * @param {Object} object - 对象绑定到输入函数(作为输入函数的 this 对象)。 * @returns {function} object 参数作为 func 函数的 this 对象。 */ bind: function (func, object) { // create a reference to all arguments past the second one var args = Array.prototype.slice.apply(arguments, [2]); return function () { // Push on any additional arguments from the actual function call. // These will come after those sent to the bind call. var newArgs = args.concat( Array.prototype.slice.apply(arguments, [0]) ); return func.apply(object, newArgs); }; }, /** * @function FunctionExt.bindAsEventListener * @description 绑定函数到对象,在调用该函数时配置并使用事件对象作为第一个参数。 * @param {function} func - 用于监听事件的函数。 * @param {Object} object - this 对象的引用。 * @returns {function} */ bindAsEventListener: function (func, object) { return function (event) { return func.call(object, event || window.event); }; }, /** * @function FunctionExt.False * @description 该函数仅仅返回 false。该函数主要是避免在 IE8 以下浏览中 DOM 事件句柄的匿名函数问题。 * @example * document.onclick = FunctionExt.False; * @returns {boolean} */ False: function () { return false; }, /** * @function FunctionExt.True * @description 该函数仅仅返回 true。该函数主要是避免在 IE8 以下浏览中 DOM 事件句柄的匿名函数问题。 * @example * document.onclick = FunctionExt.True; * @returns {boolean} */ True: function () { return true; }, /** * @function FunctionExt.Void * @description 可重用函数,仅仅返回 "undefined"。 * @returns {undefined} */ Void: function () { } }; /** * @name Array * @namespace * @category BaseTypes Util * @description 数组操作的一系列常用扩展函数。 * @private */ var ArrayExt = { /** * @function ArrayExt.filter * @description 过滤数组,提供了 ECMA-262 标准中 Array.prototype.filter 函数的扩展。详见:{@link http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter} * @param {Array} array - 要过滤的数组。 * @param {function} callback - 数组中的每一个元素调用该函数。
* 如果函数的返回值为 true,该元素将包含在返回的数组中。该函数有三个参数: 数组中的元素,元素的索引,数组自身。
* 如果设置了可选参数 caller,在调用 callback 时,使用可选参数 caller 设置为 callback 的参数。
* @param {Object} [caller] - 在调用 callback 时,使用参数 caller 设置为 callback 的参数。 * @returns {Array} callback 函数返回 true 时的元素将作为返回数组中的元素。 */ filter: function (array, callback, caller) { var selected = []; if (Array.prototype.filter) { selected = array.filter(callback, caller); } else { var len = array.length; if (typeof callback != "function") { throw new TypeError(); } for (var i = 0; i < len; i++) { if (i in array) { var val = array[i]; if (callback.call(caller, val, i, array)) { selected.push(val); } } } } return selected; } }; ;// CONCATENATED MODULE: ./src/common/commontypes/Geometry.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ // import {WKT} from '../format/WKT'; // import {Vector} from './Vector'; /** * @class Geometry * @deprecatedclass SuperMap.Geometry * @category BaseTypes Geometry * @classdesc 几何对象类,描述地理对象的几何图形。 * @usage */ class Geometry_Geometry { constructor() { this.CLASS_NAME = "SuperMap.Geometry"; /** * @member {string} Geometry.prototype.id * @description 几何对象的唯一标识符。 * */ this.id = Util.createUniqueID(this.CLASS_NAME + "_"); /** * @member {Geometry} Geometry.prototype.parent * @description 父类几何对象。 */ this.parent = null; /** * @member {Bounds} Geometry.prototype.bounds * @description 几何对象的范围。 * */ this.bounds = null; /** * @member {number} Geometry.prototype.SRID * @description 投影坐标参数。通过该参数,服务器判断 Geometry 对象的坐标参考系是否与数据集相同,如果不同,则在数据入库前进行投影变换。 * @example * var geometry= new Geometry(); * geometry. SRID=4326; * */ this.SRID = null; } /** * @function Geometry.prototype.destroy * @description 解构 Geometry 类,释放资源。 */ destroy() { this.id = null; this.bounds = null; this.SRID = null; } /** * @function Geometry.prototype.clone * @description 克隆几何图形。克隆的几何图形不设置非标准的属性。 * @returns {Geometry} 克隆的几何图形。 */ clone() { return new Geometry_Geometry(); } /** * @function Geometry.prototype.setBounds * @description 设置几何对象的 bounds。 * @param {Bounds} bounds - 范围。 */ setBounds(bounds) { if (bounds) { this.bounds = bounds.clone(); } } /** * @function Geometry.prototype.clearBounds * @description 清除几何对象的 bounds。 * 如果该对象有父类,也会清除父类几何对象的 bounds。 */ clearBounds() { this.bounds = null; if (this.parent) { this.parent.clearBounds(); } } /** * @function Geometry.prototype.extendBounds * @description 扩展现有边界以包含新边界。如果尚未设置几何边界,则设置新边界。 * @param {Bounds} newBounds - 几何对象的 bounds。 */ extendBounds(newBounds) { var bounds = this.getBounds(); if (!bounds) { this.setBounds(newBounds); } else { this.bounds.extend(newBounds); } } /** * @function Geometry.prototype.getBounds * @description 获得几何图形的边界。如果没有设置边界,可通过计算获得。 * @returns {Bounds} 几何对象的边界。 */ getBounds() { if (this.bounds == null) { this.calculateBounds(); } return this.bounds; } /** * @function Geometry.prototype.calculateBounds * @description 重新计算几何图形的边界(需要在子类中实现此方法)。 */ calculateBounds() { // // This should be overridden by subclasses. // } /** * @function Geometry.prototype.getVertices * @description 返回几何图形的所有顶点的列表(需要在子类中实现此方法)。 * @param {boolean} [nodes] - 如果是 true,线则只返回线的末端点,如果 false,仅仅返回顶点,如果没有设置,则返回顶点。 * @returns {Array} 几何图形的顶点列表。 */ getVertices(nodes) { // eslint-disable-line no-unused-vars } /** * @function Geometry.prototype.getArea * @description 计算几何对象的面积 ,此方法需要在子类中定义。 * @returns {number} 计算后的对象面积。 */ getArea() { //to be overridden by geometries that actually have an area // return 0.0; } // /** // * @function Geometry.prototype.toString // * @description 返回geometry对象的字符串表述,需要引入{@link WKTFormat}。此方法只能在子类实现,在父类使用会报错。 // * @returns {string} geometry对象的字符串表述(Well-Known Text) // */ // toString() { // var string; // if (WKT) { // var wkt = new WKT(); // string = wkt.write(new Vector(this)); // } else { // string = Object.prototype.toString.call(this); // } // return string; // } } ;// CONCATENATED MODULE: ./src/common/commontypes/Util.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @description 浏览器名称,依赖于 userAgent 属性,BROWSER_NAME 可以是空,或者以下浏览器: * * "opera" -- Opera * * "msie" -- Internet Explorer * * "safari" -- Safari * * "firefox" -- Firefox * * "mozilla" -- Mozilla * @category BaseTypes Constant * @constant {Object} * @usage * ``` * // 浏览器 * * * // ES6 Import * import { Browser } from '{npm}'; * * const result = Browser.name; * ``` */ const Browser = (function () { var name = '', version = '', device = 'pc', uaMatch; //以下进行测试 var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf('msie') > -1 || (ua.indexOf('trident') > -1 && ua.indexOf('rv') > -1)) { name = 'msie'; uaMatch = ua.match(/msie ([\d.]+)/) || ua.match(/rv:([\d.]+)/); } else if (ua.indexOf('chrome') > -1) { name = 'chrome'; uaMatch = ua.match(/chrome\/([\d.]+)/); } else if (ua.indexOf('firefox') > -1) { name = 'firefox'; uaMatch = ua.match(/firefox\/([\d.]+)/); } else if (ua.indexOf('opera') > -1) { name = 'opera'; uaMatch = ua.match(/version\/([\d.]+)/); } else if (ua.indexOf('safari') > -1) { name = 'safari'; uaMatch = ua.match(/version\/([\d.]+)/); } version = uaMatch ? uaMatch[1] : ''; if (ua.indexOf('ipad') > -1 || ua.indexOf('ipod') > -1 || ua.indexOf('iphone') > -1) { device = 'apple'; } else if (ua.indexOf('android') > -1) { uaMatch = ua.match(/version\/([\d.]+)/); version = uaMatch ? uaMatch[1] : ''; device = 'android'; } return { name: name, version: version, device: device }; })(); const isSupportCanvas = (function () { var checkRes = true, broz = Browser; if (document.createElement('canvas').getContext) { if (broz.name === 'firefox' && parseFloat(broz.version) < 5) { checkRes = false; } if (broz.name === 'safari' && parseFloat(broz.version) < 4) { checkRes = false; } if (broz.name === 'opera' && parseFloat(broz.version) < 10) { checkRes = false; } if (broz.name === 'msie' && parseFloat(broz.version) < 9) { checkRes = false; } } else { checkRes = false; } return checkRes; })(); /** * @description 如果 userAgent 捕获到浏览器使用的是 Gecko 引擎则返回 true。 * @constant {number} * @private */ const IS_GECKO = (function () { var ua = navigator.userAgent.toLowerCase(); return ua.indexOf('webkit') === -1 && ua.indexOf('gecko') !== -1; })(); /** * @constant {number} * @default * @description 分辨率与比例尺之间转换的常量。 * @private */ const DOTS_PER_INCH = 96; /** * @name CommonUtil * @namespace * @category BaseTypes Util * @description common 工具类。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { CommonUtil } from '{npm}'; * * const result = CommonUtil.getElement(); * ``` */ const Util = { /** * @memberOf CommonUtil * @description 复制源对象的所有属性到目标对象上,源对象上的没有定义的属性在目标对象上也不会被设置。 * @example * 要复制 Size 对象的所有属性到自定义对象上,使用方法如下: * var size = new Size(100, 100); * var obj = {}; * CommonUtil.extend(obj, size); * @param {Object} [destination] - 目标对象。 * @param {Object} source - 源对象,其属性将被设置到目标对象上。 * @returns {Object} 目标对象。 */ extend: function (destination, source) { destination = destination || {}; if (source) { for (var property in source) { var value = source[property]; if (value !== undefined) { destination[property] = value; } } /** * IE doesn't include the toString property when iterating over an object's * properties with the for(property in object) syntax. Explicitly check if * the source has its own toString property. */ /* * FF/Windows < 2.0.0.13 reports "Illegal operation on WrappedNative * prototype object" when calling hawOwnProperty if the source object * is an instance of window.Event. */ var sourceIsEvt = typeof window.Event === 'function' && source instanceof window.Event; if (!sourceIsEvt && source.hasOwnProperty && source.hasOwnProperty('toString')) { destination.toString = source.toString; } } return destination; }, /** * @memberOf CommonUtil * @description 对象拷贝。 * @param {Object} [des] - 目标对象。 * @param {Object} soc - 源对象。 */ copy: function (des, soc) { des = des || {}; var v; if (soc) { for (var p in des) { v = soc[p]; if (typeof v !== 'undefined') { des[p] = v; } } } }, /** * @memberOf CommonUtil * @description 销毁对象,将其属性置空。 * @param {Object} [obj] - 目标对象。 */ reset: function (obj) { obj = obj || {}; for (var p in obj) { if (obj.hasOwnProperty(p)) { if (typeof obj[p] === 'object' && obj[p] instanceof Array) { for (var i in obj[p]) { if (obj[p][i].destroy) { obj[p][i].destroy(); } } obj[p].length = 0; } else if (typeof obj[p] === 'object' && obj[p] instanceof Object) { if (obj[p].destroy) { obj[p].destroy(); } } obj[p] = null; } } }, /** * @memberOf CommonUtil * @description 获取 HTML 元素数组。 * @returns {Array.} HTML 元素数组。 */ getElement: function () { var elements = []; for (var i = 0, len = arguments.length; i < len; i++) { var element = arguments[i]; if (typeof element === 'string') { element = document.getElementById(element); } if (arguments.length === 1) { return element; } elements.push(element); } return elements; }, /** * @memberOf CommonUtil * @description instance of 的跨浏览器实现。 * @param {Object} o - 对象。 * @returns {boolean} 是否是页面元素。 */ isElement: function (o) { return !!(o && o.nodeType === 1); }, /** * @memberOf CommonUtil * @description 判断一个对象是否是数组。 * @param {Object} a - 对象。 * @returns {boolean} 是否是数组。 */ isArray: function (a) { return Object.prototype.toString.call(a) === '[object Array]'; }, /** * @memberOf CommonUtil * @description 从数组中删除某一项。 * @param {Array} array - 数组。 * @param {Object} item - 数组中要删除的一项。 * @returns {Array} 执行删除操作后的数组。 */ removeItem: function (array, item) { for (var i = array.length - 1; i >= 0; i--) { if (array[i] === item) { array.splice(i, 1); //break;more than once?? } } return array; }, /** * @memberOf CommonUtil * @description 获取某对象在数组中的索引值。 * @param {Array.} array - 数组。 * @param {Object} obj - 对象。 * @returns {number} 某对象在数组中的索引值。 */ indexOf: function (array, obj) { if (array == null) { return -1; } else { // use the build-in function if available. if (typeof array.indexOf === 'function') { return array.indexOf(obj); } else { for (var i = 0, len = array.length; i < len; i++) { if (array[i] === obj) { return i; } } return -1; } } }, /** * @memberOf CommonUtil * @description 修改某 DOM 元素的许多属性。 * @param {HTMLElement} element - 待修改的 DOM 元素。 * @param {string} [id] - DOM 元素的 ID。 * @param {Pixel} [px] - DOM 元素的 style 属性的 left 和 top 属性。 * @param {Size} [sz] - DOM 元素的 width 和 height 属性。 * @param {string} [position] - DOM 元素的 position 属性。 * @param {string} [border] - DOM 元素的 style 属性的 border 属性。 * @param {string} [overflow] - DOM 元素的 style 属性的 overflow 属性。 * @param {number} [opacity] - 不透明度值。取值范围为(0.0 - 1.0)。 */ modifyDOMElement: function (element, id, px, sz, position, border, overflow, opacity) { if (id) { element.id = id; } if (px) { element.style.left = px.x + 'px'; element.style.top = px.y + 'px'; } if (sz) { element.style.width = sz.w + 'px'; element.style.height = sz.h + 'px'; } if (position) { element.style.position = position; } if (border) { element.style.border = border; } if (overflow) { element.style.overflow = overflow; } if (parseFloat(opacity) >= 0.0 && parseFloat(opacity) < 1.0) { element.style.filter = 'alpha(opacity=' + opacity * 100 + ')'; element.style.opacity = opacity; } else if (parseFloat(opacity) === 1.0) { element.style.filter = ''; element.style.opacity = ''; } }, /** * @memberOf CommonUtil * @description 比较两个对象并合并。 * @param {Object} [to] - 目标对象。 * @param {Object} from - 源对象。 * @returns {Object} 返回合并后的对象。 */ applyDefaults: function (to, from) { to = to || {}; /* * FF/Windows < 2.0.0.13 reports "Illegal operation on WrappedNative * prototype object" when calling hawOwnProperty if the source object is an * instance of window.Event. */ var fromIsEvt = typeof window.Event === 'function' && from instanceof window.Event; for (var key in from) { if ( to[key] === undefined || (!fromIsEvt && from.hasOwnProperty && from.hasOwnProperty(key) && !to.hasOwnProperty(key)) ) { to[key] = from[key]; } } /** * IE doesn't include the toString property when iterating over an object's * properties with the for(property in object) syntax. Explicitly check if * the source has its own toString property. */ if ( !fromIsEvt && from && from.hasOwnProperty && from.hasOwnProperty('toString') && !to.hasOwnProperty('toString') ) { to.toString = from.toString; } return to; }, /** * @memberOf CommonUtil * @description 将参数对象转换为 HTTP 的 GET 请求中的参数字符串。例如:"key1=value1&key2=value2&key3=value3"。 * @param {Object} params - 参数对象。 * @returns {string} HTTP 的 GET 请求中的参数字符串。 */ getParameterString: function (params) { var paramsArray = []; for (var key in params) { var value = params[key]; if (value != null && typeof value !== 'function') { var encodedValue; if (Array.isArray(value) || value.toString() === '[object Object]') { encodedValue = encodeURIComponent(JSON.stringify(value)); } else { /* value is a string; simply encode */ encodedValue = encodeURIComponent(value); } paramsArray.push(encodeURIComponent(key) + '=' + encodedValue); } } return paramsArray.join('&'); }, /** * @memberOf CommonUtil * @description 给 URL 追加查询参数。 * @param {string} url - 待追加参数的 URL 字符串。 * @param {string} paramStr - 待追加的查询参数。 * @returns {string} 新的 URL。 */ urlAppend: function (url, paramStr) { var newUrl = url; if (paramStr) { if (paramStr.indexOf('?') === 0) { paramStr = paramStr.substring(1); } var parts = (url + ' ').split(/[?&]/); newUrl += parts.pop() === ' ' ? paramStr : parts.length ? '&' + paramStr : '?' + paramStr; } return newUrl; }, /** * @memberOf CommonUtil * @description 给 URL 追加 path 参数。 * @param {string} url - 待追加参数的 URL 字符串。 * @param {string} paramStr - 待追加的path参数。 * @returns {string} 新的 URL。 */ urlPathAppend: function (url, pathStr) { let newUrl = url; if (!pathStr) { return newUrl; } if (pathStr.indexOf('/') === 0) { pathStr = pathStr.substring(1); } const parts = url.split('?'); if (parts[0].indexOf('/', parts[0].length - 1) < 0) { parts[0] += '/'; } newUrl = `${parts[0]}${pathStr}${parts.length > 1 ? `?${parts[1]}` : ''}`; return newUrl; }, /** * @memberOf CommonUtil * @description 为了避免浮点精度错误而保留的有效位数。 * @type {number} * @default 14 */ DEFAULT_PRECISION: 14, /** * @memberOf CommonUtil * @description 将字符串以接近的精度转换为数字。 * @param {string} number - 字符串。 * @param {number} [precision=14] - 精度。 * @returns {number} 转化后的数字。 */ toFloat: function (number, precision) { if (precision == null) { precision = Util.DEFAULT_PRECISION; } if (typeof number !== 'number') { number = parseFloat(number); } return precision === 0 ? number : parseFloat(number.toPrecision(precision)); }, /** * @memberOf CommonUtil * @description 角度转弧度。 * @param {number} x - 角度。 * @returns {number} 转化后的弧度。 */ rad: function (x) { return (x * Math.PI) / 180; }, /** * @memberOf CommonUtil * @description 从 URL 字符串中解析出参数对象。 * @param {string} url - URL。 * @returns {Object} 解析出的参数对象。 */ getParameters: function (url) { // if no url specified, take it from the location bar url = url === null || url === undefined ? window.location.href : url; //parse out parameters portion of url string var paramsString = ''; if (StringExt.contains(url, '?')) { var start = url.indexOf('?') + 1; var end = StringExt.contains(url, '#') ? url.indexOf('#') : url.length; paramsString = url.substring(start, end); } var parameters = {}; var pairs = paramsString.split(/[&;]/); for (var i = 0, len = pairs.length; i < len; ++i) { var keyValue = pairs[i].split('='); if (keyValue[0]) { var key = keyValue[0]; try { key = decodeURIComponent(key); } catch (err) { key = unescape(key); } // being liberal by replacing "+" with " " var value = (keyValue[1] || '').replace(/\+/g, ' '); try { value = decodeURIComponent(value); } catch (err) { value = unescape(value); } // follow OGC convention of comma delimited values value = value.split(','); //if there's only one value, do not return as array if (value.length == 1) { value = value[0]; } parameters[key] = value; } } return parameters; }, /** * @memberOf CommonUtil * @description 不断递增计数变量,用于生成唯一 ID。 * @type {number} * @default 0 */ lastSeqID: 0, /** * @memberOf CommonUtil * @description 创建唯一 ID 值。 * @param {string} [prefix] - 前缀。 * @returns {string} 唯一的 ID 值。 */ createUniqueID: function (prefix) { if (prefix == null) { prefix = 'id_'; } Util.lastSeqID += 1; return prefix + Util.lastSeqID; }, /** * @memberOf CommonUtil * @description 判断并转化比例尺。 * @param {number} scale - 比例尺。 * @returns {number} 正常的 scale 值。 */ normalizeScale: function (scale) { var normScale = scale > 1.0 ? 1.0 / scale : scale; return normScale; }, /** * @memberOf CommonUtil * @description 比例尺转分辨率。 * @param {number} scale - 比例尺。 * @param {string} [units='degrees'] - 比例尺单位。 * @returns {number} 转化后的分辨率。 */ getResolutionFromScale: function (scale, units) { var resolution; if (scale) { if (units == null) { units = 'degrees'; } var normScale = Util.normalizeScale(scale); resolution = 1 / (normScale * INCHES_PER_UNIT[units] * DOTS_PER_INCH); } return resolution; }, /** * @memberOf CommonUtil * @description 分辨率转比例尺。 * @param {number} resolution - 分辨率。 * @param {string} [units='degrees'] - 分辨率单位。 * @returns {number} 转化后的比例尺。 */ getScaleFromResolution: function (resolution, units) { if (units == null) { units = 'degrees'; } var scale = resolution * INCHES_PER_UNIT[units] * DOTS_PER_INCH; return scale; }, /** * @memberOf CommonUtil * @description 获取浏览器相关信息。支持的浏览器包括:Opera,Internet Explorer,Safari,Firefox。 * @returns {Object} 浏览器名称、版本、设备名称。对应的属性分别为 name, version, device。 */ getBrowser: function () { return Browser; }, /** * @memberOf CommonUtil * @description 浏览器是否支持 Canvas。 * @returns {boolean} 当前浏览器是否支持 HTML5 Canvas。 */ isSupportCanvas, /** * @memberOf CommonUtil * @description 判断浏览器是否支持 Canvas。 * @returns {boolean} 当前浏览器是否支持 HTML5 Canvas 。 */ supportCanvas: function () { return Util.isSupportCanvas; }, /** * @memberOf CommonUtil * @description 判断一个 URL 请求是否在当前域中。 * @param {string} url - URL 请求字符串。 * @returns {boolean} URL 请求是否在当前域中。 */ isInTheSameDomain: function (url) { if (!url) { return true; } var index = url.indexOf('//'); var documentUrl = document.location.toString(); var documentIndex = documentUrl.indexOf('//'); if (index === -1) { return true; } else { var protocol; var substring = (protocol = url.substring(0, index)); var documentSubString = documentUrl.substring(documentIndex + 2); documentIndex = documentSubString.indexOf('/'); var documentPortIndex = documentSubString.indexOf(':'); var documentDomainWithPort = documentSubString.substring(0, documentIndex); //var documentPort; var documentprotocol = document.location.protocol; if (documentPortIndex !== -1) { // documentPort = +documentSubString.substring(documentPortIndex, documentIndex); } else { documentDomainWithPort += ':' + (documentprotocol.toLowerCase() === 'http:' ? 80 : 443); } if (documentprotocol.toLowerCase() !== substring.toLowerCase()) { return false; } substring = url.substring(index + 2); var portIndex = substring.indexOf(':'); index = substring.indexOf('/'); var domainWithPort = substring.substring(0, index); var domain; if (portIndex !== -1) { domain = substring.substring(0, portIndex); } else { domain = substring.substring(0, index); domainWithPort += ':' + (protocol.toLowerCase() === 'http:' ? 80 : 443); } var documentDomain = document.domain; if (domain === documentDomain && domainWithPort === documentDomainWithPort) { return true; } } return false; }, /** * @memberOf CommonUtil * @description 计算 iServer 服务的 REST 图层的显示分辨率,需要从 iServer 的 REST 图层表述中获取 viewBounds、viewer、scale、coordUnit、datumAxis 五个参数,来进行计算。 * @param {Bounds} viewBounds - 地图的参照可视范围,即地图初始化时默认的地图显示范围。 * @param {Size} viewer - 地图初始化时默认的地图图片的尺寸。 * @param {number} scale - 地图初始化时默认的显示比例尺。 * @param {string} [coordUnit='degrees'] - 投影坐标系统的地图单位。 * @param {number} [datumAxis=6378137] - 地理坐标系统椭球体长半轴。用户自定义地图的 Options 时,若未指定该参数的值,则系统默认为 WGS84 参考系的椭球体长半轴 6378137。 * @returns {number} 图层显示分辨率。 */ calculateDpi: function (viewBounds, viewer, scale, coordUnit, datumAxis) { //10000 是 0.1毫米与米的转换。DPI的计算公式:Viewer / DPI * 0.0254 * 10000 = ViewBounds * scale ,公式中的10000是为了提高计算结果的精度,以下出现的ratio皆为如此。 if (!viewBounds || !viewer || !scale) { return; } var ratio = 10000, rvbWidth = viewBounds.getWidth(), rvbHeight = viewBounds.getHeight(), rvWidth = viewer.w, rvHeight = viewer.h; //用户自定义地图的Options时,若未指定该参数的值,则系统默认为6378137米,即WGS84参考系的椭球体长半轴。 datumAxis = datumAxis || 6378137; coordUnit = coordUnit || 'degrees'; var dpi; if ( coordUnit.toLowerCase() === 'degree' || coordUnit.toLowerCase() === 'degrees' || coordUnit.toLowerCase() === 'dd' ) { let num1 = rvbWidth / rvWidth, num2 = rvbHeight / rvHeight, resolution = num1 > num2 ? num1 : num2; dpi = (0.0254 * ratio) / resolution / scale / ((Math.PI * 2 * datumAxis) / 360) / ratio; } else { let resolution = rvbWidth / rvWidth; dpi = (0.0254 * ratio) / resolution / scale / ratio; } return dpi; }, /** * @memberOf CommonUtil * @description 将对象转换成 JSON 字符串。 * @param {Object} obj - 要转换成 JSON 的 Object 对象。 * @returns {string} 转换后的 JSON 对象。 */ toJSON: function (obj) { var objInn = obj; if (objInn == null) { return null; } switch (objInn.constructor) { case String: //s = "'" + str.replace(/(["\\])/g, "\\$1") + "'"; string含有单引号出错 objInn = '"' + objInn.replace(/(["\\])/g, '\\$1') + '"'; objInn = objInn.replace(/\n/g, '\\n'); objInn = objInn.replace(/\r/g, '\\r'); objInn = objInn.replace('<', '<'); objInn = objInn.replace('>', '>'); objInn = objInn.replace(/%/g, '%25'); objInn = objInn.replace(/&/g, '%26'); return objInn; case Array: var arr = ''; for (var i = 0, len = objInn.length; i < len; i++) { arr += Util.toJSON(objInn[i]); if (i !== objInn.length - 1) { arr += ','; } } return "[" + arr + "]"; case Number: return isFinite(objInn) ? String(objInn) : null; case Boolean: return String(objInn); case Date: var dateStr = '{' + '\'__type\':"System.DateTime",' + "'Year':" + objInn.getFullYear() + ',' + "'Month':" + (objInn.getMonth() + 1) + ',' + "'Day':" + objInn.getDate() + ',' + "'Hour':" + objInn.getHours() + ',' + "'Minute':" + objInn.getMinutes() + ',' + "'Second':" + objInn.getSeconds() + ',' + "'Millisecond':" + objInn.getMilliseconds() + ',' + "'TimezoneOffset':" + objInn.getTimezoneOffset() + '}'; return dateStr; default: if (objInn['toJSON'] != null && typeof objInn['toJSON'] === 'function') { return objInn.toJSON(); } if (typeof objInn === 'object') { if (objInn.length) { let arr = []; for (let i = 0, len = objInn.length; i < len; i++) { arr.push(Util.toJSON(objInn[i])); } return '[' + arr.join(',') + ']'; } let arr = []; for (let attr in objInn) { //为解决Geometry类型头json时堆栈溢出的问题,attr == "parent"时不进行json转换 if (typeof objInn[attr] !== 'function' && attr !== 'CLASS_NAME' && attr !== 'parent') { arr.push("'" + attr + "':" + Util.toJSON(objInn[attr])); } } if (arr.length > 0) { return '{' + arr.join(',') + '}'; } else { return '{}'; } } return objInn.toString(); } }, /** * @memberOf CommonUtil * @description 根据比例尺和 DPI 计算屏幕分辨率。 * @category BaseTypes Util * @param {number} scale - 比例尺。 * @param {number} dpi - 图像分辨率,表示每英寸内的像素个数。 * @param {string} [coordUnit] - 投影坐标系统的地图单位。 * @param {number} [datumAxis=6378137] - 地理坐标系统椭球体长半轴。用户自定义地图的 Options 时,若未指定该参数的值,则 DPI 默认按照 WGS84 参考系的椭球体长半轴 6378137 来计算。 * @returns {number} 当前比例尺下的屏幕分辨率。 */ getResolutionFromScaleDpi: function (scale, dpi, coordUnit, datumAxis) { var resolution = null, ratio = 10000; //用户自定义地图的Options时,若未指定该参数的值,则系统默认为6378137米,即WGS84参考系的椭球体长半轴。 datumAxis = datumAxis || 6378137; coordUnit = coordUnit || ''; if (scale > 0 && dpi > 0) { scale = Util.normalizeScale(scale); if ( coordUnit.toLowerCase() === 'degree' || coordUnit.toLowerCase() === 'degrees' || coordUnit.toLowerCase() === 'dd' ) { //scale = Util.normalizeScale(scale); resolution = (0.0254 * ratio) / dpi / scale / ((Math.PI * 2 * datumAxis) / 360) / ratio; return resolution; } else { resolution = (0.0254 * ratio) / dpi / scale / ratio; return resolution; } } return -1; }, /** * @memberOf CommonUtil * @description 根据 resolution、dpi、coordUnit 和 datumAxis 计算比例尺。 * @param {number} resolution - 用于计算比例尺的地图分辨率。 * @param {number} dpi - 图像分辨率,表示每英寸内的像素个数。 * @param {string} [coordUnit] - 投影坐标系统的地图单位。 * @param {number} [datumAxis=6378137] - 地理坐标系统椭球体长半轴。用户自定义地图的 Options 时,若未指定该参数的值,则 DPI 默认按照 WGS84 参考系的椭球体长半轴 6378137 来计算。 * @returns {number} 当前屏幕分辨率下的比例尺。 */ getScaleFromResolutionDpi: function (resolution, dpi, coordUnit, datumAxis) { var scale = null, ratio = 10000; //用户自定义地图的Options时,若未指定该参数的值,则系统默认为6378137米,即WGS84参考系的椭球体长半轴。 datumAxis = datumAxis || 6378137; coordUnit = coordUnit || ''; if (resolution > 0 && dpi > 0) { if ( coordUnit.toLowerCase() === 'degree' || coordUnit.toLowerCase() === 'degrees' || coordUnit.toLowerCase() === 'dd' ) { scale = (0.0254 * ratio) / dpi / resolution / ((Math.PI * 2 * datumAxis) / 360) / ratio; return scale; } else { scale = (0.0254 * ratio) / dpi / resolution / ratio; return scale; } } return -1; }, /** * @memberOf CommonUtil * @description 转换查询结果。 * @param {Object} result - 查询结果。 * @returns {Object} 转换后的查询结果。 */ transformResult: function (result) { if (result.responseText && typeof result.responseText === 'string') { result = JSON.parse(result.responseText); } return result; }, /** * @memberOf CommonUtil * @description 属性拷贝,不拷贝方法类名(CLASS_NAME)等。 * @param {Object} [destination] - 拷贝目标。 * @param {Object} source - 源对象。 * */ copyAttributes: function (destination, source) { destination = destination || {}; if (source) { for (var property in source) { var value = source[property]; if (value !== undefined && property !== 'CLASS_NAME' && typeof value !== 'function') { destination[property] = value; } } } return destination; }, /** * @memberOf CommonUtil * @description 将源对象上的属性拷贝到目标对象上。(不拷贝 CLASS_NAME 和方法) * @param {Object} [destination] - 目标对象。 * @param {Object} source - 源对象。 * @param {Array.} clip - 源对象中禁止拷贝到目标对象的属性,目的是防止目标对象上不可修改的属性被篡改。 * */ copyAttributesWithClip: function (destination, source, clip) { destination = destination || {}; if (source) { for (var property in source) { //去掉禁止拷贝的属性 var isInClip = false; if (clip && clip.length) { for (var i = 0, len = clip.length; i < len; i++) { if (property === clip[i]) { isInClip = true; break; } } } if (isInClip === true) { continue; } var value = source[property]; if (value !== undefined && property !== 'CLASS_NAME' && typeof value !== 'function') { destination[property] = value; } } } return destination; }, /** * @memberOf CommonUtil * @description 克隆一个 Object 对象。 * @param {Object} obj - 需要克隆的对象。 * @returns {Object} 对象的拷贝对象,注意是新的对象,不是指向。 */ cloneObject: function (obj) { // Handle the 3 simple types, and null or undefined if (null === obj || 'object' !== typeof obj) { return obj; } // Handle Date if (obj instanceof Date) { let copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { let copy = obj.slice(0); return copy; } // Handle Object if (obj instanceof Object) { let copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = Util.cloneObject(obj[attr]); } } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }, /** * @memberOf CommonUtil * @description 判断两条线段是不是有交点。 * @param {GeometryPoint} a1 - 第一条线段的起始节点。 * @param {GeometryPoint} a2 - 第一条线段的结束节点。 * @param {GeometryPoint} b1 - 第二条线段的起始节点。 * @param {GeometryPoint} b2 - 第二条线段的结束节点。 * @returns {Object} 如果相交返回交点,如果不相交返回两条线段的位置关系。 */ lineIntersection: function (a1, a2, b1, b2) { var intersectValue = null; var k1; var k2; var b = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x); var a = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x); var ab = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y); //ab==0代表两条线断的斜率一样 if (ab != 0) { k1 = b / ab; k2 = a / ab; if (k1 >= 0 && k2 <= 1 && k1 <= 1 && k2 >= 0) { intersectValue = new Geometry_Geometry.Point(a1.x + k1 * (a2.x - a1.x), a1.y + k1 * (a2.y - a1.y)); } else { intersectValue = 'No Intersection'; } } else { if (b == 0 && a == 0) { var maxy = Math.max(a1.y, a2.y); var miny = Math.min(a1.y, a2.y); var maxx = Math.max(a1.x, a2.x); var minx = Math.min(a1.x, a2.x); if ( (((b1.y >= miny && b1.y <= maxy) || (b2.y >= miny && b2.y <= maxy)) && b1.x >= minx && b1.x <= maxx) || (b2.x >= minx && b2.x <= maxx) ) { intersectValue = 'Coincident'; //重合 } else { intersectValue = 'Parallel'; //平行 } } else { intersectValue = 'Parallel'; //平行 } } return intersectValue; }, /** * @memberOf CommonUtil * @description 获取文本外接矩形宽度与高度。 * @param {ThemeStyle} style - 文本样式。 * @param {string} text - 文本内容。 * @param {Object} element - DOM 元素。 * @returns {Object} 裁剪后的宽度,高度信息。 */ getTextBounds: function (style, text, element) { document.body.appendChild(element); element.style.width = 'auto'; element.style.height = 'auto'; if (style.fontSize) { element.style.fontSize = style.fontSize; } if (style.fontFamily) { element.style.fontFamily = style.fontFamily; } if (style.fontWeight) { element.style.fontWeight = style.fontWeight; } element.style.position = 'relative'; element.style.visibility = 'hidden'; //fix 在某些情况下,element内的文本变成竖起排列,导致宽度计算不正确的bug element.style.display = 'inline-block'; element.innerHTML = text; var textWidth = element.clientWidth; var textHeight = element.clientHeight; document.body.removeChild(element); return { textWidth: textWidth, textHeight: textHeight }; }, /** * @memberOf CommonUtil * @description 获取转换后的path路径。 * @param {string} path - 待转换的path,包含`{param}`。 * @param {Object} pathParams - path中待替换的参数。 * @returns {string} 转换后的path路径。 */ convertPath: function (path, pathParams) { if (!pathParams) { return path; } return path.replace(/\{([\w-\.]+)\}/g, (fullMatch, key) => { var value; if (pathParams.hasOwnProperty(key)) { value = paramToString(pathParams[key]); } else { value = fullMatch; } return encodeURIComponent(value); }); } }; /** * @enum INCHES_PER_UNIT * @description 每单位的英尺数。 * @type {number} * @private */ const INCHES_PER_UNIT = { inches: 1.0, ft: 12.0, mi: 63360.0, m: 39.3701, km: 39370.1, dd: 4374754, yd: 36 }; INCHES_PER_UNIT['in'] = INCHES_PER_UNIT.inches; INCHES_PER_UNIT['degrees'] = INCHES_PER_UNIT.dd; INCHES_PER_UNIT['nmi'] = 1852 * INCHES_PER_UNIT.m; // Units from CS-Map const METERS_PER_INCH = 0.0254000508001016002; Util.extend(INCHES_PER_UNIT, { Inch: INCHES_PER_UNIT.inches, Meter: 1.0 / METERS_PER_INCH, //EPSG:9001 Foot: 0.30480060960121920243 / METERS_PER_INCH, //EPSG:9003 IFoot: 0.3048 / METERS_PER_INCH, //EPSG:9002 ClarkeFoot: 0.3047972651151 / METERS_PER_INCH, //EPSG:9005 SearsFoot: 0.30479947153867624624 / METERS_PER_INCH, //EPSG:9041 GoldCoastFoot: 0.30479971018150881758 / METERS_PER_INCH, //EPSG:9094 IInch: 0.0254 / METERS_PER_INCH, MicroInch: 0.0000254 / METERS_PER_INCH, Mil: 0.0000000254 / METERS_PER_INCH, Centimeter: 0.01 / METERS_PER_INCH, Kilometer: 1000.0 / METERS_PER_INCH, //EPSG:9036 Yard: 0.91440182880365760731 / METERS_PER_INCH, SearsYard: 0.914398414616029 / METERS_PER_INCH, //EPSG:9040 IndianYard: 0.91439853074444079983 / METERS_PER_INCH, //EPSG:9084 IndianYd37: 0.91439523 / METERS_PER_INCH, //EPSG:9085 IndianYd62: 0.9143988 / METERS_PER_INCH, //EPSG:9086 IndianYd75: 0.9143985 / METERS_PER_INCH, //EPSG:9087 IndianFoot: 0.30479951 / METERS_PER_INCH, //EPSG:9080 IndianFt37: 0.30479841 / METERS_PER_INCH, //EPSG:9081 IndianFt62: 0.3047996 / METERS_PER_INCH, //EPSG:9082 IndianFt75: 0.3047995 / METERS_PER_INCH, //EPSG:9083 Mile: 1609.34721869443738887477 / METERS_PER_INCH, IYard: 0.9144 / METERS_PER_INCH, //EPSG:9096 IMile: 1609.344 / METERS_PER_INCH, //EPSG:9093 NautM: 1852.0 / METERS_PER_INCH, //EPSG:9030 'Lat-66': 110943.316488932731 / METERS_PER_INCH, 'Lat-83': 110946.25736872234125 / METERS_PER_INCH, Decimeter: 0.1 / METERS_PER_INCH, Millimeter: 0.001 / METERS_PER_INCH, Dekameter: 10.0 / METERS_PER_INCH, Decameter: 10.0 / METERS_PER_INCH, Hectometer: 100.0 / METERS_PER_INCH, GermanMeter: 1.0000135965 / METERS_PER_INCH, //EPSG:9031 CaGrid: 0.999738 / METERS_PER_INCH, ClarkeChain: 20.1166194976 / METERS_PER_INCH, //EPSG:9038 GunterChain: 20.11684023368047 / METERS_PER_INCH, //EPSG:9033 BenoitChain: 20.116782494375872 / METERS_PER_INCH, //EPSG:9062 SearsChain: 20.11676512155 / METERS_PER_INCH, //EPSG:9042 ClarkeLink: 0.201166194976 / METERS_PER_INCH, //EPSG:9039 GunterLink: 0.2011684023368047 / METERS_PER_INCH, //EPSG:9034 BenoitLink: 0.20116782494375872 / METERS_PER_INCH, //EPSG:9063 SearsLink: 0.2011676512155 / METERS_PER_INCH, //EPSG:9043 Rod: 5.02921005842012 / METERS_PER_INCH, IntnlChain: 20.1168 / METERS_PER_INCH, //EPSG:9097 IntnlLink: 0.201168 / METERS_PER_INCH, //EPSG:9098 Perch: 5.02921005842012 / METERS_PER_INCH, Pole: 5.02921005842012 / METERS_PER_INCH, Furlong: 201.1684023368046 / METERS_PER_INCH, Rood: 3.778266898 / METERS_PER_INCH, CapeFoot: 0.3047972615 / METERS_PER_INCH, Brealey: 375.0 / METERS_PER_INCH, ModAmFt: 0.304812252984505969011938 / METERS_PER_INCH, Fathom: 1.8288 / METERS_PER_INCH, 'NautM-UK': 1853.184 / METERS_PER_INCH, '50kilometers': 50000.0 / METERS_PER_INCH, '150kilometers': 150000.0 / METERS_PER_INCH }); //unit abbreviations supported by PROJ.4 Util.extend(INCHES_PER_UNIT, { mm: INCHES_PER_UNIT['Meter'] / 1000.0, cm: INCHES_PER_UNIT['Meter'] / 100.0, dm: INCHES_PER_UNIT['Meter'] * 100.0, km: INCHES_PER_UNIT['Meter'] * 1000.0, kmi: INCHES_PER_UNIT['nmi'], //International Nautical Mile fath: INCHES_PER_UNIT['Fathom'], //International Fathom ch: INCHES_PER_UNIT['IntnlChain'], //International Chain link: INCHES_PER_UNIT['IntnlLink'], //International Link 'us-in': INCHES_PER_UNIT['inches'], //U.S. Surveyor's Inch 'us-ft': INCHES_PER_UNIT['Foot'], //U.S. Surveyor's Foot 'us-yd': INCHES_PER_UNIT['Yard'], //U.S. Surveyor's Yard 'us-ch': INCHES_PER_UNIT['GunterChain'], //U.S. Surveyor's Chain 'us-mi': INCHES_PER_UNIT['Mile'], //U.S. Surveyor's Statute Mile 'ind-yd': INCHES_PER_UNIT['IndianYd37'], //Indian Yard 'ind-ft': INCHES_PER_UNIT['IndianFt37'], //Indian Foot 'ind-ch': 20.11669506 / METERS_PER_INCH //Indian Chain }); //将服务端的地图单位转成SuperMap的地图单位 INCHES_PER_UNIT['degree'] = INCHES_PER_UNIT.dd; INCHES_PER_UNIT['meter'] = INCHES_PER_UNIT.m; INCHES_PER_UNIT['foot'] = INCHES_PER_UNIT.ft; INCHES_PER_UNIT['inch'] = INCHES_PER_UNIT.inches; INCHES_PER_UNIT['mile'] = INCHES_PER_UNIT.mi; INCHES_PER_UNIT['kilometer'] = INCHES_PER_UNIT.km; INCHES_PER_UNIT['yard'] = INCHES_PER_UNIT.yd; function paramToString(param) { if (param == undefined || param == null) { return ''; } if (param instanceof Date) { return param.toJSON(); } if (canBeJsonified(param)) { return JSON.stringify(param); } return param.toString(); } function canBeJsonified(str) { if (typeof str !== 'string' && typeof str !== 'object') { return false; } try { const type = str.toString(); return type === '[object Object]' || type === '[object Array]'; } catch (err) { return false; } } ;// CONCATENATED MODULE: ./src/common/commontypes/LonLat.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LonLat * @category BaseTypes Geometry * @classdesc 这个类用来表示经度和纬度对。 * @param {number|Array.} [lon=0.0] - 地图单位上的 X 轴坐标或者横纵坐标组成的数组;如果地图是地理投影,则此值是经度,否则,此值是地图地理位置的 x 坐标。 * @param {number} [lat=0.0] - 地图单位上的 Y 轴坐标,如果地图是地理投影,则此值是纬度,否则,此值是地图地理位置的 y 坐标。 * @example * var lonLat = new LonLat(30,45); * @usage */ class LonLat { constructor(lon, lat) { if (Util.isArray(lon)) { lat = lon[1]; lon = lon[0]; } /** * @member {number} [LonLat.prototype.lon=0.0] * @description 地图的单位的 X 轴(横轴)坐标。 */ this.lon = lon ? Util.toFloat(lon) : 0.0; /** * @member {number} [LonLat.prototype.lat=0.0] * @description 地图的单位的 Y 轴(纵轴)坐标。 */ this.lat = lat ? Util.toFloat(lat) : 0.0; this.CLASS_NAME = "SuperMap.LonLat"; } /** * @function LonLat.prototype.toString * @description 返回此对象的字符串形式。 * @example * var lonLat = new LonLat(100,50); * var str = lonLat.toString(); * @returns {string} 例如: "lon=100,lat=50"。 */ toString() { return ("lon=" + this.lon + ",lat=" + this.lat); } /** * @function LonLat.prototype.toShortString * @description 将经度纬度转换成简单字符串。 * @example * var lonLat = new LonLat(100,50); * var str = lonLat.toShortString(); * @returns {string} 处理后的经纬度字符串。例如:"100,50"。 */ toShortString() { return (this.lon + "," + this.lat); } /** * @function LonLat.prototype.clone * @description 复制坐标对象,并返回复制后的新对象。 * @example * var lonLat1 = new LonLat(100,50); * var lonLat2 = lonLat1.clone(); * @returns {LonLat} 相同坐标值的新的坐标对象。 */ clone() { return new LonLat(this.lon, this.lat); } /** * @function LonLat.prototype.add * @description 在已有坐标对象的经纬度基础上加上新的坐标经纬度,并返回新的坐标对象。 * @example * var lonLat1 = new LonLat(100,50); * //lonLat2 是新的对象 * var lonLat2 = lonLat1.add(100,50); * @param {number} lon - 经度参数。 * @param {number} lat - 纬度参数。 * @returns {LonLat} 新的 LonLat 对象,此对象的经纬度是由传入的经纬度与当前的经纬度相加所得。 */ add(lon, lat) { if ((lon == null) || (lat == null)) { throw new TypeError('LonLat.add cannot receive null values'); } return new LonLat(this.lon + Util.toFloat(lon), this.lat + Util.toFloat(lat)); } /** * @function LonLat.prototype.equals * @description 判断两个坐标对象是否相等。 * @example * var lonLat1 = new LonLat(100,50); * var lonLat2 = new LonLat(100,50); * var isEquals = lonLat1.equals(lonLat2); * @param {LonLat} ll - 需要进行比较的坐标对象。 * @returns {boolean} 如果LonLat对象的经纬度和传入的经纬度一致则返回true,不一 * 致或传入的ll参数为NULL则返回false。 */ equals(ll) { var equals = false; if (ll != null) { equals = ((this.lon === ll.lon && this.lat === ll.lat) || (isNaN(this.lon) && isNaN(this.lat) && isNaN(ll.lon) && isNaN(ll.lat))); } return equals; } /** * @function LonLat.prototype.wrapDateLine * @description 通过传入的范围对象对坐标对象转换到该范围内。 * 如果经度小于给定范围最小精度,则在原经度基础上加上范围宽度,直到精度在范围内为止,如果经度大于给定范围则在原经度基础上减去范围宽度。 * 即指将不在经度范围内的坐标转换到范围以内(只会转换 lon,不会转换 lat,主要用于转移到日界线以内)。 * @example * var lonLat1 = new LonLat(420,50); * var lonLat2 = lonLat1.wrapDateLine( * new Bounds(-180,-90,180,90) * ); * @param {Bounds} maxExtent - 最大边界的范围。 * @returns {LonLat} 将坐标转换到范围对象以内,并返回新的坐标。 */ wrapDateLine(maxExtent) { var newLonLat = this.clone(); if (maxExtent) { //shift right? while (newLonLat.lon < maxExtent.left) { newLonLat.lon += maxExtent.getWidth(); } //shift left? while (newLonLat.lon > maxExtent.right) { newLonLat.lon -= maxExtent.getWidth(); } } return newLonLat; } /** * * @function LonLat.prototype.destroy * @description 销毁此对象。 * 销毁后此对象的所有属性为 null,而不是初始值。 * @example * var lonLat = new LonLat(100,50); * lonLat.destroy(); */ destroy() { this.lon = null; this.lat = null; } /** * @function LonLat.fromString * @description 通过字符串生成一个 {@link LonLat} 对象。 * @example * var str = "100,50"; * var lonLat = LonLat.fromString(str); * @param {string} str - 字符串的格式:Lon+","+Lat。如:"100,50"。 * @returns {LonLat} {@link LonLat} 对象。 */ static fromString(str) { var pair = str.split(","); return new LonLat(pair[0], pair[1]); } /** * @function LonLat.fromArray * @description 通过数组生成一个 {@link LonLat} 对象。 * @param {Array.} arr - 数组的格式,长度只能为2,:[Lon,Lat]。如:[5,-42]。 * @returns {LonLat} {@link LonLat} 对象。 */ static fromArray(arr) { var gotArr = Util.isArray(arr), lon = gotArr && arr[0], lat = gotArr && arr[1]; return new LonLat(lon, lat); } } ;// CONCATENATED MODULE: ./src/common/commontypes/Bounds.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Bounds * @deprecatedclass SuperMap.Bounds * @category BaseTypes Geometry * @classdesc 表示边界类实例。使用 bounds 之前需要设置 left,bottom,right,top 四个属性,这些属性的初始值为 null。 * @param {number|Array.} [left] - 如果是number,则表示左边界,注意考虑宽度,理论上小于 right 值。如果是数组,则表示 [left, bottom, right, top] 左下右上组成的数组。 * @param {number} [bottom] - 下边界。考虑高度,理论上小于 top 值。 * @param {number} [right] - 右边界。 * @param {number} [top] - 上边界。 * @example * var bounds = new Bounds(); * bounds.extend(new LonLat(4,5)); * bounds.extend(new LonLat(5,6)); * bounds.toBBOX(); // returns 4,5,5,6 * @usage */ class Bounds { constructor(left, bottom, right, top) { if (Util.isArray(left)) { top = left[3]; right = left[2]; bottom = left[1]; left = left[0]; } /** * @member {number} Bounds.prototype.left * @description 最小的水平坐标系。 */ this.left = left != null ? Util.toFloat(left) : this.left; /** * @member {number} Bounds.prototype.bottom * @description 最小的垂直坐标系。 */ this.bottom = bottom != null ? Util.toFloat(bottom) : this.bottom; /** * @member {number} Bounds.prototype.right * @description 最大的水平坐标系。 */ this.right = right != null ? Util.toFloat(right) : this.right; /** * @member {number} Bounds.prototype.top * @description 最大的垂直坐标系。 */ this.top = top != null ? Util.toFloat(top) : this.top; /** * @member {LonLat} Bounds.prototype.centerLonLat * @description bounds 的地图空间的中心点。用 getCenterLonLat() 获得。 */ this.centerLonLat = null; this.CLASS_NAME = "SuperMap.Bounds"; } /** * @function Bounds.prototype.clone * @description 复制当前 bounds 对象。 * @example * var bounds1 = new Bounds(-180,-90,180,90); * var bounds2 = bounds1.clone(); * @returns {Bounds} 克隆后的 bounds。 */ clone() { return new Bounds(this.left, this.bottom, this.right, this.top); } /** * @function Bounds.prototype.equals * @description 判断两个 bounds 对象是否相等。 * @example * var bounds1 = new Bounds(-180,-90,180,90); * var bounds2 = new Bounds(-180,-90,180,90); * var isEquals = bounds1.equals(bounds2); * @param {Bounds} bounds - 需要进行计较的 bounds。 * @returns {boolean} 如果 bounds 对象的边和传入的 bounds 一致则返回 true,不一致或传入的 bounds 参数为 NULL 则返回 false。 */ equals(bounds) { var equals = false; if (bounds != null) { equals = ((this.left === bounds.left) && (this.right === bounds.right) && (this.top === bounds.top) && (this.bottom === bounds.bottom)); } return equals; } /** * @function Bounds.prototype.toString * @description 返回此对象的字符串形式。 * @example * var bounds = new Bounds(-180,-90,180,90); * var str = bounds.toString(); * @returns {string} 边界对象的字符串表示形式(left,bottom,right,top),例如: "-180,-90,180,90"。 */ toString() { return [this.left, this.bottom, this.right, this.top].join(","); } /** * @function Bounds.prototype.toArray * @description 边界对象的数组表示形式。 * @example * var bounds = new Bounds(-180,-90,100,80); * //array1 = [-180,-90,100,80]; * var array1 = bounds.toArray(); * //array1 = [-90,-180,80,100]; * var array2 = bounds.toArray(true); * @param {boolean} [reverseAxisOrder=false] - 是否反转轴顺序。 * 如果设为 true,则倒转顺序(bottom,left,top,right),否则按正常轴顺序(left,bottom,right,top)。 * @returns {Array.} left, bottom, right, top 数组。 */ toArray(reverseAxisOrder) { if (reverseAxisOrder === true) { return [this.bottom, this.left, this.top, this.right]; } else { return [this.left, this.bottom, this.right, this.top]; } } /** * @function Bounds.prototype.toBBOX * @description 取小数点后 decimal 位数字进行四舍五入再转换为 BBOX 字符串。 * @example * var bounds = new Bounds(-1.1234567,-1.7654321,1.4444444,1.5555555); * //str1 = "-1.123457,-1.765432,1.444444,1.555556"; * var str1 = bounds.toBBOX(); * //str2 = "-1.1,-1.8,1.4,1.6"; * var str2 = bounds.toBBOX(1); * //str2 = "-1.8,-1.1,1.6,1.4"; * var str2 = bounds.toBBOX(1,true); * @param {number} [decimal=6] - 边界方位坐标的有效数字个数。 * @param {boolean} [reverseAxisOrder=false] - 是否是反转轴顺序。 * 如果设为true,则倒转顺序(bottom,left,top,right),否则按正常轴顺序(left,bottom,right,top)。 * @returns {string} 边界对象的字符串表示形式,如:"5,42,10,45"。 */ toBBOX(decimal, reverseAxisOrder) { if (decimal == null) { decimal = 6; } var mult = Math.pow(10, decimal); var xmin = Math.round(this.left * mult) / mult; var ymin = Math.round(this.bottom * mult) / mult; var xmax = Math.round(this.right * mult) / mult; var ymax = Math.round(this.top * mult) / mult; if (reverseAxisOrder === true) { return ymin + "," + xmin + "," + ymax + "," + xmax; } else { return xmin + "," + ymin + "," + xmax + "," + ymax; } } ///** // * @function Bounds.prototype.toGeometry // * @description 基于当前边界范围创建一个新的多边形对象。 // * @example // * var bounds = new Bounds(-180,-90,100,80); // * // Polygon对象 // * var geo = bounds.toGeometry(); // * @returns {GeometryPolygon} 基于当前 bounds 坐标创建的新的多边形。 // */ // toGeometry() { // return new Polygon([ // new LinearRing([ // new Point(this.left, this.bottom), // new Point(this.right, this.bottom), // new Point(this.right, this.top), // new Point(this.left, this.top) // ]) // ]); // } /** * @function Bounds.prototype.getWidth * @description 获取 bounds 的宽度。 * @example * var bounds = new Bounds(-180,-90,100,80); * //width = 280; * var width = bounds.getWidth(); * @returns {number} 获取当前 bounds 的宽度(right 减去 left)。 */ getWidth() { return (this.right - this.left); } /** * @function Bounds.prototype.getHeight * @description 获取 bounds 的高度。 * @example * var bounds = new Bounds(-180,-90,100,80); * //height = 170; * var height = bounds.getHeight(); * @returns {number} 边界高度(top 减去 bottom)。 */ getHeight() { return (this.top - this.bottom); } /** * @function Bounds.prototype.getSize * @description 获取边框大小。 * @example * var bounds = new Bounds(-180,-90,100,80); * var size = bounds.getSize(); * @returns {Size} 边框大小。 */ getSize() { return new Size(this.getWidth(), this.getHeight()); } /** * @function Bounds.prototype.getCenterPixel * @description 获取像素格式的范围中心点。 * @example * var bounds = new Bounds(-180,-90,100,80); * var pixel = bounds.getCenterPixel(); * @returns {Pixel} 像素格式的当前范围的中心点。 */ getCenterPixel() { return new Pixel((this.left + this.right) / 2, (this.bottom + this.top) / 2); } /** * @function Bounds.prototype.getCenterLonLat * @description 获取地理格式的范围中心点。 * @example * var bounds = new Bounds(-180,-90,100,80); * var lonlat = bounds.getCenterLonLat(); * @returns {LonLat} 当前地理范围的中心点。 */ getCenterLonLat() { if (!this.centerLonLat) { this.centerLonLat = new LonLat( (this.left + this.right) / 2, (this.bottom + this.top) / 2 ); } return this.centerLonLat; } /** * @function Bounds.prototype.scale * @description 按照比例扩大/缩小出一个新的 bounds。 * @example * var bounds = new Bounds(-50,-50,40,40); * var bounds2 = bounds.scale(2); * @param {number} [ratio=1] - 需要扩大的比例。 * @param {(Pixel|LonLat)} [origin] - 扩大时的基准点,默认为当前 bounds 的中心点。 * @returns {Bounds} 通过 ratio、origin 计算得到的新的边界范围。 */ scale(ratio, origin) { ratio = ratio ? ratio : 1; if (origin == null) { origin = this.getCenterLonLat(); } var origx, origy; // get origin coordinates if (origin.CLASS_NAME === "SuperMap.LonLat") { origx = origin.lon; origy = origin.lat; } else { origx = origin.x; origy = origin.y; } var left = (this.left - origx) * ratio + origx; var bottom = (this.bottom - origy) * ratio + origy; var right = (this.right - origx) * ratio + origx; var top = (this.top - origy) * ratio + origy; return new Bounds(left, bottom, right, top); } /** * @function Bounds.prototype.add * @description 在当前的 Bounds 上按照传入的坐标点进行平移,返回新的范围。 * @example * var bounds1 = new Bounds(-50,-50,40,40); * //bounds2 是新的 bounds * var bounds2 = bounds.add(20,10); * @param {number} x - 坐标点的 x 坐标。 * @param {number} y - 坐标点的 y 坐标。 * @returns {Bounds} 新的 bounds,此 bounds 的坐标是由传入的 x,y 参数与当前 bounds 坐标计算所得。 */ add(x, y) { if ((x == null) || (y == null)) { throw new TypeError('Bounds.add cannot receive null values'); } return new Bounds(this.left + x, this.bottom + y, this.right + x, this.top + y); } /** * @function Bounds.prototype.extend * @description 在当前 bounds 上扩展 bounds,支持 point,lonlat 和 bounds。扩展后的 bounds 的范围是两者的结合。 * @example * var bounds1 = new Bounds(-50,-50,40,40); * //bounds 改变 * bounds.extend(new LonLat(50,60)); * @param {GeometryPoint|LonLat|Bounds} object - 可以是 point、lonlat 和 bounds。 */ extend(object) { var bounds = null; if (object) { // clear cached center location switch (object.CLASS_NAME) { case "SuperMap.LonLat": bounds = new Bounds(object.lon, object.lat, object.lon, object.lat); break; case "SuperMap.Geometry.Point": bounds = new Bounds(object.x, object.y, object.x, object.y); break; case "SuperMap.Bounds": bounds = object; break; } if (bounds) { this.centerLonLat = null; if ((this.left == null) || (bounds.left < this.left)) { this.left = bounds.left; } if ((this.bottom == null) || (bounds.bottom < this.bottom)) { this.bottom = bounds.bottom; } if ((this.right == null) || (bounds.right > this.right)) { this.right = bounds.right; } if ((this.top == null) || (bounds.top > this.top)) { this.top = bounds.top; } } } } /** * @function Bounds.prototype.containsLonLat * @description 判断传入的坐标是否在范围内。 * @example * var bounds1 = new Bounds(-50,-50,40,40); * //isContains1 = true * //这里的第二个参数可以直接为 boolean 类型,也就是inclusive * var isContains1 = bounds.containsLonLat(new LonLat(40,40),true); * * //(40,40)在范围内,同样(40+360,40)也在范围内 * var bounds2 = new Bounds(-50,-50,40,40); * //isContains2 = true; * var isContains2 = bounds2.containsLonLat( * new LonLat(400,40), * { * inclusive:true, * //全球的范围 * worldBounds: new Bounds(-180,-90,180,90) * } * ); * @param {(LonLat|Object)} ll - 对象或者是一个包含 'lon' 与 'lat' 属性的对象。 * @param {Object} options - 可选参数。 * @param {boolean} [options.inclusive=true] - 是否包含边界。 * @param {Bounds} [options.worldBounds] - 如果提供 worldBounds 参数, 如果 ll 参数提供的坐标超出了世界边界(worldBounds), * 但是通过日界线的转化可以被包含, 它将被认为是包含在该范围内的。 * @returns {boolean} 传入坐标是否包含在范围内。 */ containsLonLat(ll, options) { if (typeof options === "boolean") { options = {inclusive: options}; } options = options || {}; var contains = this.contains(ll.lon, ll.lat, options.inclusive), worldBounds = options.worldBounds; //日界线以外的也有可能算包含, if (worldBounds && !contains) { var worldWidth = worldBounds.getWidth(); var worldCenterX = (worldBounds.left + worldBounds.right) / 2; //这一步很关键 var worldsAway = Math.round((ll.lon - worldCenterX) / worldWidth); contains = this.containsLonLat({ lon: ll.lon - worldsAway * worldWidth, lat: ll.lat }, {inclusive: options.inclusive}); } return contains; } /** * @function Bounds.prototype.containsPixel * @description 判断传入的像素是否在范围内。直接匹配大小,不涉及像素和地理转换。 * @example * var bounds = new Bounds(-50,-50,40,40); * //isContains = true * var isContains = bounds.containsPixel(new Pixel(40,40),true); * @param {Pixel} px - 提供的像素参数。 * @param {boolean} [inclusive=true] - 是否包含边界。 * @returns {boolean} 传入的 pixel 在当前边界范围之内。 */ containsPixel(px, inclusive) { return this.contains(px.x, px.y, inclusive); } /** * @function Bounds.prototype.contains * @description 判断传入的 x,y 坐标值是否在范围内。 * @example * var bounds = new Bounds(-50,-50,40,40); * //isContains = true * var isContains = bounds.contains(40,40,true); * @param {number} x - x 坐标值。 * @param {number} y - y 坐标值。 * @param {boolean} [inclusive=true] - 是否包含边界。 * @returns {boolean} 传入的 x,y 坐标是否在当前范围内。 */ contains(x, y, inclusive) { //set default if (inclusive == null) { inclusive = true; } if (x == null || y == null) { return false; } //x = Util.toFloat(x); //y = Util.toFloat(y); var contains = false; if (inclusive) { contains = ((x >= this.left) && (x <= this.right) && (y >= this.bottom) && (y <= this.top)); } else { contains = ((x > this.left) && (x < this.right) && (y > this.bottom) && (y < this.top)); } return contains; } /** * @function Bounds.prototype.intersectsBounds * @description 判断目标边界范围是否与当前边界范围相交。如果两个边界范围中的任意边缘相交或者一个边界包含了另外一个就认为这两个边界相交。 * @example * var bounds = new Bounds(-180,-90,100,80); * var isIntersects = bounds.intersectsBounds( * new Bounds(-170,-90,120,80) * ); * @param {Bounds} bounds - 目标边界。 * @param {Object} options - 参数。 * @param {boolean} [options.inclusive=true] - 边缘重合也看成相交。如果是false,两个边界范围没有重叠部分仅仅是在边缘相接(重合),这种情况被认为没有相交。 * @param {Bounds} [options.worldBounds] - 提供了 worldBounds 参数,如果他们相交时是在全球范围内,两个边界将被视为相交。这仅适用于交叉或完全不在世界范围的边界。 * @returns {boolean} 传入的 bounds 对象与当前 bounds 相交。 */ intersectsBounds(bounds, options) { if (typeof options === "boolean") { options = {inclusive: options}; } options = options || {}; if (options.worldBounds) { var self = this.wrapDateLine(options.worldBounds); bounds = bounds.wrapDateLine(options.worldBounds); } else { self = this; } if (options.inclusive == null) { options.inclusive = true; } var intersects = false; var mightTouch = ( self.left === bounds.right || self.right === bounds.left || self.top === bounds.bottom || self.bottom === bounds.top ); // if the two bounds only touch at an edge, and inclusive is false, // then the bounds don't *really* intersect. if (options.inclusive || !mightTouch) { // otherwise, if one of the boundaries even partially contains another, // inclusive of the edges, then they do intersect. var inBottom = ( ((bounds.bottom >= self.bottom) && (bounds.bottom <= self.top)) || ((self.bottom >= bounds.bottom) && (self.bottom <= bounds.top)) ); var inTop = ( ((bounds.top >= self.bottom) && (bounds.top <= self.top)) || ((self.top > bounds.bottom) && (self.top < bounds.top)) ); var inLeft = ( ((bounds.left >= self.left) && (bounds.left <= self.right)) || ((self.left >= bounds.left) && (self.left <= bounds.right)) ); var inRight = ( ((bounds.right >= self.left) && (bounds.right <= self.right)) || ((self.right >= bounds.left) && (self.right <= bounds.right)) ); intersects = ((inBottom || inTop) && (inLeft || inRight)); } // document me if (options.worldBounds && !intersects) { var world = options.worldBounds; var width = world.getWidth(); var selfCrosses = !world.containsBounds(self); var boundsCrosses = !world.containsBounds(bounds); if (selfCrosses && !boundsCrosses) { bounds = bounds.add(-width, 0); intersects = self.intersectsBounds(bounds, {inclusive: options.inclusive}); } else if (boundsCrosses && !selfCrosses) { self = self.add(-width, 0); intersects = bounds.intersectsBounds(self, {inclusive: options.inclusive}); } } return intersects; } /** * @function Bounds.prototype.containsBounds * @description 判断目标边界是否被当前边界包含在内。 * @example * var bounds = new Bounds(-180,-90,100,80); * var isContains = bounds.containsBounds( * new Bounds(-170,-90,100,80),true,true * ); * @param {Bounds} bounds - 目标边界。 * @param {boolean} [partial=false] - 目标边界的任意部分都包含在当前边界中则被认为是包含关系。 * 如果设为 false,整个目标边界全部被包含在当前边界范围内。 * @param {boolean} [inclusive=true] - 边缘共享是否被视为包含。 * @returns {boolean} 传入的边界是否被当前边界包含。 */ containsBounds(bounds, partial, inclusive) { if (partial == null) { partial = false; } if (inclusive == null) { inclusive = true; } var bottomLeft = this.contains(bounds.left, bounds.bottom, inclusive); var bottomRight = this.contains(bounds.right, bounds.bottom, inclusive); var topLeft = this.contains(bounds.left, bounds.top, inclusive); var topRight = this.contains(bounds.right, bounds.top, inclusive); return (partial) ? (bottomLeft || bottomRight || topLeft || topRight) : (bottomLeft && bottomRight && topLeft && topRight); } /** * @function Bounds.prototype.determineQuadrant * @description 判断传入坐标是否在 bounds 范围内的象限。以 bounds 中心点为坐标原点。 * @example * var bounds = new Bounds(-180,-90,100,80); * //str = "tr"; * var str = bounds.determineQuadrant( * new LonLat(20,20) * ); * @param {LonLat} lonlat - 传入的坐标对象。 * @returns {string} 传入坐标所在的象限("br" "tr" "tl" "bl" 分别对应"右下","右上","左上" "左下")。 */ determineQuadrant(lonlat) { var quadrant = ""; var center = this.getCenterLonLat(); quadrant += (lonlat.lat < center.lat) ? "b" : "t"; quadrant += (lonlat.lon < center.lon) ? "l" : "r"; return quadrant; } /** * @function Bounds.prototype.wrapDateLine * @description 将当前 bounds 移动到最大边界范围内部(所谓的内部是相交或者内部)。 * @example * var bounds = new Bounds(380,-40,400,-20); * var maxExtent = new Bounds(-180,-90,100,80); * //新的bounds * var newBounds = bounds.wrapDateLine(maxExtent); * @param {Bounds} maxExtent - 最大的边界范围(一般是全球范围)。 * @param {Object} options - 可选选项参数。 * @param {number} [options.leftTolerance=0] - left 允许的误差。 * @param {number} [options.rightTolerance=0] - right 允许的误差。 * @returns {Bounds} 克隆当前边界。如果当前边界完全在最大范围之外此函数则返回一个不同值的边界, * 若落在最大边界的左边,则给当前的bounds值加上最大范围的宽度,即向右移动, * 若落在右边,则向左移动,即给当前的bounds值加上负的最大范围的宽度。 */ wrapDateLine(maxExtent, options) { options = options || {}; var leftTolerance = options.leftTolerance || 0; var rightTolerance = options.rightTolerance || 0; var newBounds = this.clone(); if (maxExtent) { var width = maxExtent.getWidth(); //如果 newBounds 在 maxExtent 的左边,那么一直向右移动,直到相交或者包含为止,每次移动width //shift right? while (newBounds.left < maxExtent.left && newBounds.right - rightTolerance <= maxExtent.left) { newBounds = newBounds.add(width, 0); } //如果 newBounds 在 maxExtent 的右边,那么一直向左移动,直到相交或者包含为止,每次移动width //shift left? while (newBounds.left + leftTolerance >= maxExtent.right && newBounds.right > maxExtent.right) { newBounds = newBounds.add(-width, 0); } //如果和右边相交,左边又在内部,那么再次向左边移动一次 // crosses right only? force left var newLeft = newBounds.left + leftTolerance; if (newLeft < maxExtent.right && newLeft > maxExtent.left && newBounds.right - rightTolerance > maxExtent.right) { newBounds = newBounds.add(-width, 0); } } return newBounds; } /** * @function Bounds.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @example * var bounds = new Bounds(-180,-90,100,80); * var obj = bounds.toServerJSONObject(); * @returns {Object} JSON 格式的 Object 对象。 */ toServerJSONObject() { var jsonObject = { rightTop: {x: this.right, y: this.top}, leftBottom: {x: this.left, y: this.bottom}, left: this.left, right: this.right, top: this.top, bottom: this.bottom } return jsonObject; } /** * * @function Bounds.prototype.destroy * @description 销毁此对象。 * 销毁后此对象的所有属性为 null,而不是初始值。 * @example * var bounds = new Bounds(-180,-90,100,80); * bounds.destroy(); */ destroy() { this.left = null; this.right = null; this.top = null; this.bottom = null; this.centerLonLat = null; } /** * @function Bounds.fromString * @description 通过字符串参数创建新的 bounds 的构造函数。 * @example * var bounds = Bounds.fromString("-180,-90,100,80"); * @param {string} str - 边界字符串,用逗号隔开(e.g. "5,42,10,45")。 * @param {boolean} [reverseAxisOrder=false] - 是否反转轴顺序。 * 如果设为true,则倒转顺序(bottom,left,top,right),否则按正常轴顺序(left,bottom,right,top)。 * @returns {Bounds} 给定的字符串创建的新的边界对象。 */ static fromString(str, reverseAxisOrder) { var bounds = str.split(","); return Bounds.fromArray(bounds, reverseAxisOrder); } /** * @function Bounds.fromArray * @description 通过边界框数组创建 Bounds。 * @example * var bounds = Bounds.fromArray([-180,-90,100,80]); * @param {Array.} bbox - 边界值数组。(e.g. [5,42,10,45])。 * @param {boolean} [reverseAxisOrder=false] - 是否是反转轴顺序。如果设为true,则倒转顺序(bottom,left,top,right),否则按正常轴顺序(left,bottom,right,top)。 * @returns {Bounds} 根据传入的数组创建的新的边界对象。 */ static fromArray(bbox, reverseAxisOrder) { return reverseAxisOrder === true ? new Bounds(bbox[1], bbox[0], bbox[3], bbox[2]) : new Bounds(bbox[0], bbox[1], bbox[2], bbox[3]); } /** * @function Bounds.fromSize * @description 通过传入的边界大小来创建新的边界。 * @example * var bounds = Bounds.fromSize(new Size(20,10)); * @param {Size} size - 边界大小。 * @returns {Bounds} 根据传入的边界大小的创建新的边界。 */ static fromSize(size) { return new Bounds(0, size.h, size.w, 0); } /** * @function Bounds.oppositeQuadrant * @description 反转象限。"t"和"b" 交换,"r"和"l"交换, 如:"tl"变为"br"。 * @param {string} quadrant - 代表象限的字符串,如:"tl"。 * @returns {string} 反转后的象限。 */ static oppositeQuadrant(quadrant) { var opp = ""; opp += (quadrant.charAt(0) === 't') ? 'b' : 't'; opp += (quadrant.charAt(1) === 'l') ? 'r' : 'l'; return opp; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/Collection.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryCollection * @aliasclass Geometry.Collection * @deprecatedclass SuperMap.Geometry.Collection * @classdesc 几何对象集合类,存储在本地的 components 属性中(可作为参数传递给构造函数)。
* 随着新的几何图形添加到集合中,将不能被克隆,当移动几何图形时,需要指定参照物。
* getArea 和 getLength 函数只能通过遍历存储几何对象的 components 数组,总计所有几何图形的面积和长度。 * @category BaseTypes Geometry * @extends {Geometry} * @param {Array.} components - 几何对象数组。 * @example * var point1 = new GeometryPoint(10,20); * var point2 = new GeometryPoint(30,40); * var col = new GeometryCollection([point1,point2]); * @usage */ class Collection extends Geometry_Geometry { constructor(components) { super(); /** * @description 存储几何对象的数组。 * @member {Array.} GeometryCollection.prototype.components */ this.components = []; /** * @member {Array.} GeometryCollection.prototype.componentTypes * @description components 存储的几何对象所支持的几何类型数组,为空表示类型不受限制。 */ this.componentTypes = null; if (components != null) { this.addComponents(components); } this.CLASS_NAME = "SuperMap.Geometry.Collection"; this.geometryType = "Collection"; } /** * @function GeometryCollection.prototype.destroy * @description 销毁几何图形。 */ destroy() { this.components.length = 0; this.components = null; super.destroy(); } /** * @function GeometryCollection.prototype.clone * @description 克隆当前几何对象。 * @returns {GeometryCollection} 克隆的几何对象集合。 */ clone() { var geometry = new Collection(); for (var i = 0, len = this.components.length; i < len; i++) { geometry.addComponent(this.components[i].clone()); } // catch any randomly tagged-on properties Util.applyDefaults(geometry, this); return geometry; } /** * @function GeometryCollection.prototype.getComponentsString * @description 获取 components 字符串。 * @returns {string} components 字符串。 */ getComponentsString() { var strings = []; for (var i = 0, len = this.components.length; i < len; i++) { strings.push(this.components[i].toShortString()); } return strings.join(","); } /** * @function GeometryCollection.prototype.calculateBounds * @description 通过遍历数组重新计算边界,在遍历每一子项中时调用 extend 方法。 */ calculateBounds() { this.bounds = null; var bounds = new Bounds(); var components = this.components; if (components) { for (var i = 0, len = components.length; i < len; i++) { bounds.extend(components[i].getBounds()); } } // to preserve old behavior, we only set bounds if non-null // in the future, we could add bounds.isEmpty() if (bounds.left != null && bounds.bottom != null && bounds.right != null && bounds.top != null) { this.setBounds(bounds); } } /** * @function GeometryCollection.prototype.addComponents * @description 给几何图形对象添加元素。 * @param {Array.} components - 几何对象组件。 * @example * var geometryCollection = new GeometryCollection(); * geometryCollection.addComponents(new SuerpMap.Geometry.Point(10,10)); */ addComponents(components) { if (!(Util.isArray(components))) { components = [components]; } for (var i = 0, len = components.length; i < len; i++) { this.addComponent(components[i]); } } /** * @function GeometryCollection.prototype.addComponent * @description 添加几何对象到集合中。如果设置了 componentTypes 类型,则添加的几何对象必须是 componentTypes 中的类型。 * @param {Geometry} component - 待添加的几何对象。 * @param {number} [index] - 几何对象插入的位置。 * @returns {boolean} 是否添加成功。 */ addComponent(component, index) { var added = false; if (component) { if (this.componentTypes == null || (Util.indexOf(this.componentTypes, component.CLASS_NAME) > -1)) { if (index != null && (index < this.components.length)) { var components1 = this.components.slice(0, index); var components2 = this.components.slice(index, this.components.length); components1.push(component); this.components = components1.concat(components2); } else { this.components.push(component); } component.parent = this; this.clearBounds(); added = true; } } return added; } /** * @function GeometryCollection.prototype.removeComponents * @description 清除几何对象。 * @param {Array.} components - 需要清除的几何对象。 * @returns {boolean} 元素是否被删除。 */ removeComponents(components) { var removed = false; if (!(Util.isArray(components))) { components = [components]; } for (var i = components.length - 1; i >= 0; --i) { removed = this.removeComponent(components[i]) || removed; } return removed; } /** * @function GeometryCollection.prototype.removeComponent * @description 从集合中移除几何对象。 * @param {Geometry} component - 要移除的几何对象。 * @returns {boolean} 几何对象是否移除成功。 */ removeComponent(component) { Util.removeItem(this.components, component); // clearBounds() so that it gets recalculated on the next call // to this.getBounds(); this.clearBounds(); return true; } /** * @function GeometryCollection.prototype.getArea * @description 计算几何对象的面积。注意,这个方法在 {@link GeometryPolygon} 类中需要重写。 * @returns {number} 几何图形的面积,是几何对象中所有组成部分的面积之和。 */ getArea() { var area = 0.0; for (var i = 0, len = this.components.length; i < len; i++) { area += this.components[i].getArea(); } return area; } /** * @function GeometryCollection.prototype.equals * @description 判断两个几何图形是否相等。如果所有的 components 具有相同的坐标,则认为是相等的。 * @param {Geometry} geometry - 需要判断的几何图形。 * @returns {boolean} 输入的几何图形与当前几何图形是否相等。 */ equals(geometry) { var equivalent = true; if (!geometry || !geometry.CLASS_NAME || (this.CLASS_NAME !== geometry.CLASS_NAME)) { equivalent = false; } else if (!(Util.isArray(geometry.components)) || (geometry.components.length !== this.components.length)) { equivalent = false; } else { for (var i = 0, len = this.components.length; i < len; ++i) { if (!this.components[i].equals(geometry.components[i])) { equivalent = false; break; } } } return equivalent; } /** * @function GeometryCollection.prototype.getVertices * @description 返回几何对象的所有结点的列表。 * @param {boolean} [nodes] - 对于线来说,仅仅返回作为端点的顶点,如果设为 false,则返回非端点的顶点,如果没有设置此参数,则返回所有顶点。 * @returns {Array} 几何对象的顶点列表。 */ getVertices(nodes) { var vertices = []; for (var i = 0, len = this.components.length; i < len; ++i) { Array.prototype.push.apply( vertices, this.components[i].getVertices(nodes) ); } return vertices; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/MultiPoint.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryMultiPoint * @aliasclass Geometry.MultiPoint * @deprecatedclass SuperMap.Geometry.MultiPoint * @classdesc 几何对象多点类。 * @category BaseTypes Geometry * @extends GeometryCollection * @param {Array.} components - 点对象数组。 * @example * var point1 = new GeometryPoint(5,6); * var poine2 = new GeometryMultiPoint(7,8); * var multiPoint = new MultiPoint([point1,point2]); * @usage */ class MultiPoint extends Collection { constructor(components) { super(components); /** * @member {Array.} [GeometryMultiPoint.prototype.componentTypes=["SuperMap.Geometry.Point"]] * @description components 存储的几何对象所支持的几何类型数组。 * @readonly */ this.componentTypes = ["SuperMap.Geometry.Point"]; this.CLASS_NAME = "SuperMap.Geometry.MultiPoint"; this.geometryType = "MultiPoint"; } /** * @function GeometryMultiPoint.prototype.addPoint * @description 添加点,封装了 {@link GeometryCollection|GeometryCollection.addComponent} 方法。 * @param {GeometryPoint} point - 添加的点。 * @param {number} [index] - 下标。 */ addPoint(point, index) { this.addComponent(point, index); } /** * @function GeometryMultiPoint.prototype.removePoint * @description 移除点,封装了 {@link GeometryCollection|GeometryCollection.removeComponent} 方法。 * @param {GeometryPoint} point - 移除的点对象。 */ removePoint(point) { this.removeComponent(point); } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/Curve.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryCurve * @aliasclass Geometry.Curve * @deprecatedclass SuperMap.Geometry.Curve * @classdesc 几何对象曲线类。 * @category BaseTypes Geometry * @extends GeometryMultiPoint * @param {Array.} components - 几何对象数组。 * @example * var point1 = new GeometryPoint(10,20); * var point2 = new GeometryPoint(30,40); * var curve = new Curve([point1,point2]); * @usage */ class Curve extends MultiPoint { constructor(components) { super(components); /** * @member {Array.} [GeometryCurve.prototype.componentTypes=["SuperMap.Geometry.Point", "SuperMap.PointWithMeasure"]] * @description components 存储的几何对象所支持的几何类型数组。 * @readonly */ this.componentTypes = ["SuperMap.Geometry.Point", "SuperMap.PointWithMeasure"]; this.CLASS_NAME = "SuperMap.Geometry.Curve"; this.geometryType = "Curve"; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/Point.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryPoint * @aliasclass Geometry.Point * @deprecatedclass SuperMap.Geometry.Point * @classdesc 点几何对象类。 * @category BaseTypes Geometry * @extends {Geometry} * @param {number} x - x 坐标。 * @param {number} y - y 坐标。 * @param {string} [type = 'Point'] - 点的类型。 * @param {number} [tag] - 额外的属性,比如插值分析中的 Z 值。 * @example * var point = new GeometryPoint(-111.04, 45.68); * @usage */ class Point extends Geometry_Geometry { constructor(x, y, type, tag) { super(x, y, type, tag); /** * @member {number} GeometryPoint.prototype.x * @description 横坐标。 */ this.x = parseFloat(x); /** * @member {number} GeometryPoint.prototype.y * @description 纵坐标。 */ this.y = parseFloat(y); /** * @member {string} GeometryPoint.prototype.tag * @description 用来存储额外的属性,比如插值分析中的 Z 值。 */ this.tag = (tag || tag == 0) ? parseFloat(tag) : null; /** * @member {string} GeometryPoint.prototype.type * @description 用来存储点的类型。 */ this.type = type || "Point"; this.CLASS_NAME = "SuperMap.Geometry.Point"; this.geometryType = "Point"; } /** * @function GeometryPoint.prototype.clone * @description 克隆点对象。 * @returns {GeometryPoint} 克隆后的点对象。 */ clone(obj) { if (obj == null) { obj = new Point(this.x, this.y); } // catch any randomly tagged-on properties Util.applyDefaults(obj, this); return obj; } /** * @function GeometryPoint.prototype.calculateBounds * @description 计算点对象的范围。 */ calculateBounds() { this.bounds = new Bounds(this.x, this.y, this.x, this.y); } /** * @function GeometryPoint.prototype.equals * @description 判断两个点对象是否相等。如果两个点对象具有相同的坐标,则认为是相等的。 * @example * var point= new GeometryPoint(0,0); * var point1={x:0,y:0}; * var result= point.equals(point1); * @param {GeometryPoint} geom - 需要判断的点对象。 * @returns {boolean} 两个点对象是否相等(true 为相等,false 为不等)。 */ equals(geom) { var equals = false; if (geom != null) { equals = ((this.x === geom.x && this.y === geom.y) || (isNaN(this.x) && isNaN(this.y) && isNaN(geom.x) && isNaN(geom.y))); } return equals; } /** * @function GeometryPoint.prototype.move * @description 沿着 x、y 轴的正方向上按照给定的位移移动点对象,move 不仅改变了几何对象的位置并且清理了边界缓存。 * @param {number} x - x 轴正方向上的偏移量。 * @param {number} y - y 轴正方向上偏移量。 */ move(x, y) { this.x = this.x + x; this.y = this.y + y; this.clearBounds(); } /** * @function GeometryPoint.prototype.toShortString * @description 将 x/y 坐标转换成简单字符串。 * @returns {string} 字符串代表点对象。(ex. "5, 42") */ toShortString() { return (this.x + ", " + this.y); } /** * @function GeometryPoint.prototype.destroy * @description 释放点对象的资源。 */ destroy() { this.x = null; this.y = null; this.tag = null; super.destroy(); } /** * @function GeometryPoint.prototype.getVertices * @description 获取几何图形所有顶点的列表。 * @returns {Array} 几何图形的顶点列表。 */ getVertices() { return [this]; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/LineString.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryLineString * @aliasclass Geometry.LineString * @deprecatedclass SuperMap.Geometry.LineString * @classdesc 几何对象线串类。 * @category BaseTypes Geometry * @param {Array.} points - 用来生成线串的点数组。 * @extends GeometryCurve * @example * var points = [new GeometryPoint(4933.319287022352, -3337.3849141502124), * new GeometryPoint(4960.9674060199022, -3349.3316322355736), * new GeometryPoint(5006.0235999418364, -3358.8890067038628), * new GeometryPoint(5075.3145648369318, -3378.0037556404409), * new GeometryPoint(5305.19551436013, -3376.9669111768926)], * var roadLine = new GeometryLineString(points); * @usage */ class LineString extends Curve { constructor(points) { super(points); this.CLASS_NAME = "SuperMap.Geometry.LineString"; this.geometryType = "LineString"; } /** * @function GeometryLineString.prototype.removeComponent * @description 只有在线串上有三个或更多的点的时候,才会允许移除点(否则结果将会是单一的点)。 * @param {GeometryPoint} point - 将被删除的点。 * @returns {boolean} 删除的点。 */ removeComponent(point) { // eslint-disable-line no-unused-vars var removed = this.components && (this.components.length > 2); if (removed) { super.removeComponent.apply(this, arguments); } return removed; } /** * @function GeometryLineString.prototype.getSortedSegments * @description 获取升序排列的点坐标对象数组。 * @returns {Array} 升序排列的点坐标对象数组。 */ getSortedSegments() { var numSeg = this.components.length - 1; var segments = new Array(numSeg), point1, point2; for (var i = 0; i < numSeg; ++i) { point1 = this.components[i]; point2 = this.components[i + 1]; if (point1.x < point2.x) { segments[i] = { x1: point1.x, y1: point1.y, x2: point2.x, y2: point2.y }; } else { segments[i] = { x1: point2.x, y1: point2.y, x2: point1.x, y2: point1.y }; } } // more efficient to define this somewhere static function byX1(seg1, seg2) { return seg1.x1 - seg2.x1; } return segments.sort(byX1); } /** * @function GeometryLineString.prototype.getVertices * @description 返回几何图形的所有顶点的列表。 * @param {boolean} [nodes] - 对于线来说,仅仅返回作为端点的顶点,如果设为 false,则返回非端点的顶点,如果没有设置此参数,则返回所有顶点。 * @returns {Array} 几何图形的顶点列表。 */ getVertices(nodes) { var vertices; if (nodes === true) { vertices = [ this.components[0], this.components[this.components.length - 1] ]; } else if (nodes === false) { vertices = this.components.slice(1, this.components.length - 1); } else { vertices = this.components.slice(); } return vertices; } /** * @function GeometryLineString.calculateCircle * @description 三点画圆弧。 * @param {Array.} points - 传入的待计算的初始点串。 * @returns {Array.} 计算出相应的圆弧控制点。 * @example * var points = []; * points.push(new GeometryPoint(-50,30)); * points.push(new GeometryPoint(-30,50)); * points.push(new GeometryPoint(2,60)); * var circle = GeometryLineString.calculateCircle(points); */ static calculateCircle(points) { if (points.length < 3) { return points } var centerPoint = {}, p1 = points[0], p2 = points[1], p3 = points[2]; var R = 0, dStep = 0, direc = true, dRotation = 0, dRotationBegin = 0, dRotationAngle = 0, nSegmentCount = 72, circlePoints = []; var KTan13 = (p3.y - p1.y) / (p3.x - p1.x); var B13 = p3.y - KTan13 * p3.x; if ((((p3.x != p1.x) && (p3.y != p1.y)) && (p2.y == KTan13 * p2.x + B13)) || ((p3.x == p1.x) && (p2.x == p1.x)) || ((p3.y == p1.y) && (p2.y == p1.y)) || ((p3.x == p1.x) && (p3.y == p1.y)) || ((p3.x == p2.x) && (p3.y == p2.y)) || ((p1.x == p2.x) && (p1.y == p2.y))) { circlePoints.push(p1); circlePoints.push(p2); circlePoints.push(p3); } else { var D = ((p2.x * p2.x + p2.y * p2.y) - (p1.x * p1.x + p1.y * p1.y)) * (2 * (p3.y - p1.y)) - ((p3.x * p3.x + p3.y * p3.y) - (p1.x * p1.x + p1.y * p1.y)) * (2 * (p2.y - p1.y)); var E = (2 * (p2.x - p1.x)) * ((p3.x * p3.x + p3.y * p3.y) - (p1.x * p1.x + p1.y * p1.y)) - (2 * (p3.x - p1.x)) * ((p2.x * p2.x + p2.y * p2.y) - (p1.x * p1.x + p1.y * p1.y)); var F = 4 * ((p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)); centerPoint.x = D / F; centerPoint.y = E / F; R = Math.sqrt((p1.x - centerPoint.x) * (p1.x - centerPoint.x) + (p1.y - centerPoint.y) * (p1.y - centerPoint.y)); var dis = (p1.x - p3.x) * (p1.x - p3.x) + (p1.y - p3.y) * (p1.y - p3.y); var cons = (2 * R * R - dis) / (2 * R * R); cons = cons >= 1 ? 1 : cons; cons = cons <= -1 ? -1 : cons; dRotationAngle = Math.acos(cons) * 180 / Math.PI; if (p3.x == p1.x) { dRotationAngle = ((centerPoint.x > p1.x && p2.x > p1.x) || (centerPoint.x < p1.x && p2.x < p1.x)) ? (360 - dRotationAngle) : dRotationAngle; } else { dRotationAngle = ((centerPoint.y > (KTan13 * centerPoint.x + B13) && p2.y > (KTan13 * p2.x + B13)) || (centerPoint.y < (KTan13 * centerPoint.x + B13) && p2.y < (KTan13 * p2.x + B13))) ? (360 - dRotationAngle) : dRotationAngle; } dStep = dRotationAngle / 72; if (p3.y != p1.y) { if (p3.x == p1.x) { if (p3.y > p1.y) { if (p2.x < p1.x) { direc = false; } } else { if (p2.x > p1.x) { direc = false; } } } else if (p3.x < p1.x) { if (p2.y < KTan13 * p2.x + B13) { direc = false; } } else { if (p2.y > KTan13 * p2.x + B13) { direc = false; } } } else { if (p3.x > p1.x) { if (p2.y > p1.y) { direc = false; } } else { if (p2.y < p1.y) { direc = false; } } } var K10 = (p1.y - centerPoint.y) / (p1.x - centerPoint.x); var atan10 = K10 >= 0 ? Math.atan(K10) * 180 / Math.PI : Math.abs(Math.atan(K10) * 180 / Math.PI) + 90; var CY = Math.abs(centerPoint.y); if ((p1.y == CY) && (CY == p3.y)) { if (p1.x < p3.x) { atan10 = atan10 + 180; } } var newPY = p1.y - centerPoint.y; circlePoints.push(p1); for (var i = 1; i < nSegmentCount; i++) { dRotation = dStep * i; dRotationBegin = atan10; if (direc) { if (newPY >= 0) { if (K10 >= 0) { dRotationBegin = dRotationBegin + dRotation; } else { dRotationBegin = (180 - (dRotationBegin - 90)) + dRotation; } } else { if (K10 > 0) { dRotationBegin = (dRotationBegin - 180) + dRotation; } else { dRotationBegin = (90 - dRotationBegin) + dRotation; } } } else { if (newPY >= 0) { if (K10 >= 0) { dRotationBegin = dRotationBegin - dRotation; } else { dRotationBegin = (180 - (dRotationBegin - 90)) - dRotation; } } else { if (K10 >= 0) { dRotationBegin = (dRotationBegin - 180) - dRotation; } else { dRotationBegin = (90 - dRotationBegin) - dRotation; } } } dRotationBegin = dRotationBegin * Math.PI / 180; var x = centerPoint.x + R * Math.cos(dRotationBegin); var y = centerPoint.y + R * Math.sin(dRotationBegin); circlePoints.push(new Point(x, y)); } circlePoints.push(p3); } return circlePoints; } /** * @function GeometryLineString.createLineEPS * @description 根据点的类型画出不同类型的曲线。 * 点的类型有三种:LTypeArc,LTypeCurve,NONE。 * @param {Array.} points - 传入的待计算的初始点串。 * @returns {Array.} 计算出相应的 lineEPS 控制点。 * @example * var points = []; * points.push(new GeometryPoint(-50,30)); * points.push(new GeometryPoint(-30,50,"LTypeArc")); * points.push(new GeometryPoint(2,60)); * points.push(new GeometryPoint(8,20)); * var lineEPS = GeometryLineString.createLineEPS(points); */ static createLineEPS(points) { var list = [], len = points.length; if (len < 2) { return points; } for (var i = 0; i < len;) { var type = points[i].type; if (type == 'LTypeArc') { var listObj = LineString.createLineArc(list, i, len, points); list = listObj[0]; i = listObj[1]; } else { list.push(points[i]); i++; } } return list; } static createLineArc(list, i, len, points) { if (i == 0) { let bezierPtsObj = LineString.addPointEPS(points, i, len, 'LTypeArc'); Array.prototype.push.apply(list, bezierPtsObj[0]); i = bezierPtsObj[1] + 1; } else if (i == len - 1) { var bezierP = [points[i - 1], points[i]], bezierPts = LineString.calculateCircle(bezierP); Array.prototype.push.apply(list, bezierPts); i++; } else { let bezierPtsObj = LineString.addPointEPS(points, i, len, 'LTypeArc'); list.pop(); Array.prototype.push.apply(list, bezierPtsObj[0]); i = bezierPtsObj[1] + 1; } return [list, i]; } static addPointEPS(points, i, len, type) { var bezierP = [], j = i + 1; if (i == 0) { Array.prototype.push.apply(bezierP, [points[i], points[i + 1]]); } else if (i == len - 1) { Array.prototype.push.apply(bezierP, [points[i - 1], points[i]]); } else { Array.prototype.push.apply(bezierP, [points[i - 1], points[i], points[i + 1]]); } var bezierPts; if (type == 'LTypeCurve') { bezierPts = LineString.calculatePointsFBZN(bezierP); } else if (type == 'LTypeArc') { bezierPts = LineString.calculateCircle(bezierP); } return [bezierPts, j]; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/GeoText.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryGeoText * @aliasclass Geometry.GeoText * @deprecatedclass SuperMap.Geometry.GeoText * @classdesc 文本标签类。 * @category BaseTypes Geometry * @extends {Geometry} * @param {number} x - x 坐标。 * @param {number} y - y 坐标。 * @param {string} text - 标签中的文本内容。 * @usage */ class GeoText extends Geometry_Geometry { constructor(x, y, text) { super(x, y, text); /** * @member {number} GeometryGeoText.prototype.x * @description 横坐标。 */ this.x = parseFloat(x); /** * @member {number} GeometryGeoText.prototype.y * @description 纵坐标。 */ this.y = parseFloat(y); /** * @member {string} GeometryGeoText.prototype.text * @description 标签中的文本内容。 */ this.text = text.toString(); /** * @member {Object} GeometryGeoText.prototype.bsInfo * @description 标签范围的基础信息。 * @property {number} w - bounds 的宽度。 * @property {number} h - bounds 的高度。 */ this.bsInfo = { "h": null, "w": null }; this.element = document.createElement('span'); this.CLASS_NAME = "SuperMap.Geometry.GeoText"; this.geometryType = "GeoText"; } /** * @function GeometryGeoText.prototype.destroy * @description 销毁文本标签类。 */ destroy() { super.destroy(); this.x = null; this.y = null; this.text = null; } /** * @function GeometryGeoText.prototype.getCentroid * @description 获取标签对象的质心。 * @returns {GeometryPoint} 标签对象的质心。 */ getCentroid() { return new Point(this.x, this.y); } /** * @function GeometryGeoText.prototype.clone * @description 克隆标签对象。 * @returns {GeometryGeoText} 克隆后的标签对象。 */ clone(obj) { if (obj == null) { obj = new GeoText(this.x, this.y, this.text); } Util.applyDefaults(obj, this); return obj; } /** * @function GeometryGeoText.prototype.calculateBounds * @description 计算标签对象的范围。 */ calculateBounds() { this.bounds = new Bounds(this.x, this.y, this.x, this.y); } /** * @function GeometryGeoText.prototype.getLabelPxBoundsByLabel * @description 根据绘制好的标签获取文字标签的像素范围,参数的单位是像素;此方法相对于 getLabelPxBoundsByText 效率较低,但支持所有格式的文本。 * @param {Object} locationPixel - 标签的位置点,该对象含有属性 x(横坐标),属性 y(纵坐标)。 * @param {string} labelWidth - 标签的宽度,如:“90px”。 * @param {string} labelHeight - 标签的高度。 * @param {Object} style - 标签的 style。 * @returns {Bounds} 标签的像素范围。 */ getLabelPxBoundsByLabel(locationPixel, labelWidth, labelHeight, style) { var labelPxBounds, left, bottom, top, right; var locationPx = Util.cloneObject(locationPixel); //计算文本行数 var theText = style.label || this.text; var textRows = theText.split('\n'); var laberRows = textRows.length; //处理文字对齐 labelWidth = parseFloat(labelWidth); labelHeight = parseFloat(labelHeight); if (laberRows > 1) { labelHeight = parseFloat(labelHeight) * laberRows; } if (style.labelAlign && style.labelAlign !== "cm") { switch (style.labelAlign) { case "lt": locationPx.x += labelWidth / 2; locationPx.y += labelHeight / 2; break; case "lm": locationPx.x += labelWidth / 2; break; case "lb": locationPx.x += labelWidth / 2; locationPx.y -= labelHeight / 2; break; case "ct": locationPx.y += labelHeight / 2; break; case "cb": locationPx.y -= labelHeight / 2; break; case "rt": locationPx.x -= labelWidth / 2; locationPx.y += labelHeight / 2; break; case "rm": locationPx.x -= labelWidth / 2; break; case "rb": locationPx.x -= labelWidth / 2; locationPx.y -= labelHeight / 2; break; default: break; } } this.bsInfo.h = labelHeight; this.bsInfo.w = labelWidth; //bounds的四边 left = locationPx.x - parseFloat(labelWidth) / 2; bottom = locationPx.y + parseFloat(labelHeight) / 2; right = locationPx.x + parseFloat(labelWidth) / 2; top = locationPx.y - parseFloat(labelHeight) / 2; labelPxBounds = new Bounds(left, bottom, right, top); return labelPxBounds; } /** * @function GeometryGeoText.prototype.getLabelPxBoundsByText * @description 根据文本内容获取文字标签的像素范围。 * @param {Object} locationPixel - 标签的位置点,该对象含有属性 x(横坐标),属性 y(纵坐标)。 * @param {Object} style - 标签的样式。 * @returns {Bounds} 标签的像素范围。 */ getLabelPxBoundsByText(locationPixel, style) { var labelPxBounds, left, bottom, top, right; var labelSize = this.getLabelPxSize(style); var locationPx = Util.cloneObject(locationPixel); //处理文字对齐 if (style.labelAlign && style.labelAlign !== "cm") { switch (style.labelAlign) { case "lt": locationPx.x += labelSize.w / 2; locationPx.y += labelSize.h / 2; break; case "lm": locationPx.x += labelSize.w / 2; break; case "lb": locationPx.x += labelSize.w / 2; locationPx.y -= labelSize.h / 2; break; case "ct": locationPx.y += labelSize.h / 2; break; case "cb": locationPx.y -= labelSize.h / 2; break; case "rt": locationPx.x -= labelSize.w / 2; locationPx.y += labelSize.h / 2; break; case "rm": locationPx.x -= labelSize.w / 2; break; case "rb": locationPx.x -= labelSize.w / 2; locationPx.y -= labelSize.h / 2; break; default: break; } } this.bsInfo.h = labelSize.h; this.bsInfo.w = labelSize.w; left = locationPx.x - labelSize.w / 2; bottom = locationPx.y + labelSize.h / 2; //处理斜体字 if (style.fontStyle && style.fontStyle === "italic") { right = locationPx.x + labelSize.w / 2 + parseInt(parseFloat(style.fontSize) / 2); } else { right = locationPx.x + labelSize.w / 2; } top = locationPx.y - labelSize.h / 2; labelPxBounds = new Bounds(left, bottom, right, top); return labelPxBounds; } /** * @function GeometryGeoText.prototype.getLabelPxSize * @description 获取 label 的像素大小。 * @param {Object} style - 标签样式。 * @returns {Object} 标签大小对象,属性 w 表示标签的宽度,属性 h 表示标签的高度。 */ getLabelPxSize(style) { var text,//文本内容 fontSize,//字体大小 spacing = 1,//两个字符间的间距(单位:px) lineSpacing = 0.2, bgstrokeWidth = parseFloat(style.strokeWidth);//标签背景框边框的宽度 text = style.label || this.text; if (style.fontSize) { fontSize = parseFloat(style.fontSize); } else { fontSize = parseFloat("12px"); } //标签宽高 var labelW, labelH; var textRows = text.split('\n'); var numRows = textRows.length; if (numRows > 1) { labelH = fontSize * numRows + numRows + bgstrokeWidth + lineSpacing * fontSize; } else { labelH = fontSize + bgstrokeWidth + lineSpacing * fontSize + 1; } //取最大宽度 labelW = 0; if (this.labelWTmp && labelW < this.labelWTmp) { labelW = this.labelWTmp; } for (var i = 0; i < numRows; i++) { var textCharC = this.getTextCount(textRows[i]); var labelWTmp = this.labelWTmp = Util.getTextBounds(style, textRows[i], this.element).textWidth + textCharC.textC * spacing + bgstrokeWidth; if (labelW < labelWTmp) { labelW = labelWTmp; } } var labelSize = new Object(); //标签大小 labelSize.h = labelH; labelSize.w = labelW; return labelSize; } /** * @function GeometryGeoText.prototype.getTextCount * @description 获取 text 中的字符个数。 * @param {string} text - 字符串。 * @returns {Object} 字符个数统计结果,属性 cnC 表示中文字符个数,属性 enC 表示英文字符个数,属性 textC 表示字符总个数。 */ getTextCount(text) { var textCharCount = {}; var cnCount = 0; var enCount = 0; for (var i = 0; i < text.length; i++) { if (text.charCodeAt(i) > 255) { //遍历判断字符串中每个字符的Unicode码,大于255则为中文 cnCount++; } else { enCount++; } } //中午字符个数 textCharCount.cnC = cnCount; //英文字符个数 textCharCount.enC = enCount; //字符总个数 textCharCount.textC = text.length; return textCharCount; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/LinearRing.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryLinearRing * @aliasclass Geometry.LinearRing * @deprecatedclass SuperMap.Geometry.LinearRing * @classdesc 几何对象线环类,是一个特殊的封闭的线串,在每次 addPoint/removePoint 之后会通过添加一个点(此点是复制的第一个点得到的) * 作为最后的一个点来自动关闭线环。 * @category BaseTypes Geometry * @extends GeometryLineString * @param {Array.} points - 组成线性环的点。 * @example * var points = [new GeometryPoint(4933.319287022352, -3337.3849141502124), * new GeometryPoint(4960.9674060199022, -3349.3316322355736), * new GeometryPoint(5006.0235999418364, -3358.8890067038628), * new GeometryPoint(5075.3145648369318, -3378.0037556404409), * new GeometryPoint(5305.19551436013, -3376.9669111768926)], * var linearRing = new GeometryLinearRing(points); * @usage */ class LinearRing extends LineString { constructor(points) { super(points); /** * @member {Array.} [GeometryLinearRing.prototype.componentTypes=["SuperMap.Geometry.Point"]] * @description components 存储的几何对象所支持的几何类型数组,为空表示类型不受限制。 * @readonly */ this.componentTypes = ["SuperMap.Geometry.Point"]; this.CLASS_NAME = "SuperMap.Geometry.LinearRing"; this.geometryType = "LinearRing"; } /** * @function GeometryLinearRing.prototype.addComponent * @description 添加一个点到几何图形数组中,如果这个点将要被添加到组件数组的末端,并且与数组中已经存在的最后一个点相同, * 重复的点是不能被添加的。这将影响未关闭环的关闭。 * 这个方法可以通过将非空索引(组件数组的下标)作为第二个参数重写。 * @param {GeometryPoint} point - 点对象。 * @param {number} [index] - 插入组件数组的下标。 * @returns {boolean} 点对象是否添加成功。 */ addComponent(point, index) { var added = false; //remove last point var lastPoint = this.components.pop(); // given an index, add the point // without an index only add non-duplicate points if (index != null || !point.equals(lastPoint)) { added = super.addComponent.apply(this, arguments); } //append copy of first point var firstPoint = this.components[0]; super.addComponent.apply(this, [firstPoint]); return added; } /** * @function GeometryLinearRing.prototype.removeComponent * @description 从几何组件中删除一个点。 * @param {GeometryPoint} point - 点对象。 * @returns {boolean} 点对象是否删除。 */ removeComponent(point) { // eslint-disable-line no-unused-vars var removed = this.components && (this.components.length > 3); if (removed) { //remove last point this.components.pop(); //remove our point super.removeComponent.apply(this, arguments); //append copy of first point var firstPoint = this.components[0]; super.addComponent.apply(this, [firstPoint]); } return removed; } /** * @function GeometryLinearRing.prototype.getArea * @description 获得当前几何对象区域大小,如果是沿顺时针方向的环则是正值,否则为负值。 * @returns {number} 环的面积。 */ getArea() { var area = 0.0; if (this.components && (this.components.length > 2)) { var sum = 0.0; for (var i = 0, len = this.components.length; i < len - 1; i++) { var b = this.components[i]; var c = this.components[i + 1]; sum += (b.x + c.x) * (c.y - b.y); } area = -sum / 2.0; } return area; } /** * @function GeometryLinearRing.prototype.getVertices * @description 返回几何图形的所有点的列表。 * @param {boolean} [nodes] - 对于线来说,仅仅返回作为端点的顶点,如果设为 false ,则返回非端点的顶点,如果没有设置此参数,则返回所有顶点。 * @returns {Array} 几何对象所有点的列表。 */ getVertices(nodes) { return (nodes === true) ? [] : this.components.slice(0, this.components.length - 1); } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/MultiLineString.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryMultiLineString * @aliasclass Geometry.MultiLineString * @deprecatedclass SuperMap.Geometry.MultiLineString * @classdesc 几何对象多线类。 * @category BaseTypes Geometry * @extends GeometryCollection * @param {Array.} components - GeometryLineString 数组。 * @example * var multi = new GeometryMultiLineString([ * new GeometryLineString([ * new GeometryPoint(1, 0), * new GeometryPoint(0, 1) * ]) * ]); * @usage */ class MultiLineString extends Collection { constructor(components) { super(components); /** * @member {Array.} [GeometryMultiLineString.prototype.componentTypes=["SuperMap.Geometry.LineString"]] * @description components 存储的几何对象所支持的几何类型数组。 * @readonly */ this.componentTypes = ["SuperMap.Geometry.LineString"]; this.CLASS_NAME = "SuperMap.Geometry.MultiLineString"; this.geometryType = "MultiLineString"; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/MultiPolygon.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryMultiPolygon * @aliasclass Geometry.MultiPolygon * @deprecatedclass SuperMap.Geometry.MultiPolygon * @classdesc 几何对象多多边形类。 * @category BaseTypes Geometry * @extends GeometryCollection * @param {Array.} components - 形成 GeometryMultiPolygon 的多边形数组。 * @example * var points1 = [new GeometryPoint(10,10),new GeometryPoint(0,0)]; * var points2 = [new GeometryPoint(10,10),new GeometryPoint(0,0),new GeometryPoint(3,3),new GeometryPoint(10,10)]; * * var linearRing1 = new GeometryLinearRing(points1); * var linearRing2 = new GeometryLinearRing(points2); * * var polygon1 = new GeometryPolygon([linearRing1]); * var polygon2 = new GeometryPolygon([linearRing2]); * * var multiPolygon1 = new GeometryMultiPolygon([polygon1,polygon2]); * @usage */ class MultiPolygon extends Collection { constructor(components) { super(components); /** * @member {Array.} [GeometryMultiPolygon.prototype.componentTypes=["SuperMap.Geometry.Polygon"]] * @description components 存储的几何对象所支持的几何类型数组。 * @readonly */ this.componentTypes = ["SuperMap.Geometry.Polygon"]; this.CLASS_NAME = "SuperMap.Geometry.MultiPolygon"; this.geometryType = "MultiPolygon"; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/Polygon.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryPolygon * @aliasclass Geometry.Polygon * @deprecatedclass SuperMap.Geometry.Polygon * @classdesc 多边形几何对象类。 * @category BaseTypes Geometry * @extends GeometryCollection * @param {Array.} components - 多边形的线环数组。 * @example * var points =[new GeometryPoint(0,4010338), * new GeometryPoint(1063524,4010338), * new GeometryPoint(1063524,3150322), * new GeometryPoint(0,3150322) * ], * var linearRings = new GeometryLinearRing(points), * var region = new GeometryPolygon([linearRings]); * @usage */ class Polygon extends Collection { constructor(components) { super(components); /** * @member {Array.} [GeometryPolygon.prototype.componentTypes=["SuperMap.Geometry.LinearRing"]] * @description components 存储的几何对象所支持的几何类型数组。 * @readonly */ this.componentTypes = ["SuperMap.Geometry.LinearRing"]; this.CLASS_NAME = "SuperMap.Geometry.Polygon"; this.geometryType = "Polygon"; } /** * @function GeometryMultiPoint.prototype.getArea * @description 获得区域面积,从区域的外部口径减去计此区域内部口径算所得的面积。 * @returns {number} 几何对象的面积。 */ getArea() { var area = 0.0; if (this.components && (this.components.length > 0)) { area += Math.abs(this.components[0].getArea()); for (var i = 1, len = this.components.length; i < len; i++) { area -= Math.abs(this.components[i].getArea()); } } return area; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/Rectangle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryRectangle * @aliasclass Geometry.Rectangle * @deprecatedclass SuperMap.Geometry.Rectangle * @classdesc 矩形几何对象类。 * @category BaseTypes Geometry * @param {number} x - 矩形左下角点的横坐标。 * @param {number} y - 矩形左下角点的纵坐标。 * @param {number} width - 矩形的宽度。 * @param {number} height - 矩形的高度。 * @extends {Geometry} * @example * //x 为矩形左下角点的横坐标;y 为矩形左下角点的纵坐标;w 为矩形的宽度;h 为矩形的高度 * var x = 1; * var y = 2; * var w = 10; * var h = 20; * var recttangle = new GeometryRectangle(x, y, w, h); * @usage */ class Rectangle extends Geometry_Geometry { constructor(x, y, width, height) { super(x, y, width, height); /** * @member {number} GeometryRectangle.prototype.x * @description 矩形左下角点的横坐标。 */ this.x = x; /** * @member {number} GeometryRectangle.prototype.y * @description 矩形左下角点的纵坐标。 */ this.y = y; /** * @member {number} GeometryRectangle.prototype.width * @description 矩形的宽度。 */ this.width = width; /** * @member {number} GeometryRectangle.prototype.height * @description 矩形的高度。 */ this.height = height; this.CLASS_NAME = "SuperMap.Geometry.Rectangle"; this.geometryType = "Rectangle"; } /** * @function GeometryRectangle.prototype.calculateBounds * @description 计算出此矩形对象的 bounds。 */ calculateBounds() { this.bounds = new Bounds(this.x, this.y, this.x + this.width, this.y + this.height); } /** * @function GeometryRectangle.prototype.getArea * @description 获取矩形对象的面积。 * @returns {number} 矩形对象面积。 */ getArea() { var area = this.width * this.height; return area; } } ;// CONCATENATED MODULE: ./src/common/commontypes/geometry/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/commontypes/Credential.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Credential * @deprecatedclass SuperMap.Credential * @category Security * @classdesc SuperMap 的安全证书类,其中包括 token 等安全验证信息。
* 需要使用用户名和密码在:"http://localhost:8090/iserver/services/security/tokens" 下申请 value。
* 获得形如:"2OMwGmcNlrP2ixqv1Mk4BuQMybOGfLOrljruX6VcYMDQKc58Sl9nMHsqQaqeBx44jRvKSjkmpZKK1L596y7skQ.." 的 value。
* 目前支持的功能包括:地图服务、专题图、量算、查询、公交换乘、空间分析、网络分析,不支持轮询功能。
* @param {string} value - 访问受安全限制的服务时用于通过安全认证的验证信息。 * @param {string} [name='token'] - 验证信息前缀,name=value 部分的 name 部分。 * @example * var pixcel = new Credential("valueString","token"); * pixcel.destroy(); * @usage */ class Credential { constructor(value, name) { /** * @member {string} Credential.prototype.value * @description 访问受安全限制的服务时用于通过安全认证的验证信息。 */ this.value = value ? value : ""; /** * @member {string} [Credential.prototype.name='token'] * @description 验证信息前缀,name=value 部分的 name 部分。 */ this.name = name ? name : "token"; this.CLASS_NAME = "SuperMap.Credential"; } /** * @function Credential.prototype.getUrlParameters * @description 获取 name=value 的表达式。 * @example * var credential = new Credential("valueString","token"); * //这里 str = "token=valueString"; * var str = credential.getUrlParameters(); * @returns {string} 安全信息组成的 url 片段。 */ getUrlParameters() { //当需要其他安全信息的时候,则需要return this.name + "=" + this.value + "&" + "...";的形式添加。 return this.name + "=" + this.value; } /** * @function Credential.prototype.getValue * @description 获取 value。 * @example * var credential = new Credential("2OMwGmcNlrP2ixqv1Mk4BuQMybOGfLOrljruX6VcYMDQKc58Sl9nMHsqQaqeBx44jRvKSjkmpZKK1L596y7skQ..","token"); * //这里 str = "2OMwGmcNlrP2ixqv1Mk4BuQMybOGfLOrljruX6VcYMDQKc58Sl9nMHsqQaqeBx44jRvKSjkmpZKK1L596y7skQ.."; * var str = credential.getValue(); * @returns {string} value 字符串,在 iServer 服务下该 value 值即为 token 值。 */ getValue() { return this.value; } /** * * @function Credential.prototype.destroy * @description 销毁此对象。销毁后此对象的所有属性为 null,而不是初始值。 * @example * var credential = new Credential("valueString","token"); * credential.destroy(); */ destroy() { this.value = null; this.name = null; } } /** * @member {Credential} Credential.CREDENTIAL * @description 这个对象保存一个安全类的实例,在服务端需要安全验证的时候必须进行设置。 * @example * 代码实例: * // 当iServer启用服务安全的时候,下边的代码是必须的。安全证书类能够接收一个value和一个name参数。 * var value = "(以iServer为例,这里是申请的token值)"; * var name = "token"; * // 默认name参数为token,所以当使用iServer服务的时候可以不进行设置。 * Credential.CREDENTIAL = new Credential(value, name); * */ Credential.CREDENTIAL = null; ;// CONCATENATED MODULE: ./src/common/commontypes/Date.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @name Date * @namespace * @category BaseTypes Util * @description 包含 parse、toISOString 方法的实现,两个方法用来解析 RFC 3339 日期,遵循 ECMAScript 5 规范。 * @private */ var DateExt = { /** * @description 生成代表一个具体的日期字符串,该日期遵循 ISO 8601 标准(详情查看{@link http://tools.ietf.org/html/rfc3339})。 * @example * var dateString = DateExt.toISOString(new Date()); * @param {Date} date - 日期对象。 * @returns {string} 一个代表日期的字符串。(例如 "2010-08-07T16:58:23.123Z")。 */ toISOString: (function () { //标准的Date会存在toISOString方法,可以直接调用 if ("toISOString" in Date.prototype) { return function (date) { return date.toISOString(); }; } else {// 部分浏览器没有,就得自己组合,组合后的字符串规则不变 function pad(num, len) { var str = num + ""; while (str.length < len) { str = "0" + str; } return str; } return function (date) { var str; if (isNaN(date.getTime())) { // ECMA-262 says throw RangeError, Firefox returns // "Invalid Date" str = "Invalid Date"; } else { str = date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1, 2) + "-" + pad(date.getUTCDate(), 2) + "T" + pad(date.getUTCHours(), 2) + ":" + pad(date.getUTCMinutes(), 2) + ":" + pad(date.getUTCSeconds(), 2) + "." + pad(date.getUTCMilliseconds(), 3) + "Z"; } return str; }; } })(), /** * @description 从一个字符串生成一个日期对象。 * @example * var date = DateExt.parse("2010-08-07"); * @param {string} str - 日期的字符串。(例如: "2010", "2010-08", "2010-08-07", "2010-08-07T16:58:23.123Z","2010-08-07T11:58:23.123-06")。 * @returns {Date} 日期对象,如果字符串无法被解析,则返回一个无效的日期。(例如 isNaN(date.getTime()))。 */ parse: function (str) { var date; var match = str.match(/^(?:(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?)?(?:(?:T(\d{1,2}):(\d{2}):(\d{2}(?:\.\d+)?)(Z|(?:[+-]\d{1,2}(?::(\d{2}))?)))|Z)?$/); if (match && (match[1] || match[7])) { // must have at least year or time var year = parseInt(match[1], 10) || 0; var month = (parseInt(match[2], 10) - 1) || 0; var day = parseInt(match[3], 10) || 1; date = new Date(Date.UTC(year, month, day)); // optional time var type = match[7]; if (type) { var hours = parseInt(match[4], 10); var minutes = parseInt(match[5], 10); var secFrac = parseFloat(match[6]); var seconds = secFrac | 0; var milliseconds = Math.round(1000 * (secFrac - seconds)); date.setUTCHours(hours, minutes, seconds, milliseconds); // check offset if (type !== "Z") { var hoursOffset = parseInt(type, 10); var minutesOffset = parseInt(match[8], 10) || 0; var offset = -1000 * (60 * (hoursOffset * 60) + minutesOffset * 60); date = new Date(date.getTime() + offset); } } } else { date = new Date("invalid"); } return date; } }; ;// CONCATENATED MODULE: ./src/common/commontypes/Event.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @name Event * @namespace * @category BaseTypes Events * @description 事件处理函数. * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { Event } from '{npm}'; * * const result = Event.element(); * ``` */ var Event = { /** * @description 事件观察者列表。 * @type {Object} * @default false */ observers: false, /** * @description KEY_SPACE * @type {number} * @default 32 */ KEY_SPACE: 32, /** * @description KEY_BACKSPACE * @type {number} * @default 8 */ KEY_BACKSPACE: 8, /** * @description KEY_TAB * @type {number} * @default 9 */ KEY_TAB: 9, /** * @description KEY_RETURN * @type {number} * @default 13 */ KEY_RETURN: 13, /** * @description KEY_ESC * @type {number} * @default 27 */ KEY_ESC: 27, /** * @description KEY_LEFT * @type {number} * @default 37 */ KEY_LEFT: 37, /** * @description KEY_UP * @type {number} * @default 38 */ KEY_UP: 38, /** * @description KEY_RIGHT * @type {number} * @default 39 */ KEY_RIGHT: 39, /** * @description KEY_DOWN * @type {number} * @default 40 */ KEY_DOWN: 40, /** * @description KEY_DELETE * @type {number} * @default 46 */ KEY_DELETE: 46, /** * @description 监听浏览器 DOM 事件。 * @param {Event} event - Event 对象。 * @returns {HTMLElement} 触发事件的 DOM 元素。 */ element: function (event) { return event.target || event.srcElement; }, /** * @description 判断事件是否由单次触摸引起。 * @param {Event} event - Event 对象。 * @returns {boolean} 是否有且只有一个当前在与触摸表面接触的 Touch 对象。 */ isSingleTouch: function (event) { return event.touches && event.touches.length === 1; }, /** * @description 判断事件是否由多点触控引起。 * @param {Event} event - Event 对象。 * @returns {boolean} 是否存在多个当前在与触摸表面接触的 Touch 对象。 */ isMultiTouch: function (event) { return event.touches && event.touches.length > 1; }, /** * @description 确定事件是否由左键单击引起。 * @param {Event} event - Event 对象。 * @returns {boolean} 是否点击鼠标左键。 */ isLeftClick: function (event) { return (((event.which) && (event.which === 1)) || ((event.button) && (event.button === 1))); }, /** * @description 确定事件是否由鼠标右键单击引起。 * @param {Event} event - Event 对象。 * @returns {boolean} 是否点击鼠标右键。 */ isRightClick: function (event) { return (((event.which) && (event.which === 3)) || ((event.button) && (event.button === 2))); }, /** * @description 阻止事件冒泡。 * @param {Event} event - Event 对象。 * @param {boolean} allowDefault - 默认为 false,表示阻止事件的默认行为。 */ stop: function (event, allowDefault) { if (!allowDefault) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } }, /** * @description 查询触发指定事件的 DOM 元素。 * @param {Event} event - Event 对象。 * @param {string} tagName - html 标签名。 * @returns {HTMLElement} DOM 元素。 */ findElement: function (event, tagName) { var element = Event.element(event); while (element.parentNode && (!element.tagName || (element.tagName.toUpperCase() != tagName.toUpperCase()))) { element = element.parentNode; } return element; }, /** * @description 监听事件,注册事件处理方法。 * @param {(HTMLElement|string)} elementParam - 待监听的 DOM 对象或者其 ID 标识。 * @param {string} name - 监听事件的类别名称。 * @param {function} observer - 注册的事件处理方法。 * @param {boolean} [useCapture=false] - 是否捕获。 */ observe: function (elementParam, name, observer, useCapture) { var element = Util.getElement(elementParam); useCapture = useCapture || false; if (name === 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.attachEvent)) { name = 'keydown'; } //if observers cache has not yet been created, create it if (!this.observers) { this.observers = {}; } //if not already assigned, make a new unique cache ID if (!element._eventCacheID) { var idPrefix = "eventCacheID_"; if (element.id) { idPrefix = element.id + "_" + idPrefix; } element._eventCacheID = Util.createUniqueID(idPrefix); } var cacheID = element._eventCacheID; //if there is not yet a hash entry for this element, add one if (!this.observers[cacheID]) { this.observers[cacheID] = []; } //add a new observer to this element's list this.observers[cacheID].push({ 'element': element, 'name': name, 'observer': observer, 'useCapture': useCapture }); //add the actual browser event listener if (element.addEventListener) { if(name === 'mousewheel'){ // https://www.chromestatus.com/features/6662647093133312 element.addEventListener(name, observer, {useCapture: useCapture, passive: false} ); } else { element.addEventListener(name, observer, useCapture); } } else if (element.attachEvent) { element.attachEvent('on' + name, observer); } }, /** * @description 移除给定 DOM 元素的监听事件。 * @param {(HTMLElement|string)} elementParam - 待监听的 DOM 对象或者其 ID 标识。 */ stopObservingElement: function (elementParam) { var element = Util.getElement(elementParam); var cacheID = element._eventCacheID; this._removeElementObservers(Event.observers[cacheID]); }, _removeElementObservers: function (elementObservers) { if (elementObservers) { for (var i = elementObservers.length - 1; i >= 0; i--) { var entry = elementObservers[i]; var args = new Array(entry.element, entry.name, entry.observer, entry.useCapture); Event.stopObserving.apply(this, args); } } }, /** * @description 移除事件监听和注册的事件处理方法。注意:事件的移除和监听相对应,移除时的各属性信息必须监听时保持一致才能确保事件移除成功。 * @param {(HTMLElement|string)} elementParam - 被监听的 DOM 元素或者其 ID。 * @param {string} name - 需要移除的被监听事件名称。 * @param {function} observer - 需要移除的事件处理方法。 * @param {boolean} [useCapture=false] - 是否捕获。 * @returns {boolean} 监听事件是否被移除。 */ stopObserving: function (elementParam, name, observer, useCapture) { useCapture = useCapture || false; var element = Util.getElement(elementParam); var cacheID = element._eventCacheID; if (name === 'keypress') { if (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.detachEvent) { name = 'keydown'; } } // find element's entry in this.observers cache and remove it var foundEntry = false; var elementObservers = Event.observers[cacheID]; if (elementObservers) { // find the specific event type in the element's list var i = 0; while (!foundEntry && i < elementObservers.length) { var cacheEntry = elementObservers[i]; if ((cacheEntry.name === name) && (cacheEntry.observer === observer) && (cacheEntry.useCapture === useCapture)) { elementObservers.splice(i, 1); if (elementObservers.length == 0) { delete Event.observers[cacheID]; } foundEntry = true; break; } i++; } } //actually remove the event listener from browser if (foundEntry) { if (element.removeEventListener) { element.removeEventListener(name, observer, useCapture); } else if (element && element.detachEvent) { element.detachEvent('on' + name, observer); } } return foundEntry; }, /** * @description 移除缓存中的监听事件。 */ unloadCache: function () { // check for Event before checking for observers, because // Event may be undefined in IE if no map instance was // created if (Event && Event.observers) { for (var cacheID in Event.observers) { var elementObservers = Event.observers[cacheID]; Event._removeElementObservers.apply(this, [elementObservers]); } Event.observers = false; } }, CLASS_NAME: "SuperMap.Event" }; /* prevent memory leaks in IE */ Event.observe(window, 'resize', Event.unloadCache, false); ;// CONCATENATED MODULE: ./src/common/commontypes/Events.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Events * @deprecatedclass SuperMap.Events * @classdesc 事件类。 * @category BaseTypes Events * @param {Object} object - 当前事件对象被添加到的 JS 对象。 * @param {HTMLElement} element - 响应浏览器事件的 DOM 元素。 * @param {Array.} eventTypes - 自定义应用事件的数组。 * @param {boolean} [fallThrough=false] - 是否允许事件处理之后向上传递(冒泡),为 false 的时候阻止事件冒泡。 * @param {Object} options - 事件对象选项。 * @usage */ class Events { constructor(object, element, eventTypes, fallThrough, options) { /** * @member {Array.} Events.prototype.BROWSER_EVENTS * @description 支持的事件。 * @constant * @default [ "mouseover", "mouseout","mousedown", "mouseup", "mousemove", "click", "dblclick", "rightclick", "dblrightclick","resize", "focus", "blur","touchstart", "touchmove", "touchend","keydown", "MSPointerDown", "MSPointerUp", "pointerdown", "pointerup", "MSGestureStart", "MSGestureChange", "MSGestureEnd","contextmenu" ] */ this.BROWSER_EVENTS = [ "mouseover", "mouseout", "mousedown", "mouseup", "mousemove", "click", "dblclick", "rightclick", "dblrightclick", "resize", "focus", "blur", "touchstart", "touchmove", "touchend", "keydown", "MSPointerDown", "MSPointerUp", "pointerdown", "pointerup", "MSGestureStart", "MSGestureChange", "MSGestureEnd", "contextmenu" ]; /** * @member {Object} Events.prototype.listeners * @description 事件监听器函数。 */ this.listeners = {}; /** * @member {Object} Events.prototype.object * @description 发布应用程序事件的对象。 */ this.object = object; /** * @member {HTMLElement} Events.prototype.element * @description 接受浏览器事件的 DOM 节点。 */ this.element = null; /** * @member {Array.} Events.prototype.eventTypes * @description 支持的事件类型列表。 */ this.eventTypes = []; /** * @member {function} Events.prototype.eventHandler * @description 绑定在元素上的事件处理器对象。 */ this.eventHandler = null; /** * @member {boolean} [Events.prototype.fallThrough=false] * @description 是否允许事件处理之后向上传递(冒泡),为 false 的时候阻止事件冒泡。 */ this.fallThrough = fallThrough; /** * @member {boolean} [Events.prototype.includeXY=false] * @description 判断是否让 xy 属性自动创建到浏览器上的鼠标事件,一般设置为 false,如果设置为 true,鼠标事件将会在事件传递过程中自动产生 xy 属性。可根据事件对象的 'evt.object' 属性在相关的事件句柄上调用 getMousePosition 函数。这个选项习惯默认为 false 的原因在于,当创建一个事件对象,其主要目的是管理。在一个 div 的相对定位的鼠标事件,将其设为 true 也是有意义的。这个选项也可以用来控制是否抵消缓存。如果设为 false 不抵消,如果设为 true,用 this.clearMouseCache() 清除缓存偏移(边界元素偏移,元素在页面的位置偏移)。 * @example * function named(evt) { * this.xy = this.object.events.getMousePosition(evt); * } */ this.includeXY = false; /** * @member {Object} Events.prototype.extensions * @description 事件扩展。Keys 代表事件类型,values 代表事件对象。 */ this.extensions = {}; /** * @member {Object} Events.prototype.extensionCount * @description 事件扩展数量。 */ this.extensionCount = {}; /** * @member {Object} Events.prototype.clearMouseListener * @description 待移除的鼠标监听事件。 */ this.clearMouseListener = null; Util.extend(this, options); if (eventTypes != null) { for (var i = 0, len = eventTypes.length; i < len; i++) { this.addEventType(eventTypes[i]); } } if (element != null) { this.attachToElement(element); } this.CLASS_NAME = "SuperMap.Events"; } /** * @function Events.prototype.destroy * @description 移除当前要素 element 上的所有事件监听和处理。 */ destroy() { for (var e in this.extensions) { if (typeof this.extensions[e] !== "boolean") { this.extensions[e].destroy(); } } this.extensions = null; if (this.element) { Event.stopObservingElement(this.element); if (this.element.hasScrollEvent) { Event.stopObserving( window, "scroll", this.clearMouseListener ); } } this.element = null; this.listeners = null; this.object = null; this.eventTypes = null; this.fallThrough = null; this.eventHandler = null; } /** * @function Events.prototype.addEventType * @description 在此事件对象中添加新的事件类型,如果这个事件类型已经添加过了,则不做任何事情。 * @param {string} eventName - 事件名。 */ addEventType(eventName) { if (!this.listeners[eventName]) { this.eventTypes.push(eventName); this.listeners[eventName] = []; } } /** * @function Events.prototype.attachToElement * @description 给 DOM 元素绑定浏览器事件。 * @param {HTMLElement} element - 绑定浏览器事件的 DOM 元素。 */ attachToElement(element) { if (this.element) { Event.stopObservingElement(this.element); } else { // keep a bound copy of handleBrowserEvent() so that we can // pass the same function to both Event.observe() and .stopObserving() this.eventHandler = FunctionExt.bindAsEventListener( this.handleBrowserEvent, this ); // to be used with observe and stopObserving this.clearMouseListener = FunctionExt.bind( this.clearMouseCache, this ); } this.element = element; for (var i = 0, len = this.BROWSER_EVENTS.length; i < len; i++) { var eventType = this.BROWSER_EVENTS[i]; // every browser event has a corresponding application event // (whether it's listened for or not). this.addEventType(eventType); // use Prototype to register the event cross-browser Event.observe(element, eventType, this.eventHandler); } // disable dragstart in IE so that mousedown/move/up works normally Event.observe(element, "dragstart", Event.stop); } /** * @function Events.prototype.on * @description 在一个相同的范围内注册监听器的方法,此方法调用 register 函数。 * @example * // 注册一个 "loadstart" 监听事件 * events.on({"loadstart": loadStartListener}); * * // 同样注册一个 "loadstart" 监听事件 * events.register("loadstart", undefined, loadStartListener); * * // 同时为对象注册多个监听事件 * events.on({ * "loadstart": loadStartListener, * "loadend": loadEndListener, * scope: object * }); * * // 同时为对象注册多个监听事件,多次调用 register 方法 * events.register("loadstart", object, loadStartListener); * events.register("loadend", object, loadEndListener); * * * @param {Object} object - 添加监听的对象。 */ on(object) { for (var type in object) { if (type !== "scope" && object.hasOwnProperty(type)) { this.register(type, object.scope, object[type]); } } } /** * @function Events.prototype.register * @description 在事件对象上注册一个事件。当事件被触发时,'func' 函数被调用,假设我们触发一个事件, * 指定 Bounds 作为 "obj",当事件被触发时,回调函数的上下文作为 Bounds 对象。 * @param {string} type - 事件注册者的名字。 * @param {Object} [obj=this.object] - 对象绑定的回调。 * @param {function} [func] - 回调函数,如果没有特定的回调,则这个函数不做任何事情。 * @param {(boolean|Object)} [priority] - 当为 true 时将新的监听加在事件队列的前面。 */ register(type, obj, func, priority) { if (type in Events && !this.extensions[type]) { this.extensions[type] = new Events[type](this); } if ((func != null) && (Util.indexOf(this.eventTypes, type) !== -1)) { if (obj == null) { obj = this.object; } var listeners = this.listeners[type]; if (!listeners) { listeners = []; this.listeners[type] = listeners; this.extensionCount[type] = 0; } var listener = {obj: obj, func: func}; if (priority) { listeners.splice(this.extensionCount[type], 0, listener); if (typeof priority === "object" && priority.extension) { this.extensionCount[type]++; } } else { listeners.push(listener); } } } /** * @function Events.prototype.registerPriority * @description 相同的注册方法,但是在前面增加新的监听者事件查询而代替到方法的结束。 * @param {string} type - 事件注册者的名字。 * @param {Object} [obj=this.object] - 对象绑定的回调。 * @param {function} [func] - 回调函数,如果没有特定的回调,则这个函数不做任何事情。 */ registerPriority(type, obj, func) { this.register(type, obj, func, true); } /** * @function Events.prototype.un * @description 在一个相同的范围内取消注册监听器的方法,此方法调用 unregister 函数。 * @example * // 移除 "loadstart" 事件监听 * events.un({"loadstart": loadStartListener}); * * // 使用 "unregister" 方法移除 "loadstart" 事件监听 * events.unregister("loadstart", undefined, loadStartListener); * * // 取消对象多个事件监听 * events.un({ * "loadstart": loadStartListener, * "loadend": loadEndListener, * scope: object * }); * * // 取消对象多个事件监听,多次调用unregister方法。 * events.unregister("loadstart", object, loadStartListener); * events.unregister("loadend", object, loadEndListener); * * @param {Object} object - 移除监听的对象。 */ un(object) { for (var type in object) { if (type !== "scope" && object.hasOwnProperty(type)) { this.unregister(type, object.scope, object[type]); } } } /** * @function Events.prototype.unregister * @description 取消注册。 * @param {string} type - 事件类型。 * @param {Object} [obj=this.object] - 对象绑定的回调。 * @param {function} [func] - 回调函数,如果没有特定的回调,则这个函数不做任何事情。 */ unregister(type, obj, func) { if (obj == null) { obj = this.object; } var listeners = this.listeners[type]; if (listeners != null) { for (var i = 0, len = listeners.length; i < len; i++) { if (listeners[i].obj === obj && listeners[i].func === func) { listeners.splice(i, 1); break; } } } } /** * @function Events.prototype.remove * @description 删除某个事件类型的所有监听,如果该事件类型没有注册,则不做任何操作。 * @param {string} type - 事件类型。 */ remove(type) { if (this.listeners[type] != null) { this.listeners[type] = []; } } /** * @function Events.prototype.triggerEvent * @description 触发一个特定的注册事件。 * @param {string} type - 触发事件类型。 * @param {Event} evt - 事件对象。 * @returns {Event|boolean} 监听对象,如果返回是 false,则停止监听。 */ triggerEvent(type, evt) { var listeners = this.listeners[type]; // fast path if (!listeners || listeners.length == 0) { return undefined; } // prep evt object with object & div references if (evt == null) { evt = {}; } evt.object = this.object; evt.element = this.element; if (!evt.type) { evt.type = type; } // execute all callbacks registered for specified type // get a clone of the listeners array to // allow for splicing during callbacks listeners = listeners.slice(); var continueChain; for (var i = 0, len = listeners.length; i < len; i++) { var callback = listeners[i]; // bind the context to callback.obj continueChain = callback.func.apply(callback.obj, [evt]); if ((continueChain != undefined) && (continueChain === false)) { // if callback returns false, execute no more callbacks. break; } } // don't fall through to other DOM elements if (!this.fallThrough) { Event.stop(evt, true); } return continueChain; } /** * @function Events.prototype.handleBrowserEvent * @description 对 triggerEvent 函数的包装,给事件对象设置了 xy 属性(即当前鼠标点的 xy 坐标)。 * @param {Event} evt - 事件对象。 */ handleBrowserEvent(evt) { var type = evt.type, listeners = this.listeners[type]; if (!listeners || listeners.length == 0) { // noone's listening, bail out return; } // add clientX & clientY to all events - corresponds to average x, y var touches = evt.touches; if (touches && touches[0]) { var x = 0; var y = 0; var num = touches.length; var touch; for (var i = 0; i < num; ++i) { touch = touches[i]; x += touch.clientX; y += touch.clientY; } evt.clientX = x / num; evt.clientY = y / num; } if (this.includeXY) { evt.xy = this.getMousePosition(evt); } this.triggerEvent(type, evt); } /** * @function Events.prototype.clearMouseCache * @description 清除鼠标缓存。 */ clearMouseCache() { this.element.scrolls = null; this.element.lefttop = null; var body = document.body; if (body && !((body.scrollTop != 0 || body.scrollLeft != 0) && navigator.userAgent.match(/iPhone/i))) { this.element.offsets = null; } } /** * @function Events.prototype.getMousePosition * @description 获取当前鼠标的位置。 * @param {Event} evt - 事件对象。 * @returns {Pixel} 当前的鼠标的 xy 坐标点。 */ getMousePosition(evt) { if (!this.includeXY) { this.clearMouseCache(); } else if (!this.element.hasScrollEvent) { Event.observe(window, "scroll", this.clearMouseListener); this.element.hasScrollEvent = true; } if (!this.element.scrolls) { var viewportElement = Util.getViewportElement(); this.element.scrolls = [ viewportElement.scrollLeft, viewportElement.scrollTop ]; } if (!this.element.lefttop) { this.element.lefttop = [ (document.documentElement.clientLeft || 0), (document.documentElement.clientTop || 0) ]; } if (!this.element.offsets) { this.element.offsets = Util.pagePosition(this.element); } return new Pixel( (evt.clientX + this.element.scrolls[0]) - this.element.offsets[0] - this.element.lefttop[0], (evt.clientY + this.element.scrolls[1]) - this.element.offsets[1] - this.element.lefttop[1] ); } } Events.prototype.BROWSER_EVENTS = [ "mouseover", "mouseout", "mousedown", "mouseup", "mousemove", "click", "dblclick", "rightclick", "dblrightclick", "resize", "focus", "blur", "touchstart", "touchmove", "touchend", "keydown", "MSPointerDown", "MSPointerUp", "pointerdown", "pointerup", "MSGestureStart", "MSGestureChange", "MSGestureEnd", "contextmenu" ]; ;// CONCATENATED MODULE: ./src/common/commontypes/Feature.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Feature * @deprecatedclass SuperMap.Feature * @category BaseTypes Geometry * @classdesc 要素类组合了地理和属性,Feature 类同时具有 marker 和 lonlat 属性。 * @param {SuperMap.Layer} layer - 图层。 * @param {LonLat} lonlat - 经纬度。 * @param {Object} data - 数据对象。 * @usage */ class Feature_Feature { constructor(layer, lonlat, data) { this.CLASS_NAME = "SuperMap.Feature"; /** * @deprecated * @member {SuperMap.Layer} Feature.prototype.layer * @description 图层。 */ this.layer = layer; /** * @member {string} Feature.prototype.id * @description 要素 ID。 */ this.id = Util.createUniqueID(this.CLASS_NAME + "_"); /** * @member {LonLat} Feature.prototype.lonlat * @description 经纬度。 * */ this.lonlat = lonlat; /** * @member {Object} Feature.prototype.data * @description 数据对象。 */ this.data = (data != null) ? data : {}; } /** * @function Feature.prototype.destroy * @description 释放相关资源。 */ destroy() { this.id = null; this.lonlat = null; this.data = null; } } ;// CONCATENATED MODULE: ./src/common/commontypes/Vector.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureVector * @aliasclass Feature.Vector * @deprecatedclass SuperMap.Feature.Vector * @category BaseTypes Geometry * @classdesc 矢量要素类。该类具有 Geometry 属性存放几何信息, * attributes 属性存放非几何信息,另外还包含了 style 属性,用来定义矢量要素的样式, * 其中,默认的样式在 {@link FeatureVector.style} 类中定义,如果没有特别的指定将使用默认的样式。 * @extends {Feature} * @param {Geometry} geometry - 要素的几何信息。 * @param {Object} [attributes] - 描述要素的任意的可序列化属性,将要映射到 attributes 属性中的对象。 * @param {Object} [style] - 样式对象。 * @example * var geometry = new GeometryPoint(-115,10); * var style = { * strokeColor:"#339933", * strokeOpacity:1, * strokeWidth:3, * pointRadius:6 * } * var pointFeature = new FeatureVector(geometry,null,style); * vectorLayer.addFeatures(pointFeature); * @usage */ // TRASH THIS const State = { /** states */ UNKNOWN: 'Unknown', INSERT: 'Insert', UPDATE: 'Update', DELETE: 'Delete' }; class Vector extends Feature_Feature { constructor(geometry, attributes, style) { super(null, null, attributes); /** * @member {string} FeatureVector.prototype.fid * @description fid。 */ this.fid = null; /** * @member {Geometry} FeatureVector.prototype.geometry * @description 存放几何信息。 */ this.geometry = geometry ? geometry : null; /** * @member {Object} FeatureVector.prototype.attributes * @description 描述要素的任意的可序列化属性。 */ this.attributes = {}; if (attributes) { this.attributes = Util.extend(this.attributes, attributes); } /** * @member {Bounds} FeatureVector.prototype.bounds * @description 限制要素几何的边界。 */ this.bounds = null; /** * @member {string} FeatureVector.prototype.state * @description state。 */ this.state = null; /** * @member {Object} FeatureVector.prototype.style * @description 要素的样式属性,地图查询返回的 feature 的 style,8C 变为null。 */ this.style = style ? style : null; /** * @member {string} FeatureVector.prototype.url * @description 如果设置了这个属性,在更新或者删除要素时需要考虑 {@link HTTP} 。 */ this.url = null; this.lonlat = null; this.CLASS_NAME = "SuperMap.Feature.Vector"; Vector.style = { 'default': { fillColor: "#ee9900", fillOpacity: 0.4, hoverFillColor: "white", hoverFillOpacity: 0.8, strokeColor: "#ee9900", strokeOpacity: 1, strokeWidth: 1, strokeLinecap: "round", strokeDashstyle: "solid", hoverStrokeColor: "red", hoverStrokeOpacity: 1, hoverStrokeWidth: 0.2, pointRadius: 6, hoverPointRadius: 1, hoverPointUnit: "%", pointerEvents: "visiblePainted", cursor: "inherit", fontColor: "#000000", labelAlign: "cm", labelOutlineColor: "white", labelOutlineWidth: 3 }, 'select': { fillColor: "blue", fillOpacity: 0.4, hoverFillColor: "white", hoverFillOpacity: 0.8, strokeColor: "blue", strokeOpacity: 1, strokeWidth: 2, strokeLinecap: "round", strokeDashstyle: "solid", hoverStrokeColor: "red", hoverStrokeOpacity: 1, hoverStrokeWidth: 0.2, pointRadius: 6, hoverPointRadius: 1, hoverPointUnit: "%", pointerEvents: "visiblePainted", cursor: "pointer", fontColor: "#000000", labelAlign: "cm", labelOutlineColor: "white", labelOutlineWidth: 3 }, 'temporary': { fillColor: "#66cccc", fillOpacity: 0.2, hoverFillColor: "white", hoverFillOpacity: 0.8, strokeColor: "#66cccc", strokeOpacity: 1, strokeLinecap: "round", strokeWidth: 2, strokeDashstyle: "solid", hoverStrokeColor: "red", hoverStrokeOpacity: 1, hoverStrokeWidth: 0.2, pointRadius: 6, hoverPointRadius: 1, hoverPointUnit: "%", pointerEvents: "visiblePainted", //cursor:"inherit", cursor: "default", fontColor: "#000000", labelAlign: "cm", labelOutlineColor: "white", labelOutlineWidth: 3 }, 'delete': { display: "none" } }; } /** * @function FeatureVector.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { if (this.layer) { this.layer.removeFeatures(this); this.layer = null; } this.geometry = null; super.destroy(); } /** * @function FeatureVector.prototype.clone * @description 复制矢量要素,并返回复制后的新对象。 * @returns {FeatureVector} 相同要素的新的矢量要素。 */ clone() { return new Vector( this.geometry ? this.geometry.clone() : null, this.attributes, this.style); } /** * @function FeatureVector.prototype.toState * @description 设置新状态。 * @param {string} state - 状态。 */ toState(state) { if (state === State.UPDATE) { switch (this.state) { case State.UNKNOWN: case State.DELETE: this.state = state; break; case State.UPDATE: case State.INSERT: break; } } else if (state === State.INSERT) { switch (this.state) { case State.UNKNOWN: break; default: this.state = state; break; } } else if (state === State.DELETE) { switch (this.state) { case State.INSERT: // the feature should be destroyed break; case State.DELETE: break; case State.UNKNOWN: case State.UPDATE: this.state = state; break; } } else if (state === State.UNKNOWN) { this.state = state; } } } /** * * @typedef {Object} FeatureVector.style * @description Feature 有大量的样式属性,如果没有特别的指定将使用默认的样式, * 大部分样式通过 SVG 标准定义属性。 * - fill properties 资料介绍:{@link http://www.w3.org/TR/SVG/painting.html#FillProperties} * - stroke properties 资料介绍:{@link http://www.w3.org/TR/SVG/painting.html#StrokeProperties} * @property {boolean} [fill] - 不需要填充则设置为 false。 * @property {string} [fillColor='#ee9900'] - 十六进制填充颜色。 * @property {number} [fillOpacity=0.4] - 填充不透明度。 * @property {boolean} [stroke] - 不需要描边则设为 false。 * @property {string} [strokeColor='#ee9900'] - 十六进制描边颜色。 * @property {number} [strokeOpacity=0.4] - 描边的不透明度(0-1)。 * @property {number} [strokeWidth=1] - 像素描边宽度。 * @property {string} [strokeLinecap='round'] - strokeLinecap 有三种类型 butt,round,square。 * @property {string} [strokeDashstyle='solid'] - 有 dot,dash,dashdot,longdash,longdashdot,solid 几种样式。 * @property {boolean} [graphic] - 不需要则设置为 false。 * @property {number} [pointRadius=6] - 像素点半径。 * @property {string} [pointerEvents='visiblePainted'] - pointerEvents。 * @property {string} [cursor] - cursor。 * @property {boolean} [allowRotate='false'] - 是否允许图标随着运行方向旋转。用于时空数据图层。 * @property {string} [externalGraphic] - 连接到用来渲染点的外部的图形。 * @property {number} [graphicWidth] - 外部图表的像素宽度。 * @property {number} [graphicHeight] - 外部图表的像素高度。 * @property {number} [graphicOpacity] - 外部图表的不透明度(0-1)。 * @property {number} [graphicXOffset] - 外部图表沿着x方向的偏移量。 * @property {number} [graphicYOffset] - 外部图表沿着y方向的偏移量。 * @property {number} [rotation] - 一个图表沿着其中心点(或者偏移中心指定点)在顺时针方向旋转。 * @property {number} [graphicZIndex] - 渲染时使用的索引值。 * @property {string} [graphicName='circle'] - 渲染点时图标使用的名字。支持"circle" , "square", "star", "x", "cross", "triangle"。 * @property {string} [graphicTitle] - 外部图表的提示框。 * @property {string} [backgroundGraphic] - 外部图表的背景。 * @property {number} [backgroundGraphicZIndex] - 背景图渲染时使用的索引值。 * @property {number} [backgroundXOffset] - 背景图在 x 轴的偏移量。 * @property {number} [backgroundYOffset] - 背景图在 y 轴的偏移量。 * @property {number} [backgroundHeight] - 背景图的高度。如果没有设置,将用 graphicHeight。 * @property {number} [backgroundWidth] - 背景图的宽度。如果没有设置,将用 graphicWidth。 * @property {boolean} [isUnicode=false] - 这个属性要配合 label 属性来用,当为 true时,label 就可以使用 unicode 编码, * 比如 "a" 的 unicode 十六进制编码为 61,则 label 属性可以为 "a",其中 "&#" 为前缀,标志这个为 unicode 编码, * "x" 是指 16 进制,这时页面显示的是 "a";当此值为 false 的时候,label 的内容会被直接输出, * 比如,label 为 "a",这时页面显示的也是 "a"。 * @property {string} [label] - 可选的标签文本。 * @property {string} [labelAlign='cm'] - 标签对齐,是由两个字符组成的字符串,如:"lt", "cm", "rb", * 其中第一个字符代表水平方向上的对齐,"l"=left, "c"=center, "r"=right; * 第二个字符代表垂直方向上的对齐,"t"=top, "m"=middle, "b"=bottom。 * @property {number} [labelXOffset] - 标签在 x 轴方向的偏移量。 * @property {number} [labelYOffset] - 标签在 y 轴方向的偏移量。 * @property {boolean} [labelSelect=false] - 如果设为 true,标签可以选用 SelectFeature 或者 similar 控件。 * @property {string} [fontColor='#000000'] - 标签字体颜色。 * @property {number} [fontOpacity] - 标签透明度 (0-1)。 * @property {string} [fontFamily] - 标签的字体类型。 * @property {string} [fontSize] - 标签的字体大小。 * @property {string} [fontStyle] - 标签的字体样式。 * @property {string} [fontWeight] - 标签的字体粗细。 * @property {string} [display] - 如果 display 属性设置为 “none”,符号将没有任何效果。 * @example * // label的用法如下: * function addGeoTest(){ * var geometry = new GeometryPoint(105, 35); * var pointFeature = new FeatureVector(geometry); * var styleTest = { * label:"supermap", * fontColor:"#0000ff", * fontOpacity:"0.5", * fontFamily:"隶书", * fontSize:"8em", * fontWeight:"bold", * fontStyle:"italic", * labelSelect:"true", * } * pointFeature.style = styleTest; * vectorLayer.addFeatures([pointFeature]); * } */ ;// CONCATENATED MODULE: ./src/common/commontypes/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/format/Format.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Format * @deprecatedclass SuperMap.Format * @classdesc 读写各种格式的格式类基类。其子类应该包含并实现 read 和 write 方法。 * @category BaseTypes Format * @param {Object} options - 可选参数。 * @param {boolean} [options.keepData=false] - 如果设置为 true, data 属性会指向被解析的对象(例如 JSON 或 xml 数据对象)。 * @param {Object} [options.data] - 当 keepData 属性设置为 true,这是传递给 read 操作的要被解析的字符串。 * @usage */ class Format { constructor(options) { /** * @member {Object} Format.prototype.data * @description 当 keepData 属性设置为 true,这是传递给 read 操作的要被解析的字符串。 */ this.data = null; /** * @member {Object} [Format.prototype.keepData=false] * @description 保持最近读到的数据的引用(通过 data 属性)。 */ this.keepData = false; Util.extend(this, options); this.options = options; this.CLASS_NAME = "SuperMap.Format"; } /** * @function Format.prototype.destroy * @description 销毁该格式类,释放相关资源。 */ destroy() { //用来销毁该格式类,释放相关资源 } /** * @function Format.prototype.read * @description 来从字符串中读取数据。 * @param {string} data - 读取的数据。 */ read(data) { // eslint-disable-line no-unused-vars //用来从字符串中读取数据 } /** * @function Format.prototype.write * @description 将对象写成字符串。 * @param {Object} object - 可序列化的对象。 * @returns {string} 对象转化后的字符串。 */ write(object) { // eslint-disable-line no-unused-vars //用来写字符串 } } ;// CONCATENATED MODULE: ./src/common/format/JSON.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class JSONFormat * @aliasclass Format.JSON * @deprecatedclass SuperMap.Format.JSON * @classdesc 安全的读写 JSON 的解析类。使用 {@link JSONFormat} 构造函数创建新实例。 * @category BaseTypes Format * @param {Object} [options] - 可选参数。 * @param {string} [options.indent=" "] - 用于格式化输出,indent 字符串会在每次缩进的时候使用一次。 * @param {string} [options.space=" "] - 用于格式化输出,space 字符串会在名值对的 ":" 后边添加。 * @param {string} [options.newline="\n"] - 用于格式化输出, newline 字符串会用在每一个名值对或数组项末尾。 * @param {number} [options.level=0] - 用于格式化输出, 表示的是缩进级别。 * @param {boolean} [options.pretty=false] - 是否在序列化的时候使用额外的空格控制结构。在 write 方法中使用。 * @param {boolean} [options.nativeJSON] - 需要被注册的监听器对象。 * @extends {Format} * @usage */ class JSONFormat extends Format { constructor(options) { super(options); /** * @member {string} [JSONFormat.prototype.indent=" "] * @description 用于格式化输出,indent 字符串会在每次缩进的时候使用一次。 */ this.indent = " "; /** * @member {string} [JSONFormat.prototype.space=" "] * @description 用于格式化输出,space 字符串会在名值对的 ":" 后边添加。 */ this.space = " "; /** * @member {string} [JSONFormat.prototype.newline="\n"] * @description 用于格式化输出, newline 字符串会用在每一个名值对或数组项末尾。 */ this.newline = "\n"; /** * @member {number} [JSONFormat.prototype.level=0] * @description 用于格式化输出, 表示的是缩进级别。 */ this.level = 0; /** * @member {boolean} [JSONFormat.prototype.pretty=false] * @description 是否在序列化的时候使用额外的空格控制结构。在 write 方法中使用。 */ this.pretty = false; /** * @member {boolean} JSONFormat.prototype.nativeJSON * @description 判断浏览器是否原生支持 JSON 格式数据。 */ this.nativeJSON = (function () { return !!(window.JSON && typeof JSON.parse === "function" && typeof JSON.stringify === "function"); })(); this.CLASS_NAME = "SuperMap.Format.JSON"; /** * @member JSONFormat.prototype.serialize * @description 提供一些类型对象转 JSON 字符串的方法。 */ this.serialize = { /** * @function JSONFormat.serialize.object * @description 把对象转换为 JSON 字符串。 * @param {Object} object - 可序列化的对象。 * @returns {string} JSON 字符串。 */ 'object': function (object) { // three special objects that we want to treat differently if (object == null) { return "null"; } if (object.constructor === Date) { return this.serialize.date.apply(this, [object]); } if (object.constructor === Array) { return this.serialize.array.apply(this, [object]); } var pieces = ['{']; this.level += 1; var key, keyJSON, valueJSON; var addComma = false; for (key in object) { if (object.hasOwnProperty(key)) { // recursive calls need to allow for sub-classing keyJSON = this.write.apply(this, [key, this.pretty]); valueJSON = this.write.apply(this, [object[key], this.pretty]); if (keyJSON != null && valueJSON != null) { if (addComma) { pieces.push(','); } pieces.push(this.writeNewline(), this.writeIndent(), keyJSON, ':', this.writeSpace(), valueJSON); addComma = true; } } } this.level -= 1; pieces.push(this.writeNewline(), this.writeIndent(), '}'); return pieces.join(''); }, /** * @function JSONFormat.serialize.array * @description 把数组转换成 JSON 字符串。 * @param {Array} array - 可序列化的数组。 * @returns {string} JSON 字符串。 */ 'array': function (array) { var json; var pieces = ['[']; this.level += 1; for (var i = 0, len = array.length; i < len; ++i) { // recursive calls need to allow for sub-classing json = this.write.apply(this, [array[i], this.pretty]); if (json != null) { if (i > 0) { pieces.push(','); } pieces.push(this.writeNewline(), this.writeIndent(), json); } } this.level -= 1; pieces.push(this.writeNewline(), this.writeIndent(), ']'); return pieces.join(''); }, /** * @function JSONFormat.serialize.string * @description 把字符串转换成 JSON 字符串。 * @param {string} string - 可序列化的字符串。 * @returns {string} JSON 字符串。 */ 'string': function (string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can simply slap some quotes around it. // Otherwise we must also replace the offending characters with safe // sequences. var m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }; /*eslint-disable no-control-regex*/ if (/["\\\x00-\x1f]/.test(string)) { return '"' + string.replace(/([\x00-\x1f\\"])/g, function (a, b) { var c = m[b]; if (c) { return c; } c = b.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + string + '"'; }, /** * @function JSONFormat.serialize.number * @description 把数字转换成 JSON 字符串。 * @param {number} number - 可序列化的数字。 * @returns {string} JSON 字符串。 */ 'number': function (number) { return isFinite(number) ? String(number) : "null"; }, /** * @function JSONFormat.serialize.boolean * @description Transform a boolean into a JSON string. * @param {boolean} bool - The boolean to be serialized. * @returns {string} A JSON string representing the boolean. */ 'boolean': function (bool) { return String(bool); }, /** * @function JSONFormat.serialize.object * @description 将日期对象转换成 JSON 字符串。 * @param {Date} date - 可序列化的日期对象。 * @returns {string} JSON 字符串。 */ 'date': function (date) { function format(number) { // Format integers to have at least two digits. return (number < 10) ? '0' + number : number; } return '"' + date.getFullYear() + '-' + format(date.getMonth() + 1) + '-' + format(date.getDate()) + 'T' + format(date.getHours()) + ':' + format(date.getMinutes()) + ':' + format(date.getSeconds()) + '"'; } }; } /** * @function JSONFormat.prototype.read * @description 将一个符合 JSON 结构的字符串进行解析。 * @param {string} json - 符合 JSON 结构的字符串。 * @param {function} filter - 过滤方法,最终结果的每一个键值对都会调用该过滤方法,并在对应的值的位置替换成该方法返回的值。 * @returns {(Object|string|Array|number|boolean)} 对象,数组,字符串或数字。 */ read(json, filter) { var object; if (this.nativeJSON) { try { object = JSON.parse(json, filter); } catch (e) { // Fall through if the regexp test fails. return { data: json} } } if (this.keepData) { this.data = object; } return object; } /** * @function JSONFormat.prototype.write * @description 序列化一个对象到一个符合 JSON 格式的字符串。 * @param {Object|string|Array|number|boolean} value - 需要被序列化的对象,数组,字符串,数字,布尔值。 * @param {boolean} [pretty=false] - 是否在序列化的时候使用额外的空格控制结构。在 write 方法中使用。 * @returns {string} 符合 JSON 格式的字符串。 * */ write(value, pretty) { this.pretty = !!pretty; var json = null; var type = typeof value; if (this.serialize[type]) { try { json = (!this.pretty && this.nativeJSON) ? JSON.stringify(value) : this.serialize[type].apply(this, [value]); } catch (err) { //console.error("Trouble serializing: " + err); } } return json; } /** * @function JSONFormat.prototype.writeIndent * @description 根据缩进级别输出一个缩进字符串。 * @private * @returns {string} 一个适当的缩进字符串。 */ writeIndent() { var pieces = []; if (this.pretty) { for (var i = 0; i < this.level; ++i) { pieces.push(this.indent); } } return pieces.join(''); } /** * @function JSONFormat.prototype.writeNewline * @description 在格式化输出模式情况下输出代表新一行的字符串。 * @private * @returns {string} 代表新的一行的字符串。 */ writeNewline() { return (this.pretty) ? this.newline : ''; } /** * @function JSONFormat.prototype.writeSpace * @private * @description 在格式化输出模式情况下输出一个代表空格的字符串。 * @returns {string} 空格字符串。 */ writeSpace() { return (this.pretty) ? this.space : ''; } } ;// CONCATENATED MODULE: ./src/common/iServer/ServerColor.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ServerColor * @deprecatedclass SuperMap.ServerColor * @category iServer Map Theme * @classdesc 颜色类。该类使用三原色( RGB )来表达颜色。 * @param {Object} options - 可选参数。 * @param {number} [options.red=255] - 获取或设置红色值。 * @param {number} [options.green=0] - 获取或设置绿色值。 * @param {number} [options.blue=0] - 获取或设置蓝色值。 * @usage */ class ServerColor { constructor(red, green, blue) { /** * @member {number} [ServerColor.prototype.red=255] * @description 获取或设置红色值。 */ this.red = (!red && red != 0)?255:red; /** * @member {number} [ServerColor.prototype.green=0] * @description 获取或设置绿色值。 */ this.green = green||0; /** * @member {number} [ServerColor.prototype.blue=0] * @description 获取或设置蓝色值。 */ this.blue = blue||0; this.CLASS_NAME = "SuperMap.ServerColor"; } /** * @function ServerColor.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.red = null; me.green = null; me.blue = null; } /** * @function ServerColor.formJson * @description 将 JSON 对象转化为 ServerColor 对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 * @returns {ServerColor} 转化后的 ServerColor 对象。 */ static fromJson(jsonObject) { if (!jsonObject) { return; } var color = new ServerColor(); var red = 255; if (jsonObject.red !== null) { red = Number(jsonObject.red); } color.red = red; var green = 0; if (jsonObject.green !== null) { green = Number(jsonObject.green); } color.green = green; var blue = 0; if (jsonObject.blue !== null) { blue = Number(jsonObject.blue); } color.blue = blue; return color; } } ;// CONCATENATED MODULE: ./src/common/iServer/ServerStyle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ServerStyle * @deprecatedclass SuperMap.ServerStyle * @category iServer Map Theme * @classdesc 服务端矢量要素风格类。该类用于定义点状符号、线状符号、填充符号风格及其相关属性。 * @param {Object} options - 参数。 * @param {FillGradientMode} options.fillGradientMode - 渐变填充风格的渐变类型。 * @param {ServerColor} [options.fillBackColor=[255,255,255]] - 填充背景颜色。 * @param {boolean} [options.fillBackOpaque=false] - 背景是否不透明。 * @param {ServerColor} [options.fillForeColor=[255,0,0]] - 填充颜色。 * @param {number} [options.fillGradientAngle=0] - 渐变填充的旋转角度。 * @param {number} [options.fillGradientOffsetRatioX=0] - 渐变填充中心点相对于填充区域范围中心点的水平偏移百分比。 * @param {number} [options.fillGradientOffsetRatioY=0] - 填充中心点相对于填充区域范围中心点的垂直偏移百分比。 * @param {number} [options.fillOpaqueRate=100] - 填充不透明度。 * @param {number} [options.fillSymbolID=0] - 填充符号的编码。 * @param {ServerColor} [options.lineColor] - 矢量要素的边线颜色。默认 lineColor = new ServerColor(0, 0, 0)。 * @param {number} [options.lineSymbolID=0] - 线状符号的编码。 * @param {number} [options.lineWidth=1] - 边线的宽度。 * @param {number} [options.markerAngle=0] - 点状符号的旋转角度。 * @param {number} [options.markerSize=1] - 点状符号的大小。 * @param {number} [options.markerSymbolID=-1] - 点状符号的编码。 * @usage */ class ServerStyle { constructor(options) { /** * @member {ServerColor} ServerStyle.prototype.fillBackColor * @description 填充背景颜色。当填充模式为渐变填充时,该颜色为填充终止色。 */ this.fillBackColor = new ServerColor(255, 255, 255); /** * @member {boolean} [ServerStyle.prototype.fillBackOpaque=false] * @description 背景是否不透明。false 表示透明。 */ this.fillBackOpaque = false; /** * @member {ServerColor} ServerStyle.prototype.fillForeColor * @description 填充颜色。当填充模式为渐变填充时,该颜色为填充起始颜色。 */ this.fillForeColor = new ServerColor(255, 0, 0); /** * @member {FillGradientMode} ServerStyle.prototype.fillGradientMode * @description 渐变填充风格的渐变类型。 */ this.fillGradientMode = null; /** * @member {number} ServerStyle.prototype.fillGradientAngle - * @description 渐变填充的旋转角度。单位为度,精确到 0.1 度,逆时针方向为正方向。 */ this.fillGradientAngle = 0; /** * @member {number} ServerStyle.prototype.fillGradientOffsetRatioX * @description 渐变填充中心点相对于填充区域范围中心点的水平偏移百分比。它们的关系如下:设填充区域范围中心点的坐标为(x0, y0), * 填充中心点的坐标为(x, y),填充区域范围的宽度为 a,水平偏移百分比为 dx,则 x=x0 + a*dx/100。 */ this.fillGradientOffsetRatioX = 0; /** * @member {number} ServerStyle.prototype.fillGradientOffsetRatioY * @description 填充中心点相对于填充区域范围中心点的垂直偏移百分比。它们的关系如下:
* 设填充区域范围中心点的坐标为(x0, y0),填充中心点的坐标为(x, y),填充区域范围的高度为 b,垂直偏移百分比为 dy,则 y=y0 + b*dx/100。 */ this.fillGradientOffsetRatioY = 0; /** * @member {number} [ServerStyle.prototype.fillOpaqueRate=100] * @description 填充不透明度。合法值为 0 - 100 的数值。其中为 0 表示完全透明; * 100 表示完全不透明。赋值小于 0 时按照 0 处理,大于 100 时按照 100 处理。 */ this.fillOpaqueRate = 100; /** * @member {number} ServerStyle.prototype.fillSymbolID * @description 填充符号的编码。此编码用于唯一标识各普通填充风格的填充符号。 * 关于填充符号的样式与对应的 ID 号请在 SuperMap 桌面软件中查找。 */ this.fillSymbolID = 0; /** * @member {ServerColor} ServerStyle.prototype.lineColor * @description 矢量要素的边线颜色。如果等级符号是点符号,点符号的颜色由 lineColor 控制。 */ this.lineColor = new ServerColor(0, 0, 0); /** * @member {number} [ServerStyle.prototype.lineSymbolID=0] * @description 线状符号的编码。此编码用于唯一标识各普通填充风格的填充符号。 * 关于线状符号的样式与对应的 ID 号请在 SuperMap 桌面软件中查找。 */ this.lineSymbolID = 0; /** * @member {number} [ServerStyle.prototype.lineWidth=1.0] * @description 边线的宽度。单位为毫米,精度到 0.1。 */ this.lineWidth = 1; /** * @member {number} [ServerStyle.prototype.markerAngle=0] * @description 点状符号的旋转角度。以度为单位,精确到 0.1 度,逆时针方向为正方向。 */ this.markerAngle = 0; /** * @member {number} [ServerStyle.prototype.markerSize=1.0] * @description 点状符号的大小。单位为毫米,精度为 0.1。当该属性设置为0时,采用符号默认大小 1.0 显示。 * 当该属性设置为非法值时,交由服务器默认处理。 */ this.markerSize = 1; /** * @member {number} [ServerStyle.prototype.markerSymbolID=-1] * @description 点状符号的编码。此编码用于唯一标识各点状符号。 * 关于线状符号的样式与对应的 ID 号请在 SuperMap 桌面软件中查找。 */ this.markerSymbolID = -1; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ServerStyle"; } /** * @function ServerStyle.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.fillBackColor) { me.fillBackColor.destroy(); me.fillBackColor = null; } me.fillBackOpaque = null; if (me.fillForeColor) { me.fillForeColor.destroy(); me.fillForeColor = null; } me.fillGradientMode = null; me.fillGradientAngle = null; me.fillGradientOffsetRatioX = null; me.fillGradientOffsetRatioY = null; me.fillOpaqueRate = null; me.fillSymbolID = null; if (me.lineColor) { me.lineColor.destroy(); me.lineColor = null; } me.lineSymbolID = null; me.lineWidth = null; me.markerAngle = null; me.markerSize = null; me.markerSymbolID = null; } /** * @function ServerStyle.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象. */ toServerJSONObject() { var styleObj = {}; styleObj = Util.copyAttributes(styleObj, this); //暂时先忽略serverColor往Json的转换 return styleObj; } /** * @function ServerStyle.fromJson * @description 将JSON对象转换为 ServerStyle 对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 * @returns {ServerStyle} 转化后的 ServerStyle 对象。 */ static fromJson(jsonObject) { if (!jsonObject) { return; } return new ServerStyle({ fillBackColor: ServerColor.fromJson(jsonObject.fillBackColor), fillBackOpaque: jsonObject.fillBackOpaque, fillForeColor: ServerColor.fromJson(jsonObject.fillForeColor), fillGradientMode: jsonObject.fillGradientMode, fillGradientAngle: jsonObject.fillGradientAngle, fillGradientOffsetRatioX: jsonObject.fillGradientOffsetRatioX, fillGradientOffsetRatioY: jsonObject.fillGradientOffsetRatioY, fillOpaqueRate: jsonObject.fillOpaqueRate, fillSymbolID: jsonObject.fillSymbolID, lineColor: ServerColor.fromJson(jsonObject.lineColor), lineSymbolID: jsonObject.lineSymbolID, lineWidth: jsonObject.lineWidth, markerAngle: jsonObject.markerAngle, markerSize: jsonObject.markerSize, markerSymbolID: jsonObject.markerSymbolID }); } } ;// CONCATENATED MODULE: ./src/common/iServer/PointWithMeasure.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class PointWithMeasure * @deprecatedclass SuperMap.PointWithMeasure * @category iServer SpatialAnalyst RouteLocator * @classdesc 路由点类。路由点是指具有线性度量值 (Measure) 的二维地理坐标点。 * @param {Object} options - 参数。 * @param {number} options.measure - 度量值,即路由对象属性值 M。 * @param {number} options.x - 地理坐标系下的 X 坐标值。 * @param {number} options.y - 地理坐标系下的 Y 坐标值。 * @extends {GeometryPoint} * @usage */ class PointWithMeasure extends Point { constructor(options) { super(options); /** * @member {number} PointWithMeasure.prototype.measure * @description 度量值,即路由对象属性值 M。 */ this.measure = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.PointWithMeasure"; } /** * @function PointWithMeasure.prototype.equals * @description 判断两个路由点对象是否相等。如果两个路由点对象具有相同的坐标以及度量值,则认为是相等的。 * @param {PointWithMeasure} geom - 需要判断的路由点对象。 * @returns {boolean} 两个路由点对象是否相等(true 为相等,false 为不等)。 */ equals(geom) { var equals = false; if (geom != null) { var isValueEquals = this.x === geom.x && this.y === geom.y && this.measure === geom.measure; var isNaNValue = isNaN(this.x) && isNaN(this.y) && isNaN(this.measure); var isNaNGeometry = isNaN(geom.x) && isNaN(geom.y) && isNaN(geom.measure); equals = ( isValueEquals || ( isNaNValue && isNaNGeometry )); } return equals; } /** * @function PointWithMeasure.prototype.toJson * @description 转换为 JSON 对象。 * */ toJson() { var result = "{"; if (this.measure != null && this.measure != undefined) { result += "\"measure\":" + this.measure + ","; } result += "\"x\":" + this.x + ","; result += "\"y\":" + this.y; result += "}"; return result; } /** * @function PointWithMeasure.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.measure = null; me.x = null; me.y = null; } /** * @function PointWithMeasure.fromJson * @description 将 JSON 对象转换为{@link PointWithMeasure} 对象。 * @param {Object} jsonObject - JSON 对象表示的路由点。 * @returns {PointWithMeasure} 转化后的 PointWithMeasure 对象。 */ static fromJson(jsonObject) { if (!jsonObject) { return; } return new PointWithMeasure({ x: jsonObject.x, y: jsonObject.y, measure: jsonObject.measure }); } } ;// CONCATENATED MODULE: ./src/common/iServer/Route.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Route * @deprecatedclass SuperMap.Route * @category iServer SpatialAnalyst RouteCalculateMeasure * @classdesc 路由对象类。路由对象为一系列有序的带有属性值 M 的 x,y 坐标对,其中 M 值为该结点的距离属性(到已知点的距离)。 * @param {Array.} points - 形成路由对象的线数组。 * @param {Object} options - 参数。 * @param {number} options.id - 路由对象在数据库中的 ID。 * @param {number} options.length - 路由对象的长度。单位与数据集的单位相同。 * @param {number} [options.maxM] - 最大线性度量值,即所有结点到起始点的量算距离中最大值。 * @param {number} [options.minM] - 最小线性度量值,即所有结点到起始点的量算距离中最小值。 * @param {string} [options.type] - 数据类型,如:"LINEM"。 * @extends GeometryCollection * @usage */ class Route extends Collection { constructor(points, options) { super(points, options); /** * @member {number} Route.prototype.id * @description 路由对象在数据库中的 ID。 */ this.id = null; /** * @member {number} Route.prototype.center * @description 路由对象的中心点。 */ this.center = null; /** * @member {string} Route.prototype.style * @description 路由对象的样式。 */ this.style = null; /** * @member {number} Route.prototype.length * @description 路由对象的长度。单位与数据集的单位相同。 */ this.length = null; /** * @member {number} Route.prototype.maxM * @description 最大线性度量值,即所有结点到起始点的量算距离中最大值。 */ this.maxM = null; /** * @member {number} Route.prototype.minM * @description 最小线性度量值,即所有结点到起始点的量算距离中最小值。 */ this.minM = null; /** * @member {Array.} Route.prototype.parts * @description 服务端几何对象中各个子对象所包含的节点个数。 */ this.parts = null; /** * @member {Array.} Route.prototype.points * @description 路由对象的所有路由点。 * @example * (start code) * [ * { * "measure": 0, * "y": -4377.027184298267, * "x": 4020.0045221720466 * }, * { * "measure": 37.33288381391519, * "y": -4381.569363260499, * "x": 4057.0600591960642 * } * ] * (end) */ this.points = null; /** * @member {string} Route.prototype.type * @description 服务端几何对象类型。 */ this.type = null; /** * @member {Array.} [Route.prototype.componentTypes=LineString] * @description components 存储的几何对象所支持的几何类型数组。 */ this.componentTypes = ["SuperMap.Geometry.LinearRing", "SuperMap.Geometry.LineString"]; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.Route"; this.geometryType = "LINEM"; } /** * * @function Route.prototype.toJson * @description 转换为 JSON 对象。 * @returns {Object} JSON 对象。 */ toJson() { var result = "{"; if (this.id != null && this.id != undefined) { result += "\"id\":" + this.id + ","; } if (this.center != null && this.center != undefined) { result += "\"center\":" + this.center + ","; } if (this.style != null && this.style != undefined) { result += "\"style\":" + this.style + ","; } if (this.length != null && this.length != undefined) { result += "\"length\":" + this.length + ","; } if (this.maxM != null && this.maxM != undefined) { result += "\"maxM\":" + this.maxM + ","; } if (this.minM != null && this.minM != undefined) { result += "\"minM\":" + this.minM + ","; } if (this.type != null && this.type != undefined) { result += "\"type\":\"" + this.type + "\","; } if (this.parts != null && this.parts != undefined) { result += "\"parts\":[" + this.parts[0]; for (var i = 1; i < this.parts.length; i++) { result += "," + this.parts[i]; } result += "],"; } if (this.components != null && this.components.length > 0) { result += "\"points\":["; for (var j = 0, len = this.components.length; j < len; j++) { for (var k = 0, len2 = this.components[j].components.length; k < len2; k++) { result += this.components[j].components[k].toJson() + ","; } } result = result.replace(/,$/g, ''); result += "]"; } result = result.replace(/,$/g, ''); result += "}"; return result; } /** * @function Route.prototype.destroy * @override */ destroy() { var me = this; me.id = null; me.center = null; me.style = null; me.length = null; me.maxM = null; me.minM = null; me.type = null; me.parts = null; me.components.length = 0; me.components = null; me.componentTypes = null; } /** * @function Route.fromJson * @description 将 JSON 对象转换为 Route 对象。 * @param {Object} [jsonObject] - JSON 对象表示的路由对象。 * @returns {Route} 转化后的 Route 对象。 */ static fromJson(jsonObject) { if (!jsonObject) { return; } var geoParts = jsonObject.parts || [], geoPoints = jsonObject.points || [], len = geoParts.length, lineList = []; if (len > 0) { for (var i = 0, pointIndex = 0, pointList = []; i < len; i++) { for (var j = 0; j < geoParts[i]; j++) { pointList.push(PointWithMeasure.fromJson(geoPoints[pointIndex + j])); } pointIndex += geoParts[i]; //判断线是否闭合,如果闭合,则返回LinearRing,否则返回LineString if (pointList[0].equals(pointList[geoParts[i] - 1])) { lineList.push(new LinearRing(pointList)); } else { lineList.push(new LineString(pointList)); } pointList = []; } } else { return null; } return new Route(lineList, { id: jsonObject.id, center: jsonObject.center, style: jsonObject.style, length: jsonObject.length, maxM: jsonObject.maxM, minM: jsonObject.minM, type: jsonObject.type, parts: jsonObject.parts }); } } ;// CONCATENATED MODULE: ./src/common/iServer/ServerGeometry.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ServerGeometry * @deprecatedclass SuperMap.ServerGeometry * @category iServer Data Feature * @classdesc 服务端几何对象类。该类描述几何对象(矢量)的特征数据(坐标点对、几何对象的类型等)。基于服务端的空间分析、空间关系运算、查询等 GIS 服务功能使用服务端几何对象。 * @param {Object} options - 参数。 * @param {string} options.id - 服务端几何对象唯一标识符。 * @param {Array.} options.parts - 服务端几何对象中各个子对象所包含的节点个数。 * @param {Array.} options.points - 组成几何对象的节点的坐标对数组。 * @param {GeometryType} options.type - 几何对象的类型。 * @param {ServerStyle} [options.style] - 服务端几何对象的风格。 * @usage */ class ServerGeometry { constructor(options) { /** * @member {string} ServerGeometry.prototype.id * @description 服务端几何对象唯一标识符。 */ this.id = 0; /** * @member {ServerStyle} [ServerGeometry.prototype.style] * @description 服务端几何对象的风格(ServerStyle)。 */ this.style = null; /** * @member {Array.} ServerGeometry.prototype.parts * @description 服务端几何对象中各个子对象所包含的节点个数。
* 1.几何对象从结构上可以分为简单几何对象和复杂几何对象。 * 简单几何对象与复杂几何对象的区别:简单的几何对象一般为单一对象, * 而复杂的几何对象由多个简单对象组成或经过一定的空间运算之后产生, * 如:矩形为简单的区域对象,而中空的矩形为复杂的区域对象。
* 2.通常情况,一个简单几何对象的子对象就是它本身, * 因此对于简单对象来说的该字段为长度为1的整型数组, * 该字段的值就是这个简单对象节点的个数。 * 如果一个几何对象是由几个简单对象组合而成的, * 例如,一个岛状几何对象由 3 个简单的多边形组成而成, * 那么这个岛状的几何对象的 Parts 字段值就是一个长度为 3 的整型数组, * 数组中每个成员的值分别代表这三个多边形所包含的节点个数。 */ this.parts = null; /** * @member {Array.} ServerGeometry.prototype.points * @description 组成几何对象的节点的坐标对数组。
* 1.所有几何对象(点、线、面)都是由一些简单的点坐标组成的, * 该字段存放了组成几何对象的点坐标的数组。 * 对于简单的面对象,他的起点和终点的坐标点相同。
* 2.对于复杂的几何对象,根据 Parts 属性来确定每一个组成复杂几何对象的简单对象所对应的节点的个数, * 从而确定 Points 字段中坐标对的分配归属问题。 */ this.points = null; /** * @member {GeometryType} ServerGeometry.prototype.type * @description 几何对象的类型(GeometryType)。 */ this.type = null; /** * @member {Object} ServerGeometry.prototype.prjCoordSys * @description 投影坐标参数,现仅在缓冲区分析中有效。 */ this.prjCoordSys = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = 'SuperMap.ServerGeometry'; } /** * @function ServerGeometry.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.id = null; me.style = null; me.parts = null; me.partTopo = null; me.points = null; me.type = null; me.prjCoordSys = null; } /** * @function ServerGeometry.prototype.toGeometry * @description 将服务端几何对象 ServerGeometry 转换为客户端几何对象 Geometry。 * @returns {Geometry} 转换后的客户端几何对象。 */ toGeometry() { var me = this, geoType = me.type; switch (geoType.toUpperCase()) { case REST_GeometryType.POINT: return me.toGeoPoint(); case REST_GeometryType.LINE: return me.toGeoLine(); case REST_GeometryType.LINEM: return me.toGeoLinem(); case REST_GeometryType.REGION: return me.toGeoRegion(); case REST_GeometryType.POINTEPS: return me.toGeoPoint(); case REST_GeometryType.LINEEPS: return me.toGeoLineEPS(); case REST_GeometryType.REGIONEPS: return me.toGeoRegionEPS(); case REST_GeometryType.GEOCOMPOUND: return me.transformGeoCompound(); } } /** * @function ServerGeometry.prototype.toGeoPoint * @description 将服务端的点几何对象转换为客户端几何对象。包括 Point、MultiPoint。 * @returns {Geometry} 转换后的客户端几何对象。 */ toGeoPoint() { var me = this, geoParts = me.parts || [], geoPoints = me.points || [], len = geoParts.length; if (len > 0) { if (len === 1) { return new Point(geoPoints[0].x, geoPoints[0].y); } else { var pointList = []; for (let i = 0; i < len; i++) { pointList.push(new Point(geoPoints[i].x, geoPoints[i].y)); } return new MultiPoint(pointList); } } else { return null; } } /** * @function ServerGeometry.prototype.toGeoLine * @description 将服务端的线几何对象转换为客户端几何对象。包括 GeometryLinearRing、GeometryLineString、GeometryMultiLineString。 * @returns {Geometry} 转换后的客户端几何对象。 */ toGeoLine() { var me = this, geoParts = me.parts || [], geoPoints = me.points || [], len = geoParts.length; if (len > 0) { if (len === 1) { let pointList = []; for (let i = 0; i < geoParts[0]; i++) { pointList.push(new Point(geoPoints[i].x, geoPoints[i].y)); } //判断线是否闭合,如果闭合,则返回LinearRing,否则返回LineString if (pointList[0].equals(pointList[geoParts[0] - 1])) { return new LinearRing(pointList); } else { return new LineString(pointList); } } else { let lineList = []; for (let i = 0; i < len; i++) { let pointList = []; for (let j = 0; j < geoParts[i]; j++) { pointList.push(new Point(geoPoints[j].x, geoPoints[j].y)); } lineList.push(new LineString(pointList)); geoPoints.splice(0, geoParts[i]); } return new MultiLineString(lineList); } } else { return null; } } /** * @function ServerGeometry.prototype.toGeoLineEPS * @description 将服务端的线几何对象转换为客户端几何对象。包括 GeometryLinearRing、GeometryLineString、GeometryMultiLineString。 * @returns {Geometry} 转换后的客户端几何对象。 */ toGeoLineEPS() { var me = this, geoParts = me.parts || [], geoPoints = me.points || [], i, j, pointList, lineList, lineEPS, len = geoParts.length; if (len > 0) { if (len === 1) { for (i = 0, pointList = []; i < geoParts[0]; i++) { pointList.push(new Point(geoPoints[i].x, geoPoints[i].y, geoPoints[i].type)); } //判断线是否闭合,如果闭合,则返回LinearRing,否则返回LineString if (pointList[0].equals(pointList[geoParts[0] - 1])) { lineEPS = LineString.createLineEPS(pointList); return new LinearRing(lineEPS); } else { lineEPS = LineString.createLineEPS(pointList); return new LineString(lineEPS); } } else { for (i = 0, lineList = []; i < len; i++) { for (j = 0, pointList = []; j < geoParts[i]; j++) { pointList.push(new Point(geoPoints[j].x, geoPoints[j].y)); } lineEPS = LineString.createLineEPS(pointList); lineList.push(new LineString(lineEPS)); geoPoints.splice(0, geoParts[i]); } return new MultiLineString(lineList); } } else { return null; } } /** * @function ServerGeometry.prototype.toGeoLinem * @description 将服务端的路由线几何对象转换为客户端几何对象。包括 LinearRing、LineString、MultiLineString。 * @returns {Geometry} 转换后的客户端几何对象。 */ toGeoLinem() { var me = this; return Route.fromJson(me); } /** * @function ServerGeometry.prototype.toGeoRegion * @description 将服务端的面几何对象转换为客户端几何对象。类型为 GeometryPolygon。 * @returns {Geometry} 转换后的客户端几何对象。 */ toGeoRegion() { var me = this, geoParts = me.parts || [], geoTopo = me.partTopo || [], geoPoints = me.points || [], len = geoParts.length; if (len <= 0) { return null; } var polygonArray = []; var pointList = []; if (len == 1) { for (let i = 0; i < geoPoints.length; i++) { pointList.push(new Point(geoPoints[i].x, geoPoints[i].y)); } polygonArray.push(new Polygon([new LinearRing(pointList)])); return new MultiPolygon(polygonArray); } //处理复杂面 var CCWArray = []; var areaArray = []; var polygonArrayTemp = []; var polygonBounds = []; //polyon岛洞标识数组,初始都是岛。 var CCWIdent = []; for (let i = 0, pointIndex = 0; i < len; i++) { for (let j = 0; j < geoParts[i]; j++) { pointList.push(new Point(geoPoints[pointIndex + j].x, geoPoints[pointIndex + j].y)); } pointIndex += geoParts[i]; var polygon = new Polygon([new LinearRing(pointList)]); pointList = []; polygonArrayTemp.push(polygon); if (geoTopo.length === 0) { polygonBounds.push(polygon.getBounds()); } CCWIdent.push(1); areaArray.push(polygon.getArea()); } //iServer 9D新增字段 if (geoTopo.length === 0) { //根据面积排序 ServerGeometry.bubbleSort(areaArray, polygonArrayTemp, geoTopo, polygonBounds); //岛洞底层判断原则:将所有的子对象按照面积排序,面积最大的直接判定为岛(1),从面积次大的开始处理, // 如果发现该对象在某个面积大于它的对象之中(即被包含),则根据包含它的对象的标识(1 or -1),指定其标识(-1 or 1), // 依次处理完所有对象,就得到了一个标识数组,1表示岛,-1表示洞 //目标polygon索引列表 -1标示没有被任何polygon包含, var targetArray = []; for (let i = 1; i < polygonArrayTemp.length; i++) { for (let j = i - 1; j >= 0; j--) { targetArray[i] = -1; if (polygonBounds[j].containsBounds(polygonBounds[i])) { CCWIdent[i] = CCWIdent[j] * -1; if (CCWIdent[i] < 0) { targetArray[i] = j; } break; } } } for (let i = 0; i < polygonArrayTemp.length; i++) { if (CCWIdent[i] > 0) { polygonArray.push(polygonArrayTemp[i]); } else { polygonArray[targetArray[i]].components = polygonArray[targetArray[i]].components.concat( polygonArrayTemp[i].components ); //占位 polygonArray.push(''); } } } else { polygonArray = new Array(); for (let i = 0; i < polygonArrayTemp.length; i++) { if (geoTopo[i] && geoTopo[i] == -1) { CCWArray = CCWArray.concat(polygonArrayTemp[i].components); } else { if (CCWArray.length > 0 && polygonArray.length > 0) { polygonArray[polygonArray.length - 1].components = polygonArray[polygonArray.length - 1].components.concat(CCWArray); CCWArray = []; } polygonArray.push(polygonArrayTemp[i]); } if (i == len - 1) { var polyLength = polygonArray.length; if (polyLength) { polygonArray[polyLength - 1].components = polygonArray[polyLength - 1].components.concat(CCWArray); } else { for (let k = 0, length = CCWArray.length; k < length; k++) { polygonArray.push(new Polygon(CCWArray)); } } } } } return new MultiPolygon(polygonArray); } /** * @function ServerGeometry.prototype.toGeoRegionEPS * @description 将服务端的面几何对象转换为客户端几何对象。类型为 Polygon。 * @returns {Geometry} 转换后的客户端几何对象。 */ toGeoRegionEPS() { var me = this, geoParts = me.parts || [], geoTopo = me.partTopo || [], geoPoints = me.points || [], len = geoParts.length; if (len <= 0) { return null; } var polygonArray = []; var pointList = []; var lineEPS; if (len == 1) { for (var i = 0; i < geoPoints.length; i++) { pointList.push(new Point(geoPoints[i].x, geoPoints[i].y)); } lineEPS = LineString.createLineEPS(pointList); polygonArray.push(new Polygon([new LinearRing(lineEPS)])); return new MultiPolygon(polygonArray); } //处理复杂面 var CCWArray = []; var areaArray = []; var polygonArrayTemp = []; var polygonBounds = []; //polyon岛洞标识数组,初始都是岛。 var CCWIdent = []; for (let i = 0, pointIndex = 0; i < len; i++) { for (let j = 0; j < geoParts[i]; j++) { pointList.push(new Point(geoPoints[pointIndex + j].x, geoPoints[pointIndex + j].y)); } pointIndex += geoParts[i]; lineEPS = LineString.createLineEPS(pointList); var polygon = new Polygon([new LinearRing(lineEPS)]); pointList = []; polygonArrayTemp.push(polygon); if (geoTopo.length === 0) { polygonBounds.push(polygon.getBounds()); } CCWIdent.push(1); areaArray.push(polygon.getArea()); } //iServer 9D新增字段 if (geoTopo.length === 0) { //根据面积排序 ServerGeometry.bubbleSort(areaArray, polygonArrayTemp, geoTopo, polygonBounds); //岛洞底层判断原则:将所有的子对象按照面积排序,面积最大的直接判定为岛(1),从面积次大的开始处理, // 如果发现该对象在某个面积大于它的对象之中(即被包含),则根据包含它的对象的标识(1 or -1),指定其标识(-1 or 1), // 依次处理完所有对象,就得到了一个标识数组,1表示岛,-1表示洞 //目标polygon索引列表 -1标示没有被任何polygon包含, var targetArray = []; for (let i = 1; i < polygonArrayTemp.length; i++) { for (let j = i - 1; j >= 0; j--) { targetArray[i] = -1; if (polygonBounds[j].containsBounds(polygonBounds[i])) { CCWIdent[i] = CCWIdent[j] * -1; if (CCWIdent[i] < 0) { targetArray[i] = j; } break; } } } for (let i = 0; i < polygonArrayTemp.length; i++) { if (CCWIdent[i] > 0) { polygonArray.push(polygonArrayTemp[i]); } else { polygonArray[targetArray[i]].components = polygonArray[targetArray[i]].components.concat( polygonArrayTemp[i].components ); //占位 polygonArray.push(''); } } } else { polygonArray = new Array(); for (let i = 0; i < polygonArrayTemp.length; i++) { if (geoTopo[i] && geoTopo[i] == -1) { CCWArray = CCWArray.concat(polygonArrayTemp[i].components); } else { if (CCWArray.length > 0 && polygonArray.length > 0) { polygonArray[polygonArray.length - 1].components = polygonArray[polygonArray.length - 1].components.concat(CCWArray); CCWArray = []; } polygonArray.push(polygonArrayTemp[i]); } if (i == len - 1) { var polyLength = polygonArray.length; if (polyLength) { polygonArray[polyLength - 1].components = polygonArray[polyLength - 1].components.concat(CCWArray); } else { for (let k = 0, length = CCWArray.length; k < length; k++) { polygonArray.push(new Polygon(CCWArray)); } } } } } return new MultiPolygon(polygonArray); } transformGeoCompound() { const me = this, geoParts = me.geoParts || [], len = geoParts.length; if (len <= 0) { return null; } const geometryList = []; for (let index = 0; index < len; index++) { const geometry = geoParts[index]; geometryList.push(new ServerGeometry(geometry).toGeometry()); } return new Collection(geometryList); } /** * @function ServerGeometry.prototype.fromJson * @description 将 JSON 对象表示服务端几何对象转换为 ServerGeometry。 * @param {Object} jsonObject - 要转换的 JSON 对象。 * @returns {ServerGeometry} 转换后的 ServerGeometry 对象。 */ static fromJson(jsonObject) { if (!jsonObject) { return; } return new ServerGeometry({ id: jsonObject.id, style: ServerStyle.fromJson(jsonObject.style), parts: jsonObject.parts, partTopo: jsonObject.partTopo, points: jsonObject.points, center: jsonObject.center, length: jsonObject.length, maxM: jsonObject.maxM, minM: jsonObject.minM, type: jsonObject.type }); } /** * @function ServerGeometry.prototype.fromGeometry * @description 将客户端 Geometry 转换成服务端 ServerGeometry。 * @param {Geometry} geometry - 要转换的客户端 Geometry 对象。 * @returns {ServerGeometry} 转换后的 ServerGeometry 对象。 */ static fromGeometry(geometry) { if (!geometry) { return; } var id = 0, parts = [], points = [], type = null, icomponents = geometry.components, className = geometry.CLASS_NAME, prjCoordSys = { epsgCode: geometry.SRID }; if (!isNaN(geometry.id)) { id = geometry.id; } //坑爹的改法,没法,为了支持态势标绘,有时间就得全改 if ( className != 'SuperMap.Geometry.LinearRing' && className != 'SuperMap.Geometry.LineString' && (geometry instanceof MultiPoint || geometry instanceof MultiLineString) ) { let ilen = icomponents.length; for (let i = 0; i < ilen; i++) { const vertices = icomponents[i].getVertices(); let partPointsCount = vertices.length; parts.push(partPointsCount); for (let j = 0; j < partPointsCount; j++) { points.push(new Point(vertices[j].x, vertices[j].y)); } } //这里className不是多点就全部是算线 type = className == 'SuperMap.Geometry.MultiPoint' ? REST_GeometryType.POINT : REST_GeometryType.LINE; } else if (geometry instanceof MultiPolygon) { let ilen = icomponents.length; for (let i = 0; i < ilen; i++) { let polygon = icomponents[i], linearRingOfPolygon = polygon.components, linearRingOfPolygonLen = linearRingOfPolygon.length; for (let j = 0; j < linearRingOfPolygonLen; j++) { const vertices = linearRingOfPolygon[j].getVertices(); const partPointsCount = vertices.length + 1; parts.push(partPointsCount); for (let k = 0; k < partPointsCount - 1; k++) { points.push(new Point(vertices[k].x, vertices[k].y)); } points.push( new Point(vertices[0].x, vertices[0].y) ); } } type = REST_GeometryType.REGION; } else if (geometry instanceof Polygon) { let ilen = icomponents.length; for (let i = 0; i < ilen; i++) { const vertices = icomponents[i].getVertices(); let partPointsCount = vertices.length + 1; parts.push(partPointsCount); for (let j = 0; j < partPointsCount - 1; j++) { points.push(new Point(vertices[j].x, vertices[j].y)); } points.push(new Point(vertices[0].x, vertices[0].y)); } type = REST_GeometryType.REGION; } else { const vertices = geometry.getVertices(); let geometryVerticesCount = vertices.length; for (let j = 0; j < geometryVerticesCount; j++) { points.push(new Point(vertices[j].x, vertices[j].y)); } if (geometry instanceof LinearRing) { points.push(new Point(vertices[0].x, vertices[0].y)); geometryVerticesCount++; } parts.push(geometryVerticesCount); type = geometry instanceof Point ? REST_GeometryType.POINT : REST_GeometryType.LINE; } return new ServerGeometry({ id: id, style: null, parts: parts, points: points, type: type, prjCoordSys: prjCoordSys }); } /** * @function ServerGeometry.prototype.IsClockWise * @description 判断 linearRing 中的点的顺序。返回值大于 0,逆时针;小于 0,顺时针。 * @param {Geometry} geometry - 要转换的客户端 Geometry 对象。 * @returns {number} 返回值大于 0,逆时针;小于 0,顺时针。 */ static IsClockWise(points) { var length = points.length; if (length < 3) { return 0.0; } var s = points[0].y * (points[length - 1].x - points[1].x); points.push(points[0]); for (var i = 1; i < length; i++) { s += points[i].y * (points[i - 1].x - points[i + 1].x); } return s * 0.5; } static bubbleSort(areaArray, pointList, geoTopo, polygonBounds) { for (var i = 0; i < areaArray.length; i++) { for (var j = 0; j < areaArray.length; j++) { if (areaArray[i] > areaArray[j]) { var d = areaArray[j]; areaArray[j] = areaArray[i]; areaArray[i] = d; var b = pointList[j]; pointList[j] = pointList[i]; pointList[i] = b; if (geoTopo && geoTopo.length > 0) { var c = geoTopo[j]; geoTopo[j] = geoTopo[i]; geoTopo[i] = c; } if (polygonBounds && polygonBounds.length > 0) { var f = polygonBounds[j]; polygonBounds[j] = polygonBounds[i]; polygonBounds[i] = f; } } } } } } ;// CONCATENATED MODULE: ./src/common/format/GeoJSON.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeoJSONFormat * @aliasclass Format.GeoJSON * @deprecatedclass SuperMap.Format.GeoJSON * @classdesc GeoJSON 的读和写。使用 {@link GeoJSONObject} 构造器创建一个 GeoJSON 解析器。 * @category BaseTypes Format * @param {Object} [options] - 可选参数。 * @param {string} [options.indent=" "] - 用于格式化输出,indent 字符串会在每次缩进的时候使用一次。 * @param {string} [options.space=" "] - 用于格式化输出,space 字符串会在名值对的 ":" 后边添加。 * @param {string} [options.newline="\n"] - 用于格式化输出, newline 字符串会用在每一个名值对或数组项末尾。 * @param {number} [options.level=0] - 用于格式化输出, 表示的是缩进级别。 * @param {boolean} [options.pretty=false] - 是否在序列化的时候使用额外的空格控制结构。在 write 方法中使用。 * @param {boolean} [options.nativeJSON] - 需要被注册的监听器对象。 * @param {boolean} [options.ignoreExtraDims=true] - 忽略维度超过 2 的几何要素。 * @extends {JSONFormat} * @usage */ class GeoJSON extends JSONFormat { constructor(options) { super(options); /** * @member {boolean} [GeoJSONFormat.prototype.ignoreExtraDims=true] * @description 忽略维度超过 2 的几何要素。 */ this.ignoreExtraDims = true; this.CLASS_NAME = "SuperMap.Format.GeoJSON"; /** * @member {Object} GeoJSONFormat.prototype.parseCoords * @private * @description 一个属性名对应着 GeoJSON 对象的几何类型的对象。每个属性其实都是一个实际上做解析用的方法。 */ this.parseCoords = { /** * @function GeoJSONFormat.parseCoords.point * @description 将一组坐标转成一个 {@link Geometry} 对象。 * @param {Object} array - GeoJSON 片段中的一组坐标。 * @returns {Geometry} 一个几何对象。 */ "point": function (array) { if (this.ignoreExtraDims === false && array.length != 2) { throw "Only 2D points are supported: " + array; } return new Point(array[0], array[1]); }, /** * @function GeoJSONFormat.parseCoords.multipoint * @description 将坐标组数组转化成为一个 {@link Geometry} 对象。 * @param {Object} array - GeoJSON 片段中的坐标组数组。 * @returns {Geometry} 一个几何对象。 */ "multipoint": function (array) { var points = []; var p = null; for (var i = 0, len = array.length; i < len; ++i) { try { p = this.parseCoords["point"].apply(this, [array[i]]); } catch (err) { throw err; } points.push(p); } return new MultiPoint(points); }, /** * @function GeoJSONFormat.parseCoords.linestring * @description 将坐标组数组转化成为一个 {@link Geometry} 对象。 * @param {Object} array - GeoJSON 片段中的坐标组数组。 * @returns {Geometry} 一个几何对象。 */ "linestring": function (array) { var points = []; var p = null; for (var i = 0, len = array.length; i < len; ++i) { try { p = this.parseCoords["point"].apply(this, [array[i]]); } catch (err) { throw err; } points.push(p); } return new LineString(points); }, /** * @function GeoJSONFormat.parseCoords.multilinestring * @description 将坐标组数组转化成为一个 {@link Geometry} 对象。 * @param {Object} array - GeoJSON 片段中的坐标组数组。 * @returns {Geometry} 一个几何对象。 */ "multilinestring": function (array) { var lines = []; var l = null; for (var i = 0, len = array.length; i < len; ++i) { try { l = this.parseCoords["linestring"].apply(this, [array[i]]); } catch (err) { throw err; } lines.push(l); } return new MultiLineString(lines); }, /** * @function GeoJSONFormat.parseCoords.polygon * @description 将坐标组数组转化成为一个 {@link Geometry} 对象。 * @returns {Geometry} 一个几何对象。 */ "polygon": function (array) { var rings = []; var r, l; for (var i = 0, len = array.length; i < len; ++i) { try { l = this.parseCoords["linestring"].apply(this, [array[i]]); } catch (err) { throw err; } r = new LinearRing(l.components); rings.push(r); } return new Polygon(rings); }, /** * @function GeoJSONFormat.parseCoords.multipolygon * @description 将坐标组数组转化成为一个 {@link Geometry} 对象。 * @param {Object} array - GeoJSON 片段中的坐标组数组。 * @returns {Geometry} 一个几何对象。 */ "multipolygon": function (array) { var polys = []; var p = null; for (var i = 0, len = array.length; i < len; ++i) { try { p = this.parseCoords["polygon"].apply(this, [array[i]]); } catch (err) { throw err; } polys.push(p); } return new MultiPolygon(polys); }, /** * @function GeoJSONFormat.parseCoords.box * @description 将坐标组数组转化成为一个 {@link Geometry} 对象。 * @param {Array} array - GeoJSON 片段中的坐标组数组。 * @returns {Geometry} 一个几何对象。 */ "box": function (array) { if (array.length != 2) { throw "GeoJSON box coordinates must have 2 elements"; } return new Polygon([ new LinearRing([ new Point(array[0][0], array[0][1]), new Point(array[1][0], array[0][1]), new Point(array[1][0], array[1][1]), new Point(array[0][0], array[1][1]), new Point(array[0][0], array[0][1]) ]) ]); } }; /** * @member {Object} GeoJSONFormat.prototype.extract * @private * @description 一个属性名对应着GeoJSON类型的对象。其值为相应的实际的解析方法。 */ this.extract = { /** * @function GeoJSONFormat.extract.feature * @description 返回一个表示单个要素对象的 GeoJSON 的一部分。 * @param {SuperMap.ServerFeature} feature - iServer 要素对象。 * @returns {Object} 一个表示点的对象。 */ 'feature': function (feature) { var geom = this.extract.geometry.apply(this, [feature.geometry]); var json = { "type": "Feature", "properties": this.createAttributes(feature), "geometry": geom }; if (feature.geometry && feature.geometry.type === 'TEXT') { json.properties.texts = feature.geometry.texts; json.properties.textStyle = feature.geometry.textStyle; } if (feature.fid) { json.id = feature.fid; } if (feature.ID) { json.id = feature.ID; } return json; }, /** * @function GeoJSONFormat.extract.geometry * @description 返回一个表示单个几何对象的 GeoJSON 的一部分。 * @param {Object} geometry - iServer 几何对象。 * @returns {Object} 一个表示几何体的对象。 */ 'geometry': function (geometry) { if (geometry == null) { return null; } if (!geometry.parts && geometry.points) { geometry.parts = [geometry.points.length]; } var geo = geometry.hasOwnProperty('geometryType') ? geometry : new ServerGeometry(geometry).toGeometry() || geometry; var geometryType = geo.geometryType || geo.type; var data; if (geometryType === "LinearRing") { geometryType = "LineString"; } if (geometryType === "LINEM") { geometryType = "MultiLineString"; } data = this.extract[geometryType.toLowerCase()].apply(this, [geo]); geometryType = geometryType === 'TEXT' ? 'Point' : geometryType; var json; if (geometryType === "Collection") { json = { "type": "GeometryCollection", "geometries": data }; } else { json = { "type": geometryType, "coordinates": data }; } return json; }, /** * @function GeoJSONFormat.extract.point * @description 从一个点对象中返回一个坐标组。 * @param {GeometryPoint} point - 一个点对象。 * @returns {Array} 一个表示一个点的坐标组。 */ 'point': function (point) { var p = [point.x, point.y]; for (var name in point) { if (name !== "x" && name !== "y" && point[name] !== null && !isNaN(point[name])) { p.push(point[name]); } } return p; }, /** * @function GeoJSONFormat.extract.point * @description 从一个文本对象中返回一个坐标组。 * @param {Object} geo - 一个文本对象。 * @returns {Array} 一个表示一个点的坐标组。 */ 'text': function (geo) { return [geo.points[0].x, geo.points[0].y]; }, /** * @function GeoJSONFormat.extract.multipoint * @description 从一个多点对象中返一个坐标组数组。 * @param {GeometryMultiPoint} multipoint - 多点对象。 * @returns {Array} 一个表示多点的坐标组数组。 */ 'multipoint': function (multipoint) { var array = []; for (var i = 0, len = multipoint.components.length; i < len; ++i) { array.push(this.extract.point.apply(this, [multipoint.components[i]])); } return array; }, /** * @function GeoJSONFormat.extract.linestring * @description 从一个线对象中返回一个坐标组数组。 * @param {Linestring} linestring - 线对象。 * @returns {Array} 一个表示线对象的坐标组数组。 */ 'linestring': function (linestring) { var array = []; for (var i = 0, len = linestring.components.length; i < len; ++i) { array.push(this.extract.point.apply(this, [linestring.components[i]])); } return array; }, /** * @function GeoJSONFormat.extract.multilinestring * @description 从一个多线对象中返回一个线数组。 * @param {GeometryMultiLineString} multilinestring - 多线对象。 * * @returns {Array} 一个表示多线的线数组。 */ 'multilinestring': function (multilinestring) { var array = []; for (var i = 0, len = multilinestring.components.length; i < len; ++i) { array.push(this.extract.linestring.apply(this, [multilinestring.components[i]])); } return array; }, /** * @function GeoJSONFormat.extract.polygon * @description 从一个面对象中返回一组线环。 * @param {GeometryPolygon} polygon - 面对象。 * @returns {Array} 一组表示面的线环。 */ 'polygon': function (polygon) { var array = []; for (var i = 0, len = polygon.components.length; i < len; ++i) { array.push(this.extract.linestring.apply(this, [polygon.components[i]])); } return array; }, /** * @function GeoJSONFormat.extract.multipolygon * @description 从一个多面对象中返回一组面。 * @param {GeometryMultiPolygon} multipolygon - 多面对象。 * @returns {Array} 一组表示多面的面。 */ 'multipolygon': function (multipolygon) { var array = []; for (var i = 0, len = multipolygon.components.length; i < len; ++i) { array.push(this.extract.polygon.apply(this, [multipolygon.components[i]])); } return array; }, /** * @function GeoJSONFormat.extract.collection * @description 从一个几何要素集合中一组几何要素数组。 * @param {GeometryCollection} collection - 几何要素集合。 * @returns {Array} 一组表示几何要素集合的几何要素数组。 */ 'collection': function (collection) { var len = collection.components.length; var array = new Array(len); for (var i = 0; i < len; ++i) { array[i] = this.extract.geometry.apply(this, [collection.components[i]]); } return array; } }; } /** * @function GeoJSONFormat.prototype.read * @description 将 GeoJSON 对象或者GeoJSON 对象字符串转换为 SuperMap Feature 对象。 * @param {GeoJSONObject} json - GeoJSON 对象。 * @param {string} [type='FeaureCollection'] - 可选的字符串,它决定了输出的格式。支持的值有:"Geometry","Feature",和 "FeatureCollection",如果此值为null。 * @param {function} filter - 对象中每个层次每个键值对都会调用此函数得出一个结果。每个值都会被 filter 函数的结果所替换掉。这个函数可被用来将某些对象转化成某个类相应的对象,或者将日期字符串转化成Date对象。 * @returns {Object} 返回值依赖于 type 参数的值。 * -如果 type 等于 "FeatureCollection",返回值将会是 {@link FeatureVector} 数组。 * -如果 type 为 "Geometry",输入的 JSON 对象必须表示一个唯一的几何体,然后返回值就会是 {@link Geometry}。 * -如果 type 为 "Feature",输入的 JSON 对象也必须表示的一个要素,这样返回值才会是 {@link FeatureVector}。 */ read(json, type, filter) { type = (type) ? type : "FeatureCollection"; var results = null; var obj = null; if (typeof json == "string") { obj = super.read(json, filter); } else { obj = json; } if (!obj) { //console.error("Bad JSON: " + json); } else if (typeof (obj.type) != "string") { //console.error("Bad GeoJSON - no type: " + json); } else if (this.isValidType(obj, type)) { switch (type) { case "Geometry": try { results = this.parseGeometry(obj); } catch (err) { //console.error(err); } break; case "Feature": try { results = this.parseFeature(obj); results.type = "Feature"; } catch (err) { //console.error(err); } break; case "FeatureCollection": // for type FeatureCollection, we allow input to be any type results = []; switch (obj.type) { case "Feature": try { results.push(this.parseFeature(obj)); } catch (err) { results = null; //console.error(err); } break; case "FeatureCollection": for (var i = 0, len = obj.features.length; i < len; ++i) { try { results.push(this.parseFeature(obj.features[i])); } catch (err) { results = null; // console.error(err); } } break; default: try { var geom = this.parseGeometry(obj); results.push(new Vector(geom)); } catch (err) { results = null; //console.error(err); } } break; default: break; } } return results; } /** * @function GeoJSONFormat.prototype.write * @description iServer Geometry JSON 对象 转 GeoJSON对象字符串。 * @param {Object} obj - iServer Geometry JSON 对象。 * @param {boolean} [pretty=false] - 是否使用换行和缩进来控制输出。 * @returns {GeoJSONObject} 一个 GeoJSON 字符串,它表示了输入的几何对象,要素对象,或者要素对象数组。 */ write(obj, pretty) { return super.write(this.toGeoJSON(obj), pretty); } /** * @function GeoJSONFormat.prototype.fromGeoJSON * @version 9.1.1 * @description 将 GeoJSON 对象或者GeoJSON 对象字符串转换为iServer Feature JSON。 * @param {GeoJSONObject} json - GeoJSON 对象。 * @param {string} [type='FeaureCollection'] - 可选的字符串,它决定了输出的格式。支持的值有:"Geometry","Feature",和 "FeatureCollection",如果此值为null。 * @param {function} filter - 对象中每个层次每个键值对都会调用此函数得出一个结果。每个值都会被 filter 函数的结果所替换掉。这个函数可被用来将某些对象转化成某个类相应的对象,或者将日期字符串转化成Date对象。 * @returns {Object} iServer Feature JSON。 */ fromGeoJSON(json, type, filter) { let feature = this.read(json, type, filter); if (!Util.isArray(feature)) { return this._toiSevrerFeature(feature); } return feature.map((element) => { return this._toiSevrerFeature(element); }) } /** * @function GeoJSONFormat.prototype.toGeoJSON * @version 9.1.1 * @description 将 iServer Feature JSON 对象转换为 GeoJSON 对象。 * @param {Object} obj - iServer Feature JSON。 * @returns {GeoJSONObject} GeoJSON 对象。 */ toGeoJSON(obj) { var geojson = { "type": null }; if (Util.isArray(obj)) { geojson.type = "FeatureCollection"; var numFeatures = obj.length; geojson.features = new Array(numFeatures); for (var i = 0; i < numFeatures; ++i) { var element = obj[i]; if (isGeometry(element)) { let feature = {}; feature.geometry = element; geojson.features[i] = this.extract.feature.apply(this, [feature]); } else { geojson.features[i] = this.extract.feature.apply(this, [element]); } } } else if (isGeometry(obj)) { let feature = {}; feature.geometry = obj; geojson = this.extract.feature.apply(this, [feature]); } else { geojson = this.extract.feature.apply(this, [obj]); } function isGeometry(input) { return (input.hasOwnProperty("parts") && input.hasOwnProperty("points")) || input.hasOwnProperty("geoParts"); } return geojson; } /** * @function GeoJSONFormat.prototype.isValidType * @description 检查一个 GeoJSON 对象是否和给定的类型相符的合法的对象。 * @returns {boolean} GeoJSON 是否是给定类型的合法对象。 * @private */ isValidType(obj, type) { var valid = false; switch (type) { case "Geometry": if (Util.indexOf( ["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "Box", "GeometryCollection" ], obj.type) == -1) { // unsupported geometry type //console.error("Unsupported geometry type: " + // obj.type); } else { valid = true; } break; case "FeatureCollection": // allow for any type to be converted to a feature collection valid = true; break; default: // for Feature types must match if (obj.type == type) { valid = true; } else { //console.error("Cannot convert types from " + //obj.type + " to " + type); } } return valid; } /** * @function GeoJSONFormat.prototype.parseFeature * @description 将一个 GeoJSON 中的 feature 转化成 {@link FeatureVector}> 对象。 * @private * @param {GeoJSONObject} obj - 从 GeoJSON 对象中创建一个对象。 * @returns {FeatureVector} 一个要素。 */ parseFeature(obj) { var feature, geometry, attributes, bbox; attributes = (obj.properties) ? obj.properties : {}; bbox = (obj.geometry && obj.geometry.bbox) || obj.bbox; try { geometry = this.parseGeometry(obj.geometry); } catch (err) { // deal with bad geometries throw err; } feature = new Vector(geometry, attributes); if (bbox) { feature.bounds = Bounds.fromArray(bbox); } if (obj.id) { feature.geometry.id = obj.id; feature.fid = obj.id; } return feature; } /** * @function GeoJSONFormat.prototype.parseGeometry * @description 将一个 GeoJSON 中的几何要素转化成 {@link Geometry} 对象。 * @param {GeoJSONObject} obj - 从 GeoJSON 对象中创建一个对象。 * @returns {Geometry} 一个几何要素。 * @private */ parseGeometry(obj) { if (obj == null) { return null; } var geometry; if (obj.type == "GeometryCollection") { if (!(Util.isArray(obj.geometries))) { throw "GeometryCollection must have geometries array: " + obj; } var numGeom = obj.geometries.length; var components = new Array(numGeom); for (var i = 0; i < numGeom; ++i) { components[i] = this.parseGeometry.apply( this, [obj.geometries[i]] ); } geometry = new Collection(components); } else { if (!(Util.isArray(obj.coordinates))) { throw "Geometry must have coordinates array: " + obj; } if (!this.parseCoords[obj.type.toLowerCase()]) { throw "Unsupported geometry type: " + obj.type; } try { geometry = this.parseCoords[obj.type.toLowerCase()].apply( this, [obj.coordinates] ); } catch (err) { // deal with bad coordinates throw err; } } return geometry; } /** * @function GeoJSONFormat.prototype.createCRSObject * @description 从一个要素对象中创建一个坐标参考系对象。 * @param {FeatureVector} object - 要素对象。 * @private * @returns {GeoJSONObject} 一个可作为 GeoJSON 对象的 CRS 属性使用的对象。 */ createCRSObject(object) { var proj = object.layer.projection.toString(); var crs = {}; if (proj.match(/epsg:/i)) { var code = parseInt(proj.substring(proj.indexOf(":") + 1)); if (code == 4326) { crs = { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }; } else { crs = { "type": "name", "properties": { "name": "EPSG:" + code } }; } } return crs; } _toiSevrerFeature(feature) { const attributes = feature.attributes; const attrNames = []; const attrValues = []; for (var attr in attributes) { attrNames.push(attr); attrValues.push(attributes[attr]); } const newFeature = { fieldNames: attrNames, fieldValues: attrValues, geometry: ServerGeometry.fromGeometry(feature.geometry) }; newFeature.geometry.id = feature.fid; return newFeature; } createAttributes(feature) { if (!feature) { return null; } var attr = {}; processFieldsAttributes(feature, attr); var exceptKeys = ["fieldNames", "fieldValues", "geometry", "stringID", "ID"]; for (var key in feature) { if (exceptKeys.indexOf(key) > -1) { continue; } attr[key] = feature[key]; } function processFieldsAttributes(feature, attributes) { if (!(feature.hasOwnProperty("fieldNames") && feature.hasOwnProperty("fieldValues"))) { return; } var names = feature.fieldNames, values = feature.fieldValues; for (var i in names) { attributes[names[i]] = values[i]; } } return attr; } } ;// CONCATENATED MODULE: ./src/common/format/WKT.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WKTFormat * @aliasclass Format.WKT * @deprecatedclass SuperMap.Format.WKT * @classdesc 用于读写常见文本的类。通过 {@link WKTFormat} 构造器来创建一个新的实例。 * @category BaseTypes Format * @extends {Format} * @param {Object} options - 可选的选项对象,其属性将被设置到实例。option 具体配置项继承自 {@link Format}。 * @usage */ class WKT extends Format { constructor(options) { super(options); this.regExes = { 'typeStr': /^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/, 'spaces': /\s+/, 'parenComma': /\)\s*,\s*\(/, 'doubleParenComma': /\)\s*\)\s*,\s*\(\s*\(/, // can't use {2} here 'trimParens': /^\s*\(?(.*?)\)?\s*$/ }; this.CLASS_NAME = "SuperMap.Format.WKT"; /** * @private * @description Object with properties corresponding to the geometry types. * Property values are functions that do the actual data extraction. */ this.extract = { /** * @description Return a space delimited string of point coordinates. * @param {GeometryPoint} point * @returns {string} A string of coordinates representing the point */ 'point': function (point) { return point.x + ' ' + point.y; }, /** * @description Return a comma delimited string of point coordinates from a multipoint. * @param {GeometryMultiPoint} multipoint * @returns {string} A string of point coordinate strings representing * the multipoint */ 'multipoint'(multipoint) { var array = []; for (var i = 0, len = multipoint.components.length; i < len; ++i) { array.push('(' + this.extract.point.apply(this, [multipoint.components[i]]) + ')'); } return array.join(','); }, /** * @description Return a comma delimited string of point coordinates from a line. * @param {GeometryLineString} linestring * @returns {string} A string of point coordinate strings representing * the linestring */ 'linestring'(linestring) { var array = []; for (var i = 0, len = linestring.components.length; i < len; ++i) { array.push(this.extract.point.apply(this, [linestring.components[i]])); } return array.join(','); }, /** * @description Return a comma delimited string of linestring strings from a multilinestring. * @param {GeometryMultiLineString} multilinestring * @returns {string} A string of of linestring strings representing * the multilinestring */ 'multilinestring'(multilinestring) { var array = []; for (var i = 0, len = multilinestring.components.length; i < len; ++i) { array.push('(' + this.extract.linestring.apply(this, [multilinestring.components[i]]) + ')'); } return array.join(','); }, /** * @description Return a comma delimited string of linear ring arrays from a polygon. * @param {GeometryPolygon} polygon * @returns {string} An array of linear ring arrays representing the polygon */ 'polygon'(polygon) { var array = []; for (var i = 0, len = polygon.components.length; i < len; ++i) { array.push('(' + this.extract.linestring.apply(this, [polygon.components[i]]) + ')'); } return array.join(','); }, /** * @description Return an array of polygon arrays from a multipolygon. * @param {GeometryMultiPolygon} multipolygon * @returns {string} An array of polygon arrays representing * the multipolygon */ 'multipolygon'(multipolygon) { var array = []; for (var i = 0, len = multipolygon.components.length; i < len; ++i) { array.push('(' + this.extract.polygon.apply(this, [multipolygon.components[i]]) + ')'); } return array.join(','); }, /** * @description Return the WKT portion between 'GEOMETRYCOLLECTION(' and ')' for an * @param {GeometryCollection} collection * @returns {string} internal WKT representation of the collection */ 'collection'(collection) { var array = []; for (var i = 0, len = collection.components.length; i < len; ++i) { array.push(this.extractGeometry.apply(this, [collection.components[i]])); } return array.join(','); } }; /** * @private * @description Object with properties corresponding to the geometry types. * Property values are functions that do the actual parsing. */ this.parse = { /** * @private * @description Return point feature given a point WKT fragment. * @param {string} str A WKT fragment representing the point * @returns {FeatureVector} A point feature * */ 'point': function (str) { var coords = StringExt.trim(str).split(this.regExes.spaces); return new Vector(new Point(coords[0], coords[1]) ); }, /** * @description Return a multipoint feature given a multipoint WKT fragment. * @param {string} A WKT fragment representing the multipoint * @returns {FeatureVector} A multipoint feature * @private */ 'multipoint': function (str) { var point; var points = StringExt.trim(str).split(','); var components = []; for (var i = 0, len = points.length; i < len; ++i) { point = points[i].replace(this.regExes.trimParens, '$1'); components.push(this.parse.point.apply(this, [point]).geometry); } return new Vector( new MultiPoint(components) ); }, /** * @description Return a linestring feature given a linestring WKT fragment. * @param {string} A WKT fragment representing the linestring * @returns {FeatureVector} A linestring feature * @private */ 'linestring': function (str) { var points = StringExt.trim(str).split(','); var components = []; for (var i = 0, len = points.length; i < len; ++i) { components.push(this.parse.point.apply(this, [points[i]]).geometry); } return new Vector( new LineString(components) ); }, /** * @description Return a multilinestring feature given a multilinestring WKT fragment. * @param {string} A WKT fragment representing the multilinestring * @returns {FeatureVector} A multilinestring feature * @private */ 'multilinestring': function (str) { var line; var lines = StringExt.trim(str).split(this.regExes.parenComma); var components = []; for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i].replace(this.regExes.trimParens, '$1'); components.push(this.parse.linestring.apply(this, [line]).geometry); } return new Vector( new MultiLineString(components) ); }, /** * @description Return a polygon feature given a polygon WKT fragment. * @param {string} A WKT fragment representing the polygon * @returns {FeatureVector} A polygon feature * @private */ 'polygon': function (str) { var ring, linestring, linearring; var rings = StringExt.trim(str).split(this.regExes.parenComma); var components = []; for (var i = 0, len = rings.length; i < len; ++i) { ring = rings[i].replace(this.regExes.trimParens, '$1'); linestring = this.parse.linestring.apply(this, [ring]).geometry; linearring = new LinearRing(linestring.components); components.push(linearring); } return new Vector( new Polygon(components) ); }, /** * @private * @description Return a multipolygon feature given a multipolygon WKT fragment. * @param {string} A WKT fragment representing the multipolygon * @returns {FeatureVector} A multipolygon feature * */ 'multipolygon': function (str) { var polygon; var polygons = StringExt.trim(str).split(this.regExes.doubleParenComma); var components = []; for (var i = 0, len = polygons.length; i < len; ++i) { polygon = polygons[i].replace(this.regExes.trimParens, '$1'); components.push(this.parse.polygon.apply(this, [polygon]).geometry); } return new Vector( new MultiPolygon(components) ); }, /** * @description Return an array of features given a geometrycollection WKT fragment. * @param {string} A WKT fragment representing the geometrycollection * @returns {Array} An array of FeatureVector * @private */ 'geometrycollection': function (str) { // separate components of the collection with | str = str.replace(/,\s*([A-Za-z])/g, '|$1'); var wktArray = StringExt.trim(str).split('|'); var components = []; for (var i = 0, len = wktArray.length; i < len; ++i) { components.push(this.read(wktArray[i])); } return components; } }; } /** * @function WKTFormat.prototype.read * @description 反序列化 WKT 字符串并返回向量特征或向量特征数组。支持 POINT、MULTIPOINT、LINESTRING、MULTILINESTRING、POLYGON、MULTIPOLYGON 和 GEOMETRYCOLLECTION 的 WKT。 * @param {string} wkt - WKT 字符串。 * @returns {FeatureVector|Array} GEOMETRYCOLLECTION WKT 的矢量要素或者矢量要素数组。 */ read(wkt) { var features, type, str; wkt = wkt.replace(/[\n\r]/g, " "); var matches = this.regExes.typeStr.exec(wkt); if (matches) { type = matches[1].toLowerCase(); str = matches[2]; if (this.parse[type]) { features = this.parse[type].apply(this, [str]); } } return features; } /** * @function WKTFormat.prototype.write * @description 将矢量要素或矢量要素数组序列化为 WKT 字符串。 * @param {(FeatureVector|Array)} features - 矢量要素或矢量要素数组。 * @returns {string} 表示几何的 WKT 字符串。 */ write(features) { var collection, geometry, isCollection; if (features.constructor === Array) { collection = features; isCollection = true; } else { collection = [features]; isCollection = false; } var pieces = []; if (isCollection) { pieces.push('GEOMETRYCOLLECTION('); } for (var i = 0, len = collection.length; i < len; ++i) { if (isCollection && i > 0) { pieces.push(','); } geometry = collection[i].geometry; pieces.push(this.extractGeometry(geometry)); } if (isCollection) { pieces.push(')'); } return pieces.join(''); } /** * @function WKTFormat.prototype.extractGeometry * @description 为单个 Geometry 对象构造 WKT 的入口点。 * @param {Geometry} geometry - Geometry 对象。 * @returns {string} 表示几何的 WKT 字符串。 */ extractGeometry(geometry) { var type = geometry.CLASS_NAME.split('.')[2].toLowerCase(); if (!this.extract[type]) { return null; } var wktType = type === 'collection' ? 'GEOMETRYCOLLECTION' : type.toUpperCase(); var data = wktType + '(' + this.extract[type].apply(this, [geometry]) + ')'; return data; } } ;// CONCATENATED MODULE: ./src/common/format/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/control/TimeControlBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TimeControlBase * @deprecatedclass SuperMap.TimeControlBase * @classdesc 时间控制基类。 * @category Control * @param {Object} options - 可选参数。 * @param {number} [options.speed=1] - 速度。不能小于 0,(每帧渲染的数据之间的间隔为1),设置越大速度越快。 * @param {number} [options.frequency=1000] - 刷新频率(单位 ms),服务器刷新的时间间隔。 * @param {number} [options.startTime=0] - 起始时间,必须为数字,且小于等于 endTime。如果不设置,初始化时为 0,建议设置。 * @param {number} [options.endTime] - 结束时间,必须为数字,且大于等于 startTime。如果不设置,初始化时以当前时间进行设置,建议设置。 * @param {boolean} [options.repeat=true] - 是否重复循环。 * @param {boolean} [options.reverse=false] - 是否反向。 * @usage */ class TimeControlBase { constructor(options) { //设置步长,刷新频率、开始结束时间、是否循环、是否反向 var me = this; options = options || {}; /** * @member {number} [TimeControlBase.prototype.speed=1] * @description 步长,必须为非负数,默认为1(表示前后两次渲染的数据之间的间隔为1)。 */ this.speed = (options.speed && options.speed >= 0) ? options.speed : 1; /** * @member {number} [TimeControlBase.prototype.frequency=1000] * @description 刷新频率(单位ms),服务器刷新的时间间隔。 */ this.frequency = (options.speed && options.frequency >= 0) ? options.frequency : 1000; /** * @member {number} [TimeControlBase.prototype.startTime=0] * @description 记录的起始时间,必须为数字, * 如果不设置,初始化时为0,建议设置。 */ this.startTime = (options.startTime && options.startTime != null) ? options.startTime : 0; /** * @member {number} TimeControlBase.prototype.endTime * @description 记录的结束时间,必须为数字, * 如果不设置,初始化时以当前时间进行设置,建议设置。 */ this.endTime = (options.endTime && options.endTime != null && options.endTime >= me.startTime) ? options.endTime : +new Date(); /** * @member {boolean} [TimeControlBase.prototype.repeat=true] * @description 是否重复循环。 */ this.repeat = (options.repeat !== undefined) ? options.repeat : true; /** * @member {boolean} [TimeControlBase.prototype.reverse=false] * @description 是否反向。 */ this.reverse = (options.reverse !== undefined) ? options.reverse : false; /** * @member {number} TimeControlBase.prototype.currentTime * @description 记录近期的时间,也就是当前帧运行到的时间。 */ this.currentTime = null; /** * @member {number} TimeControlBase.prototype.oldTime * @description 记录上一帧的时间,也就是之前运行到的时间。 */ this.oldTime = null; /** * @member {boolean} [TimeControlBase.prototype.running=false] * @description 记录当前是否处于运行中。 */ this.running = false; /** * @private * @member {Array.} TimeControlBase.prototype.EVENT_TYPES * @description 此类支持的事件类型。 * */ this.EVENT_TYPES = ["start", "pause", "stop"]; /** * @private * @member {Events} TimeControlBase.prototype.events * @description 事件 */ me.events = new Events(this, null, this.EVENT_TYPES); me.speed = Number(me.speed); me.frequency = Number(me.frequency); me.startTime = Number(me.startTime); me.endTime = Number(me.endTime); me.startTime = Date.parse(new Date(me.startTime)); me.endTime = Date.parse(new Date(me.endTime)); //初始化当前时间 me.currentTime = me.startTime; this.CLASS_NAME = "SuperMap.TimeControlBase"; } /** * @function TimeControlBase.prototype.updateOptions * @description 更新参数。 * @param {Object} options - 设置参数的可选参数。设置步长,刷新频率、开始结束时间、是否循环、是否反向。 */ updateOptions(options) { //设置步长,刷新频率、开始结束时间、是否循环、是否反向 var me = this; options = options || {}; if (options.speed && options.speed >= 0) { me.speed = options.speed; me.speed = Number(me.speed); } if (options.speed && options.frequency >= 0) { me.frequency = options.frequency; me.frequency = Number(me.frequency); } if (options.startTime && options.startTime != null) { me.startTime = options.startTime; me.startTime = Date.parse(new Date(me.startTime)); } if (options.endTime && options.endTime != null && options.endTime >= me.startTime) { me.endTime = options.endTime; me.endTime = Date.parse(new Date(me.endTime)); } if (options.repeat != null) { me.repeat = options.repeat; } if (options.reverse != null) { me.reverse = options.reverse; } } /** * @function TimeControlBase.prototype.start * @description 开始。 */ start() { var me = this; if (!me.running) { me.running = true; me.tick(); me.events.triggerEvent('start', me.currentTime); } } /** * @function TimeControlBase.prototype.pause * @description 暂停。 */ pause() { var me = this; me.running = false; me.events.triggerEvent('pause', me.currentTime); } /** * @function TimeControlBase.prototype.stop * @description 停止,停止后返回起始状态。 */ stop() { var me = this; //停止时 时间设置为开始时间 me.currentTime = me.startTime; //如果正在运行,修改为初始时间即可绘制一帧 if (me.running) { me.running = false; } me.events.triggerEvent('stop', me.currentTime); } /** * @function TimeControlBase.prototype.toggle * @description 开关切换,切换的是开始和暂停。 */ toggle() { var me = this; if (me.running) { me.pause(); } else { me.start(); } } /** * @function TimeControlBase.prototype.setSpeed * @description 设置步长。 * @param {number} [speed=1] - 步长,必须为非负数。 * @returns {boolean} true 代表设置成功,false 设置失败(speed 小于 0 时失败)。 */ setSpeed(speed) { var me = this; if (speed >= 0) { me.speed = speed; return true; } return false; } /** * @function TimeControlBase.prototype.getSpeed * @description 获取步长。 * @returns {number} 返回当前的步长。 */ getSpeed() { return this.speed; } /** * @function TimeControlBase.prototype.setFrequency * @description 设置刷新频率。 * @param {number} [frequency=1000] - 刷新频率,单位为 ms。 * @returns {boolean} true 代表设置成功,false 设置失败(frequency 小于 0 时失败)。 */ setFrequency(frequency) { var me = this; if (frequency >= 0) { me.frequency = frequency; return true; } return false; } /** * @function TimeControlBase.prototype.getFrequency * @description 获取刷新频率。 * @returns {number} 返回当前的刷新频率。 */ getFrequency() { return this.frequency; } /** * @function TimeControlBase.prototype.setStartTime * @description 设置起始时间,设置完成后如果当前时间小于起始时间,则从起始时间开始。 * @param {number} startTime - 需要设置的起始时间。 * @returns {boolean} true 代表设置成功,false 设置失败(startTime 大于结束时间时失败)。 */ setStartTime(startTime) { var me = this; startTime = Date.parse(new Date(startTime)); //起始时间不得大于结束时间 if (startTime > me.endTime) { return false; } me.startTime = startTime; //如果当前时间小于了起始时间,则从当前起始时间开始 if (me.currentTime < me.startTime) { me.currentTime = me.startTime; me.tick(); } return true; } /** * @function TimeControlBase.prototype.getStartTime * @description 获取起始时间。 * @returns {number} 返回当前的起始时间。 */ getStartTime() { return this.startTime; } /** * @function TimeControlBase.prototype.setEndTime * @description 设置结束时间,设置完成后如果当前时间大于结束,则从起始时间开始。 * @param {number} endTime - 需要设置的结束时间。 * @returns {boolean} true 代表设置成功,false 设置失败(endTime 小于开始时间时失败)。 */ setEndTime(endTime) { var me = this; me.endTime = Date.parse(new Date(me.endTime)); //结束时间不得小于开始时间 if (endTime < me.startTime) { return false; } me.endTime = endTime; //如果当前时间大于了结束时间,则从起始时间开始 if (me.currentTime >= me.endTime) { me.currentTime = me.startTime; me.tick(); } return true; } /** * @function TimeControlBase.prototype.getEndTime * @description 获取结束时间。 * @returns {number} 返回当前的结束时间。 */ getEndTime() { return this.endTime; } /** * @function TimeControlBase.prototype.setCurrentTime * @description 设置当前时间。 * @param {number} currentTime - 需要设置的当前时间。 * @returns {boolean} true 代表设置成功,false 设置失败。 */ setCurrentTime(currentTime) { var me = this; me.currentTime = Date.parse(new Date(me.currentTime)); //结束时间不得小于开始时间 if (currentTime >= me.startTime && currentTime <= me.endTime) { me.currentTime = currentTime; me.startTime = me.currentTime; me.tick(); return true; } return false; } /** * @function TimeControlBase.prototype.getCurrentTime * @description 获取当前时间。 * @returns {number} 返回当前时间。 */ getCurrentTime() { return this.currentTime; } /** * @function TimeControlBase.prototype.setRepeat * @description 设置是否重复循环。 * @param {boolean} [repeat=true] - 是否重复循环。 */ setRepeat(repeat) { this.repeat = repeat; } /** * @function TimeControlBase.prototype.getRepeat * @description 获取是否重复循环,默认是 true。 * @returns {boolean} 返回是否重复循环。 */ getRepeat() { return this.repeat; } /** * @function TimeControlBase.prototype.setReverse * @description 设置是否反向。 * @param {boolean} [reverse=false] - 是否反向。 */ setReverse(reverse) { this.reverse = reverse; } /** * @function TimeControlBase.prototype.getReverse * @description 获取是否反向,默认是false。 * @returns {boolean} 返回是否反向。 */ getReverse() { return this.reverse; } /** * @function TimeControlBase.prototype.getRunning * @description 获取运行状态。 * @returns {boolean} true 代表正在运行,false 发表没有运行。 */ getRunning() { return this.running; } /** * @function TimeControlBase.prototype.destroy * @description 销毁 Animator 对象,释放资源。 */ destroy() { var me = this; me.speed = null; me.frequency = null; me.startTime = null; me.endTime = null; me.currentTime = null; me.repeat = null; me.running = false; me.reverse = null; } tick() { //TODO 每次刷新执行的操作。子类实现 } } ;// CONCATENATED MODULE: ./src/common/control/TimeFlowControl.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TimeFlowControl * @deprecatedclass SuperMap.TimeFlowControl * @category Control * @classdesc 时间管理类。此类只负责时间上的控制,具体执行的操作需要用户在初始化时的回调函数内部进行实现。 * 如设置起始时间为 1000,结束时间是 2000,步长设置为 1, * 那么表示按照每次1年(可以通过 setSpeed 进行修改)的变化从公元 1000 年开始到公元 2000 年为止,默认每 1 秒会变化 1 次(通过 setFrequency 修改) * @extends {TimeControlBase} * @param {function} callback - 每次刷新回调函数。具体的效果需要用户在此回调函数里面实现。 * @param {Object} options - 可选参数。 * @param {number} [options.speed=1] - 步长(单位 ms)。不能小于 0,(每次刷新的数据之间的间隔为 1ms)。 * @param {number} [options.frequency=1000] - 刷新频率(单位 ms)。 * @param {number} [options.startTime=0] - 起始时间,必须为数字,且小于等于 endTime。如果不设置,初始化时为 0,建议设置。 * @param {number} [options.endTime] - 结束时间,必须为数字,且大于等于 startTime。如果不设置,初始化时使用 new Date() 以当前时间进行设置,建议设置。 * @param {boolean} [options.repeat=true] - 是否重复循环。 * @param {boolean} [options.reverse=false] - 是否反向。 * @usage */ class TimeFlowControl extends TimeControlBase { constructor(callback, options) { super(options); var me = this; /** * @member TimeFlowControl.prototype.callback -{function} * @description 每次刷新执行的回调函数。 */ me.callback = callback; //先让IE下支持bind方法 if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { //empty Function }, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } //保证 this.tick 的上下文还是 TimeControl 这个对象 me.update = me.update.bind(me); me.oldTime = me.currentTime; me.CLASS_NAME = "SuperMap.TimeFlowControl"; } /** * @function TimeFlowControl.prototype.updateOptions * @override */ updateOptions(options) { options = options || {}; super.updateOptions(options); } /** * @function TimeFlowControl.prototype.start * @override */ start() { var me = this; if (me.running) { return; } me.running = true; if (me.reverse) { if (me.currentTime === me.startTime) { me.oldTime = me.endTime; me.currentTime = me.oldTime; } } else { if (me.oldTime === me.endTime) { me.currentTime = me.startTime; me.oldTime = me.currentTime; } } me.tick(); } /** * @function TimeFlowControl.prototype.stop * @override */ stop() { super.stop(); var me = this; me.oldTime = me.currentTime; if (me.running) { me.running = false; } //清除定时tick me.intervalId && window.clearTimeout(me.intervalId); } /** * @function TimeFlowControl.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.oldTime = null; me.callback = null; } /** * @function TimeFlowControl.prototype.tick * @description 定时刷新。 */ tick() { var me = this; me.intervalId && window.clearInterval(me.intervalId); me.intervalId = null; me.update(); me.intervalId = window.setInterval(me.update, me.frequency); } /** * @function TimeFlowControl.prototype.update * @description 更新控件。 */ update() { var me = this; //判定是否还需要继续 if (!me.running) { return; } //调用回调函数 me.callback && me.callback(me.currentTime); //destroy之后callback就为空,所以需要判定一下 if (!me.reverse) { //如果相等,则代表上一帧已经运行到了最后,下一帧运行初始化的状态 if (me.currentTime === me.endTime) { //不循环时 if (!me.repeat) { me.running = false; me.stop(); return null; } me.stop(); me.currentTime = me.startTime; me.oldTime = me.currentTime; me.start(); } else {//否则时间递增 me.oldTime = me.currentTime; me.currentTime += me.speed; } if (me.currentTime >= me.endTime) { me.currentTime = me.endTime; } } else { //如果相等,则代表上一帧已经运行到了最前,下一帧运行结束的状态 if (me.currentTime === me.startTime) { //不循环时 if (!me.repeat) { me.running = false; return null; } me.oldTime = me.endTime; me.currentTime = me.oldTime; } else {//否则时间递减 me.currentTime = me.oldTime; me.oldTime -= me.speed; } if (me.oldTime <= me.startTime) { me.oldTime = me.startTime; } } } } ;// CONCATENATED MODULE: ./src/common/control/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ // EXTERNAL MODULE: ./node_modules/promise-polyfill/dist/polyfill.js var polyfill = __webpack_require__(107); // EXTERNAL MODULE: ./node_modules/fetch-ie8/fetch.js var fetch_ie8_fetch = __webpack_require__(693); // EXTERNAL MODULE: ./node_modules/fetch-jsonp/build/fetch-jsonp.js var fetch_jsonp = __webpack_require__(144); var fetch_jsonp_default = /*#__PURE__*/__webpack_require__.n(fetch_jsonp); ;// CONCATENATED MODULE: ./src/common/util/FetchRequest.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ let FetchRequest_fetch = window.fetch; var setFetch = function (newFetch) { FetchRequest_fetch = newFetch; } var RequestJSONPPromise = { limitLength: 1500, queryKeys: [], queryValues: [], supermap_callbacks: {}, addQueryStrings: function (values) { var me = this; for (var key in values) { me.queryKeys.push(key); if (typeof values[key] !== 'string') { values[key] = Util.toJSON(values[key]); } var tempValue = encodeURIComponent(values[key]); me.queryValues.push(tempValue); } }, issue: function (config) { var me = this, uid = me.getUid(), url = config.url, splitQuestUrl = []; var p = new Promise(function (resolve) { me.supermap_callbacks[uid] = function (response) { delete me.supermap_callbacks[uid]; resolve(response); }; }); // me.addQueryStrings({ // callback: "RequestJSONPPromise.supermap_callbacks[" + uid + "]" // }); var sectionURL = url, keysCount = 0; //此次sectionURL中有多少个key var length = me.queryKeys ? me.queryKeys.length : 0; for (var i = 0; i < length; i++) { if (sectionURL.length + me.queryKeys[i].length + 2 >= me.limitLength) { //+2 for ("&"or"?")and"=" if (keysCount == 0) { return false; } splitQuestUrl.push(sectionURL); sectionURL = url; keysCount = 0; i--; } else { if (sectionURL.length + me.queryKeys[i].length + 2 + me.queryValues[i].length > me.limitLength) { var leftValue = me.queryValues[i]; while (leftValue.length > 0) { var leftLength = me.limitLength - sectionURL.length - me.queryKeys[i].length - 2; //+2 for ("&"or"?")and"=" if (sectionURL.indexOf('?') > -1) { sectionURL += '&'; } else { sectionURL += '?'; } var tempLeftValue = leftValue.substring(0, leftLength); //避免 截断sectionURL时,将类似于%22这样的符号截成两半,从而导致服务端组装sectionURL时发生错误 if (tempLeftValue.substring(leftLength - 1, leftLength) === '%') { leftLength -= 1; tempLeftValue = leftValue.substring(0, leftLength); } else if (tempLeftValue.substring(leftLength - 2, leftLength - 1) === '%') { leftLength -= 2; tempLeftValue = leftValue.substring(0, leftLength); } sectionURL += me.queryKeys[i] + '=' + tempLeftValue; leftValue = leftValue.substring(leftLength); if (tempLeftValue.length > 0) { splitQuestUrl.push(sectionURL); sectionURL = url; keysCount = 0; } } } else { keysCount++; if (sectionURL.indexOf('?') > -1) { sectionURL += '&'; } else { sectionURL += '?'; } sectionURL += me.queryKeys[i] + '=' + me.queryValues[i]; } } } splitQuestUrl.push(sectionURL); me.send( splitQuestUrl, 'RequestJSONPPromise.supermap_callbacks[' + uid + ']', config && config.proxy ); return p; }, getUid: function () { var uid = new Date().getTime(), random = Math.floor(Math.random() * 1e17); return uid * 1000 + random; }, send: function (splitQuestUrl, callback, proxy) { var len = splitQuestUrl.length; if (len > 0) { var jsonpUserID = new Date().getTime(); for (var i = 0; i < len; i++) { var url = splitQuestUrl[i]; if (url.indexOf('?') > -1) { url += '&'; } else { url += '?'; } url += 'sectionCount=' + len; url += '§ionIndex=' + i; url += '&jsonpUserID=' + jsonpUserID; if (proxy) { url = decodeURIComponent(url); url = proxy + encodeURIComponent(url); } fetch_jsonp_default()(url, { jsonpCallbackFunction: callback, timeout: 30000 }); } } }, GET: function (config) { var me = this; me.queryKeys.length = 0; me.queryValues.length = 0; me.addQueryStrings(config.params); return me.issue(config); }, POST: function (config) { var me = this; me.queryKeys.length = 0; me.queryValues.length = 0; me.addQueryStrings({ requestEntity: config.data }); return me.issue(config); }, PUT: function (config) { var me = this; me.queryKeys.length = 0; me.queryValues.length = 0; me.addQueryStrings({ requestEntity: config.data }); return me.issue(config); }, DELETE: function (config) { var me = this; me.queryKeys.length = 0; me.queryValues.length = 0; me.addQueryStrings({ requestEntity: config.data }); return me.issue(config); } }; var CORS; var RequestTimeout; /** * @function setCORS * @description 设置是否允许跨域请求,全局配置,优先级低于 service 下的 crossOring 参数。 * @category BaseTypes Util * @param {boolean} cors - 是否允许跨域请求。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { setCORS } from '{npm}'; * * setCORS(cors); * ``` */ var setCORS = function (cors) { CORS = cors; } /** * @function isCORS * @description 是是否允许跨域请求。 * @category BaseTypes Util * @returns {boolean} 是否允许跨域请求。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { isCORS } from '{npm}'; * * const result = isCORS(); * ``` */ var isCORS = function () { if (CORS != undefined) { return CORS; } return window.XMLHttpRequest && 'withCredentials' in new window.XMLHttpRequest(); } /** * @function setRequestTimeout * @category BaseTypes Util * @description 设置请求超时时间。 * @param {number} [timeout=45] - 请求超时时间,单位秒。 * @usage * ``` * // 浏览器 // ES6 Import import { setRequestTimeout } from '{npm}'; setRequestTimeout(timeout); * ``` */ var setRequestTimeout = function (timeout) { return RequestTimeout = timeout; } /** * @function getRequestTimeout * @category BaseTypes Util * @description 获取请求超时时间。 * @returns {number} 请求超时时间。 * @usage * ``` * // 浏览器 // ES6 Import import { getRequestTimeout } from '{npm}'; getRequestTimeout(); * ``` */ var getRequestTimeout = function () { return RequestTimeout || 45000; } /** * @name FetchRequest * @namespace * @category BaseTypes Util * @description 获取请求。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { FetchRequest } from '{npm}'; * * const result = FetchRequest.commit(method, url, params, options); * * ``` */ var FetchRequest = { /** * @function FetchRequest.commit * @description commit 请求。 * @param {string} method - 请求方法。 * @param {string} url - 请求地址。 * @param {string} params - 请求参数。 * @param {Object} options - 请求的配置属性。 * @returns {Promise} Promise 对象。 */ commit: function (method, url, params, options) { method = method ? method.toUpperCase() : method; switch (method) { case 'GET': return this.get(url, params, options); case 'POST': return this.post(url, params, options); case 'PUT': return this.put(url, params, options); case 'DELETE': return this.delete(url, params, options); default: return this.get(url, params, options); } }, /** * @function FetchRequest.supportDirectRequest * @description supportDirectRequest 请求。 * @param {string} url - 请求地址。 * @param {Object} options - 请求的配置属性。 * @returns {boolean} 是否允许跨域请求。 */ supportDirectRequest: function (url, options) { if (Util.isInTheSameDomain(url)) { return true; } if (options.crossOrigin != undefined) { return options.crossOrigin; } else { return isCORS() || options.proxy; } }, /** * @function FetchRequest.get * @description get 请求。 * @param {string} url - 请求地址。 * @param {string} params - 请求参数。 * @param {Object} options - 请求的配置属性。 * @returns {Promise} Promise 对象。 */ get: function (url, params, options) { options = options || {}; var type = 'GET'; url = Util.urlAppend(url, this._getParameterString(params || {})); url = this._processUrl(url, options); if (!this.supportDirectRequest(url, options)) { url = url.replace('.json', '.jsonp'); var config = { url: url, data: params }; return RequestJSONPPromise.GET(config); } if (!this.urlIsLong(url)) { return this._fetch(url, params, options, type); } else { return this._postSimulatie(type, url.substring(0, url.indexOf('?')), params, options); } }, /** * @function FetchRequest.delete * @description delete 请求。 * @param {string} url - 请求地址。 * @param {string} params - 请求参数。 * @param {Object} options -请求的配置属性。 * @returns {Promise} Promise 对象。 */ delete: function (url, params, options) { options = options || {}; var type = 'DELETE'; url = Util.urlAppend(url, this._getParameterString(params || {})); url = this._processUrl(url, options); if (!this.supportDirectRequest(url, options)) { url = url.replace('.json', '.jsonp'); var config = { url: url += "&_method=DELETE", data: params }; return RequestJSONPPromise.DELETE(config); } if (this.urlIsLong(url)) { return this._postSimulatie(type, url.substring(0, url.indexOf('?')), params, options); } return this._fetch(url, params, options, type); }, /** * @function FetchRequest.post * @description post 请求。 * @param {string} url - 请求地址。 * @param {string} params - 请求参数。 * @param {Object} options - 请求的配置属性。 * @returns {Promise} Promise 对象。 */ post: function (url, params, options) { options = options || {}; if (!this.supportDirectRequest(url, options)) { url = url.replace('.json', '.jsonp'); var config = { url: url += "&_method=POST", data: params }; return RequestJSONPPromise.POST(config); } return this._fetch(this._processUrl(url, options), params, options, 'POST'); }, /** * @function FetchRequest.put * @description put 请求。 * @param {string} url - 请求地址。 * @param {string} params - 请求参数。 * @param {Object} options - 请求的配置属性。 * @returns {Promise} Promise 对象。 */ put: function (url, params, options) { options = options || {}; url = this._processUrl(url, options); if (!this.supportDirectRequest(url, options)) { url = url.replace('.json', '.jsonp'); var config = { url: url += "&_method=PUT", data: params }; return RequestJSONPPromise.PUT(config); } return this._fetch(url, params, options, 'PUT'); }, /** * @function FetchRequest.urlIsLong * @description URL 的字节长度是否太长。 * @param {string} url - 请求地址。 * @returns {boolean} URL 的字节长度是否太长。 */ urlIsLong: function (url) { //当前url的字节长度。 var totalLength = 0, charCode = null; for (var i = 0, len = url.length; i < len; i++) { //转化为Unicode编码 charCode = url.charCodeAt(i); if (charCode < 0x007f) { totalLength++; } else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) { totalLength += 2; } else if ((0x0800 <= charCode) && (charCode <= 0xffff)) { totalLength += 3; } } return totalLength < 2000 ? false : true; }, _postSimulatie: function (type, url, params, options) { var separator = url.indexOf('?') > -1 ? '&' : '?'; url += separator + '_method=' + type; if (typeof params !== 'string') { params = JSON.stringify(params); } return this.post(url, params, options); }, _processUrl: function (url, options) { if (this._isMVTRequest(url)) { return url; } if (url.indexOf('.json') === -1 && !options.withoutFormatSuffix) { if (url.indexOf('?') < 0) { url += '.json'; } else { var urlArrays = url.split('?'); if (urlArrays.length === 2) { url = urlArrays[0] + '.json?' + urlArrays[1]; } } } if (options && options.proxy) { if (typeof options.proxy === 'function') { url = options.proxy(url); } else { url = decodeURIComponent(url); url = options.proxy + encodeURIComponent(url); } } return url; }, _fetch: function (url, params, options, type) { options = options || {}; options.headers = options.headers || {}; if (!options.headers['Content-Type'] && !FormData.prototype.isPrototypeOf(params)) { options.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; } if (options.timeout) { return this._timeout( options.timeout, FetchRequest_fetch(url, { method: type, headers: options.headers, body: type === 'PUT' || type === 'POST' ? params : undefined, credentials: this._getWithCredentials(options), mode: 'cors', timeout: getRequestTimeout() }).then(function (response) { return response; }) ); } return FetchRequest_fetch(url, { method: type, body: type === 'PUT' || type === 'POST' ? params : undefined, headers: options.headers, credentials: this._getWithCredentials(options), mode: 'cors', timeout: getRequestTimeout() }).then(function (response) { return response; }); }, _getWithCredentials: function (options) { if (options.withCredentials === true) { return 'include'; } if (options.withCredentials === false) { return 'omit'; } return 'same-origin'; }, _fetchJsonp: function (url, options) { options = options || {}; return fetch_jsonp_default()(url, { method: 'GET', timeout: options.timeout }).then(function (response) { return response; }); }, _timeout: function (seconds, promise) { return new Promise(function (resolve, reject) { setTimeout(function () { reject(new Error('timeout')); }, seconds); promise.then(resolve, reject); }); }, _getParameterString: function (params) { var paramsArray = []; for (var key in params) { var value = params[key]; if (value != null && typeof value !== 'function') { var encodedValue; if (Array.isArray(value) || value.toString() === '[object Object]') { encodedValue = encodeURIComponent(JSON.stringify(value)); } else { encodedValue = encodeURIComponent(value); } paramsArray.push(encodeURIComponent(key) + '=' + encodedValue); } } return paramsArray.join('&'); }, _isMVTRequest: function (url) { return url.indexOf('.mvt') > -1 || url.indexOf('.pbf') > -1; } } ;// CONCATENATED MODULE: ./src/common/security/SecurityManager.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SecurityManager * @deprecatedclass SuperMap.SecurityManager * @category Security * @classdesc 安全管理中心,提供 iServer,iPortal,Online 统一权限认证管理。 * > 使用说明: * > 创建任何一个服务之前调用 {@link SecurityManager.registerToken}或 * > {@link SecurityManager.registerKey}注册凭据。 * > 发送请求时根据 URL 或者服务 ID 获取相应的 key 或者 token 并自动添加到服务地址中。 * @usage */ class SecurityManager { /** * @description 从服务器获取一个token,在此之前要注册服务器信息。 * @function SecurityManager.generateToken * @param {string} url - 服务器域名+端口,如:http://localhost:8092。 * @param {TokenServiceParameter} tokenParam - token 申请参数。 * @returns {Promise} 包含 token 信息的 Promise 对象。 */ static generateToken(url, tokenParam) { var serverInfo = this.servers[url]; if (!serverInfo) { return; } return FetchRequest.post(serverInfo.tokenServiceUrl, JSON.stringify(tokenParam.toJSON())).then(function( response ) { return response.text(); }); } /** * @description 注册安全服务器相关信息。 * @function SecurityManager.registerServers * @param {ServerInfo} serverInfos - 服务器信息。 */ static registerServers(serverInfos) { this.servers = this.servers || {}; if (!Util.isArray(serverInfos)) { serverInfos = [serverInfos]; } for (var i = 0; i < serverInfos.length; i++) { var serverInfo = serverInfos[i]; this.servers[serverInfo.server] = serverInfo; } } /** * @description 服务请求都会自动带上这个 token。 * @function SecurityManager.registerToken * @param {string} url -服务器域名+端口:如http://localhost:8090。 * @param {string} token - token。 */ static registerToken(url, token) { this.tokens = this.tokens || {}; if (!url || !token) { return; } var domain = this._getTokenStorageKey(url); this.tokens[domain] = token; } /** * @description 注册 key,ids 为数组(存在一个 key 对应多个服务)。 * @function SecurityManager.registerKey * @param {Array} ids - 可以是服务 ID 数组或者 URL 地址数组或者 webAPI 类型数组。 * @param {string} key - key。 */ static registerKey(ids, key) { this.keys = this.keys || {}; if (!ids || ids.length < 1 || !key) { return; } ids = Util.isArray(ids) ? ids : [ids]; for (var i = 0; i < ids.length; i++) { var id = this._getUrlRestString(ids[0]) || ids[0]; this.keys[id] = key; } } /** * @description 获取服务器信息。 * @function SecurityManager.getServerInfo * @param {string} url - 服务器域名+端口,如:http://localhost:8092。 * @returns {ServerInfo} 服务器信息。 */ static getServerInfo(url) { this.servers = this.servers || {}; return this.servers[url]; } /** * @description 根据 URL 获取token。 * @function SecurityManager.getToken * @param {string} url - 服务器域名+端口,如:http://localhost:8092。 * @returns {string} token。 */ static getToken(url) { if (!url) { return; } this.tokens = this.tokens || {}; var domain = this._getTokenStorageKey(url); return this.tokens[domain]; } /** * @description 根据 URL 获取 key。 * @function SecurityManager.getKey * @param {string} id - ID。 * @returns {string} key。 */ static getKey(id) { this.keys = this.keys || {}; var key = this._getUrlRestString(id) || id; return this.keys[key]; } /** * @description iServer 登录验证。 * @function SecurityManager.loginiServer * @param {string} url - iServer 首页地址,如:http://localhost:8090/iserver。 * @param {string} username - 用户名。 * @param {string} password - 密码。 * @param {boolean} [rememberme=false] - 是否记住。 * @returns {Promise} 包含 iServer 登录请求结果的 Promise 对象。 */ static loginiServer(url, username, password, rememberme) { url = Util.urlPathAppend(url, 'services/security/login'); var loginInfo = { username: username && username.toString(), password: password && password.toString(), rememberme: rememberme }; loginInfo = JSON.stringify(loginInfo); var requestOptions = { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }; return FetchRequest.post(url, loginInfo, requestOptions).then(function(response) { return response.json(); }); } /** * @description iServer登出。 * @function SecurityManager.logoutiServer * @param {string} url - iServer 首页地址,如:http://localhost:8090/iserver。 * @returns {Promise} 是否登出成功。 */ static logoutiServer(url) { url = Util.urlPathAppend(url, 'services/security/logout'); var requestOptions = { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, withoutFormatSuffix: true }; return FetchRequest.get(url, '', requestOptions) .then(function() { return true; }) .catch(function() { return false; }); } /** * @description Online 登录验证。 * @function SecurityManager.loginOnline * @param {string} callbackLocation - 跳转位置。 * @param {boolean} [newTab=true] - 是否新窗口打开。 */ static loginOnline(callbackLocation, newTab) { var loginUrl = SecurityManager.SSO + '/login?service=' + callbackLocation; this._open(loginUrl, newTab); } /** * @description iPortal登录验证。 * @function SecurityManager.loginiPortal * @param {string} url - iportal 首页地址,如:http://localhost:8092/iportal。 * @param {string} username - 用户名。 * @param {string} password - 密码。 * @returns {Promise} 包含 iPortal 登录请求结果的 Promise 对象。 */ static loginiPortal(url, username, password) { url = Util.urlPathAppend(url, 'web/login'); var loginInfo = { username: username && username.toString(), password: password && password.toString() }; loginInfo = JSON.stringify(loginInfo); var requestOptions = { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, withCredentials: true }; return FetchRequest.post(url, loginInfo, requestOptions).then(function(response) { return response.json(); }); } /** * @description iPortal 登出。 * @function SecurityManager.logoutiPortal * @param {string} url - iportal 首页地址,如:http://localhost:8092/iportal。 * @returns {Promise} 如果登出成功,返回 true;否则返回 false。 */ static logoutiPortal(url) { url = Util.urlPathAppend(url, 'services/security/logout'); var requestOptions = { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, withCredentials: true, withoutFormatSuffix: true }; return FetchRequest.get(url, '', requestOptions) .then(function() { return true; }) .catch(function() { return false; }); } /** * @description iManager 登录验证。 * @function SecurityManager.loginManager * @param {string} url - iManager 地址。地址参数为 iManager 首页地址,如: http://localhost:8390/imanager。 * @param {Object} [loginInfoParams] - iManager 登录参数。 * @param {string} loginInfoParams.userName - 用户名。 * @param {string} loginInfoParams.password - 密码。 * @param {Object} options * @param {boolean} [options.isNewTab=true] - 不同域时是否在新窗口打开登录页面。 * @returns {Promise} 包含 iManager 登录请求结果的 Promise 对象。 */ static loginManager(url, loginInfoParams, options) { if (!Util.isInTheSameDomain(url)) { var isNewTab = options ? options.isNewTab : true; this._open(url, isNewTab); return; } var requestUrl = Util.urlPathAppend(url, 'icloud/security/tokens'); var params = loginInfoParams || {}; var loginInfo = { username: params.userName && params.userName.toString(), password: params.password && params.password.toString() }; loginInfo = JSON.stringify(loginInfo); var requestOptions = { headers: { Accept: '*/*', 'Content-Type': 'application/json' } }; var me = this; return FetchRequest.post(requestUrl, loginInfo, requestOptions).then(function(response) { response.text().then(function(result) { me.imanagerToken = result; return result; }); }); } /** * @description 清空全部验证信息。 * @function SecurityManager.destroyAllCredentials */ static destroyAllCredentials() { this.keys = null; this.tokens = null; this.servers = null; } /** * @description 清空令牌信息。 * @function SecurityManager.destroyToken * @param {string} url - iportal 首页地址,如:http://localhost:8092/iportal。 */ static destroyToken(url) { if (!url) { return; } var domain = this._getTokenStorageKey(url); this.tokens = this.tokens || {}; if (this.tokens[domain]) { delete this.tokens[domain]; } } /** * @description 清空服务授权码。 * @function SecurityManager.destroyKey * @param {string} url - iServer 首页地址,如:http://localhost:8090/iserver。 */ static destroyKey(url) { if (!url) { return; } this.keys = this.keys || {}; var key = this._getUrlRestString(url) || url; if (this.keys[key]) { delete this.keys[key]; } } /** * @description 服务URL追加授权信息,授权信息需先通过SecurityManager.registerKey或SecurityManager.registerToken注册。 * @version 10.1.2 * @function SecurityManager.appendCredential * @param {string} url - 服务URL。 * @returns {string} 绑定了token或者key的服务URL。 */ static appendCredential(url) { var newUrl = url; var value = this.getToken(url); var credential = value ? new Credential(value, 'token') : null; if (!credential) { value = this.getKey(url); credential = value ? new Credential(value, 'key') : null; } if (credential) { newUrl = Util.urlAppend(newUrl, credential.getUrlParameters()); } return newUrl; } static _open(url, newTab) { newTab = newTab != null ? newTab : true; var offsetX = window.screen.availWidth / 2 - this.INNER_WINDOW_WIDTH / 2; var offsetY = window.screen.availHeight / 2 - this.INNER_WINDOW_HEIGHT / 2; var options = 'height=' + this.INNER_WINDOW_HEIGHT + ', width=' + this.INNER_WINDOW_WIDTH + ',top=' + offsetY + ', left=' + offsetX + ',toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no'; if (newTab) { window.open(url, 'login'); } else { window.open(url, 'login', options); } } static _getTokenStorageKey(url) { var patten = /(.*?):\/\/([^\/]+)/i; var result = url.match(patten); if (!result) { return url; } return result[0]; } static _getUrlRestString(url) { if (!url) { return url; } // var patten = /http:\/\/(.*\/rest)/i; var patten = /(http|https):\/\/(.*\/rest)/i; var result = url.match(patten); if (!result) { return url; } return result[0]; } } SecurityManager.INNER_WINDOW_WIDTH = 600; SecurityManager.INNER_WINDOW_HEIGHT = 600; SecurityManager.SSO = 'https://sso.supermap.com'; SecurityManager.ONLINE = 'https://www.supermapol.com'; ;// CONCATENATED MODULE: ./src/common/iManager/iManagerServiceBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IManagerServiceBase * @aliasclass iManagerServiceBase * @deprecatedclass SuperMap.iManagerServiceBase * @classdesc iManager 服务基类(有权限限制的类需要实现此类)。 * @category iManager * @param {string} url - iManager 首页地址,如:http://localhost:8390/imanager。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class IManagerServiceBase { constructor(url,options) { if (url) { var end = url.substr(url.length - 1, 1); this.serviceUrl = end === "/" ? url.substr(0, url.length - 2) : url; } this.options = options || {}; this.CLASS_NAME = "SuperMap.iManagerServiceBase"; } /** * @function IManagerServiceBase.prototype.request * @description 子类统一通过该方法发送请求。 * @param {string} url - 请求 URL。 * @param {string} [method='GET'] - 请求类型。 * @param {Object} [requestOptions] - 请求选项。 * @param {Object} param - 请求参数。 * @description 发送请求。 * @returns {Promise} Promise 对象。 */ request(method, url, param, requestOptions) { requestOptions = requestOptions || { headers: { 'Accept': '*/*', 'Content-Type': 'application/json' } }; if (!requestOptions.hasOwnProperty("withCredentials")) { requestOptions['withCredentials'] = true; } requestOptions['crossOrigin'] = this.options.crossOrigin; requestOptions['headers'] = this.options.headers; var token = SecurityManager.imanagerToken; if (token) { if (!requestOptions.headers) { requestOptions.headers = []; } requestOptions.headers['X-Auth-Token'] = token; } if (param) { param = JSON.stringify(param); } return FetchRequest.commit(method, url, param, requestOptions).then(function (response) { return response.json(); }); } } ;// CONCATENATED MODULE: ./src/common/iManager/iManagerCreateNodeParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IManagerCreateNodeParam * @aliasclass iManagerCreateNodeParam * @deprecatedclass SuperMap.iManagerCreateNodeParam * @classdesc iManager 创建节点参数。 * @category iManager * @param {Object} [params] - 节点参数。 * @usage */ class IManagerCreateNodeParam { constructor(params) { params = params || {}; this.nodeSpec = 'SMALL'; //取值范围: ['SMALL','MEDIUM','LARGE'] 以及自定义的环境规格名称 this.nodeCount = 1; //要创建vm的个数 this.nodeName = ''; //vm名称 this.password = ''; //vm的密码,空表示随机分配 this.description = ''; //描述信息 this.physicalMachineName = ''; //vm所属的物理机名称. this.ips = []; //vm的ip,空数组表示随机分配 this.userName = ''; //vm所属用户 Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iManager/iManager.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IManager * @aliasclass iManager * @deprecatedclass SuperMap.iManager * @classdesc iManager 服务类。 * @category iManager * @param {string} serviceUrl - iManager 首页地址。 * @usage */ class IManager extends IManagerServiceBase { constructor(iManagerUrl) { super(iManagerUrl); } /** * @function IManager.prototype.load * @description 获取所有服务接口,验证是否已登录授权。 * @returns {Promise} Promise 对象。 */ load() { return this.request("GET", this.serviceUrl + '/web/api/service.json'); } /** * @function IManager.prototype.createIServer * @param {IManagerCreateNodeParam} createParam - 创建参数。 * @description 创建 iServer。 * @returns {Promise} Promise 对象。 */ createIServer(createParam) { return this.request("POST", this.serviceUrl + '/icloud/web/nodes/server.json', new IManagerCreateNodeParam(createParam)); } /** * @function IManager.prototype.createIPortal * @param {IManagerCreateNodeParam} createParam - 创建参数。 * @description 创建 iPortal。 * @returns {Promise} Promise 对象。 */ createIPortal(createParam) { return this.request("POST", this.serviceUrl + '/icloud/web/nodes/portal.json', new IManagerCreateNodeParam(createParam)); } /** * @function IManager.prototype.iServerList * @description 获取所有创建的 iServer。 * @returns {Promise} Promise 对象。 */ iServerList() { return this.request("GET", this.serviceUrl + '/icloud/web/nodes/server.json'); } /** * @function IManager.prototype.iPortalList * @description 获取所有创建的 iPortal。 * @returns {Promise} Promise 对象。 */ iPortalList() { return this.request("GET", this.serviceUrl + '/icloud/web/nodes/portal.json'); } /** * @function IManager.prototype.startNodes * @param {Array.} ids - 需要启动节点的 ID 数组。e.g:['1']。 * @description 启动节点。 * @returns {Promise} Promise 对象。 */ startNodes(ids) { return this.request("POST", this.serviceUrl + '/icloud/web/nodes/started.json', ids); } /** * @function IManager.prototype.stopNodes * @param {Array.} ids - 需要停止节点的 ID 数组。e.g:['1']。 * @description 停止节点。 * @returns {Promise} Promise 对象。 */ stopNodes(ids) { return this.request("POST", this.serviceUrl + '/icloud/web/nodes/stopped.json', ids); } } ;// CONCATENATED MODULE: ./src/common/iManager/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalServiceBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalServiceBase * @aliasclass iPortalServiceBase * @deprecatedclass SuperMap.iPortalServiceBase * @classdesc iPortal 服务基类(有权限限制的类需要实现此类)。 * @category iPortal/Online Core * @param {string} url - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class IPortalServiceBase { constructor(url, options) { options = options || {}; this.serviceUrl = url; this.CLASS_NAME = "SuperMap.iPortalServiceBase"; this.withCredentials = options.withCredentials || false; this.crossOrigin = options.crossOrigin this.headers = options.headers } /** * @function IPortalServiceBase.prototype.request * @description 子类统一通过该方法发送请求。 * @param {string} [method='GET'] - 请求类型。 * @param {string} url - 服务地址。 * @param {Object} param - 请求参数。 * @param {Object} [requestOptions] - fetch 请求配置项。 * @returns {Promise} 返回包含请求结果的 Promise 对象。 */ request(method, url, param, requestOptions = {headers: this.headers, crossOrigin: this.crossOrigin, withCredentials: this.withCredentials }) { url = SecurityManager.appendCredential(url); return FetchRequest.commit(method, url, param, requestOptions).then(function (response) { return response.json(); }); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalQueryParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalQueryParam * @aliasclass iPortalQueryParam * @deprecatedclass SuperMap.iPortalQueryParam * @classdesc iPortal 资源查询参数。 * @version 10.0.1 * @category iPortal/Online Resources ResourcesQuery * @param {Object} params - 可选参数。 * @param {ResourceType} [params.resourceType] - 资源类型。 * @param {number} [params.pageSize] - 分页中每页大小。 * @param {number} [params.currentPage] - 分页页码。 * @param {OrderBy} [params.orderBy] - 排序字段。 * @param {OrderType} [params.orderType] - 根据升序还是降序过滤。 * @param {SearchType} [params.searchType] - 根据查询的范围进行过滤。 * @param {Array} [params.tags] - 标签。 * @param {Array} [params.dirIds] - 目录 ID。 * @param {Array} [params.resourceSubTypes] - 根据资源的子类型进行过滤。 * @param {AggregationTypes} [params.aggregationTypes] - 聚合查询的类型。 * @param {string} [params.text] - 搜索的关键词。 * @param {Array} [params.groupIds] - 根据群组进行过滤。 * @param {Array} [params.departmentIds] - 根据部门进行过滤。 * @usage */ class IPortalQueryParam { constructor(params) { params = params || {}; this.resourceType = ""; // 空为全部 MAP SERVICE SCENE DATA INSIGHTS_WORKSPACE MAP_DASHBOARD this.pageSize = 12; // 每页多少条 this.currentPage = 1; // 第几页 this.orderBy = "UPDATETIME"; // UPDATETIME HEATLEVEL this.orderType = "DESC"; // DESC ASC this.searchType = "PUBLIC"; // PUBLIC SHARETOME_RES MYDEPARTMENT_RES MYGROUP_RES MY_RES this.tags = []; // 标签 this.dirIds = []; // 类别 this.resourceSubTypes = []; // 类型 this.aggregationTypes = []; // TAG TYPE SUBTYPE this.text = ""; // 搜索字段 this.groupIds = []; // 群组Id过滤 this.departmentIds = []; // 部门Id过滤 Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalQueryResult.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalQueryResult * @aliasclass iPortalQueryResult * @deprecatedclass SuperMap.iPortalQueryResult * @classdesc iPortal 资源结果集封装类。 * @version 10.0.1 * @category iPortal/Online Resources ResourcesQuery * @param {Object} queryResult - 可选参数。 * @param {Array} [queryResult.content] - 页面内容。 * @param {number} [queryResult.total] - 总记录数。 * @param {number} [queryResult.currentPage] - 当前第几页。 * @param {number} [queryResult.pageSize] - 每页大小。 * @param {Object} [queryResult.aggregations] - 聚合查询的结果。 * @usage */ class IPortalQueryResult { constructor(queryResult) { queryResult = queryResult || {}; this.content = []; this.total = 0; this.currentPage = 1; this.pageSize = 12; this.aggregations = null; Util.extend(this, queryResult); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalResource.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalResource * @aliasclass iPortalResource * @deprecatedclass SuperMap.iPortalResource * @classdesc iPortal 资源详情类。 * @version 10.0.1 * @category iPortal/Online Resources * @param {string} portalUrl - 服务地址。 * @param {Object} resourceInfo - 可选参数。 * @param {Array} [resourceInfo.authorizeSetting] - 资源的授权信息。 * @param {string} [resourceInfo.bounds] - 资源的坐标范围。 * @param {string} [resourceInfo.bounds4326] - 资源的坐标范围,转换为EPSG 4326坐标系统后的地理范围。 * @param {string} [resourceInfo.checkStatus] - 资源的审核状态,可以是:空,SUCCESSFUL,UNCHECKED,FAILED。 * @param {Date} [resourceInfo.createTime] - 资源的创建时间。 * @param {string} [resourceInfo.description] - 资源描述。 * @param {number} [resourceInfo.dirId] - 资源所在的门户目录的ID。 * @param {number} [resourceInfo.epsgCode] - 门户资源基于的坐标系的EPSG值。 * @param {number} [resourceInfo.heatLevel] - 记录资源的访问量或下载量。 * @param {string} [resourceInfo.id] - 资源存储到ElasticSearch中的文档ID。 * @param {string} [resourceInfo.name] - 资源名称。 * @param {number} [resourceInfo.personalDirId] - 资源所在的个人目录的ID。 * @param {number} [resourceInfo.resourceId] - 资源表(maps,services等)里的ID。 * @param {string} [resourceInfo.resourceSubType] - 某类资源的具体子类型。 * @param {ResourceType} [resourceInfo.resourceType] - 资源类型。 * @param {number} [resourceInfo.serviceRootUrlId] - 批量注册服务时,服务根地址的ID。 * @param {Array} [resourceInfo.tags] - 资源的标签。 * @param {string} [resourceInfo.thumbnail] - 资源的缩略图。 * @param {Date} [resourceInfo.updateTime] - 资源的更新时间。 * @param {string} [resourceInfo.userName] - 搜索的关键词。 * @param {Object} [resourceInfo.sourceJSON] - 提供了门户项目返回的所有信息。 * @extends {IPortalServiceBase} * @usage */ class IPortalResource extends IPortalServiceBase { constructor(portalUrl, resourceInfo) { super(portalUrl); resourceInfo = resourceInfo || {}; this.authorizeSetting = []; this.bounds = ""; this.bounds4326 = ""; this.checkStatus = ""; this.createTime = 0; this.description = null; this.dirId = null; this.epsgCode = 0; this.heatLevel = 0; this.id = 0; this.name = ""; this.personalDirId = null; this.resourceId = 0; this.resourceSubType = null; this.resourceType = null; this.serviceRootUrlId = null; this.tags = null; this.thumbnail = null; this.updateTime = 0; this.userName = ""; this.sourceJSON = {};//返回门户资源详细信息 Util.extend(this, resourceInfo); // INSIGHTS_WORKSPACE MAP_DASHBOARD this.resourceUrl = portalUrl + "/web/"+this.resourceType.replace("_","").toLowerCase()+"s/" + this.resourceId; if (this.withCredentials) { this.resourceUrl = portalUrl + "/web/mycontent/"+this.resourceType.replace("_","").toLowerCase()+"s/" + this.resourceId; } // if (this.id) { // this.mapUrl = mapUrl + "/" + this.id; // } } /** * @function IPortalResource.prototype.load * @description 加载资源信息。 * @returns {Promise} 返回 Promise 对象。如果成功,Promise 没有返回值,请求返回结果自动填充到该类的属性中;如果失败,Promise 返回值包含错误信息。 */ load() { var me = this; return me.request("GET", me.resourceUrl + ".json") .then(function (resourceInfo) { if (resourceInfo.error) { return resourceInfo; } me.sourceJSON = resourceInfo; }); } /** * @function IPortalResource.prototype.update * @description 更新资源属性信息。 * @returns {Promise} 返回包含更新操作状态的 Promise 对象。 */ update() { var resourceName = this.resourceType.replace("_","").toLowerCase(); var options = { headers: {'Content-Type': 'application/x-www-form-urlencoded'} }; if( resourceName === 'data') { this.resourceUrl = this.resourceUrl + "/attributes.json"; } var entity = JSON.stringify(this.sourceJSON); //对服务资源进行编辑时,请求体内容只留关键字字段(目前如果是全部字段 更新返回成功 但其实没有真正的更新) if( resourceName === 'service') { var serviceInfo = { authorizeSetting:this.sourceJSON.authorizeSetting, metadata:this.sourceJSON.metadata, tags:this.sourceJSON.tags, thumbnail:this.sourceJSON.thumbnail, tokenRefreshUrl:this.sourceJSON.tokenRefreshUrl }; entity = JSON.stringify(serviceInfo); } return this.request("PUT", this.resourceUrl, entity, options); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalShareParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalShareParam * @aliasclass iPortalShareParam * @deprecatedclass SuperMap.iPortalShareParam * @classdesc iPortal 资源共享参数。 * @version 10.0.1 * @category iPortal/Online Resources ResourcesShare * @param {Object} params - 可选参数。 * @param {ResourceType} [params.resourceType] - 资源类型。 * @param {Array} [params.ids] - 资源的ID数组。 * @param {IPortalShareEntity} [params.entities] - 资源的实体共享参数。 * @usage */ class IPortalShareParam { constructor(params) { params = params || {}; this.ids = []; this.entities = []; this.resourceType = ""; // MAP SERVICE SCENE DATA INSIGHTS_WORKSPACE MAP_DASHBOARD Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortal.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortal * @aliasclass iPortal * @deprecatedclass SuperMap.iPortal * @classdesc 对接 SuperMap iPortal 基础服务。 * @category iPortal/Online Resources * @extends {IPortalServiceBase} * @param {string} iportalUrl - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.withCredentials] - 请求是否携带 cookie。 * @usage */ class IPortal extends IPortalServiceBase { constructor(iportalUrl, options) { super(iportalUrl, options); this.iportalUrl = iportalUrl; options = options || {}; this.withCredentials = options.withCredentials || false; } /** * @function IPortal.prototype.load * @description 加载页面。 * @returns {Promise} 包含 iportal web 资源信息的 Promise 对象。 */ load() { return FetchRequest.get(this.iportalUrl + "/web"); } /** * @function IPortal.prototype.queryResources * @description 查询资源。 * @version 10.0.1 * @param {IPortalQueryParam} queryParams - 查询参数。 * @returns {Promise} 包含所有资源结果的 Promise 对象。 */ queryResources(queryParams) { if (!(queryParams instanceof IPortalQueryParam)) { return new Promise( function(resolve){ resolve( "queryParams is not instanceof iPortalQueryParam !" ); }); } var me = this; var resourceUrl = this.iportalUrl + "/gateway/catalog/resource/search.json"; queryParams.t = new Date().getTime(); return this.request("GET", resourceUrl, queryParams).then(function(result) { var content = []; result.content.forEach(function(item) { content.push(new IPortalResource(me.iportalUrl, item)); }); let queryResult = new IPortalQueryResult(); queryResult.content = content; queryResult.total = result.total; queryResult.currentPage = result.currentPage; queryResult.pageSize = result.pageSize; queryResult.aggregations = result.aggregations; return queryResult; }); } /** * @function IPortal.prototype.updateResourcesShareSetting * @description 更新共享设置。 * @version 10.0.1 * @param {IPortalShareParam} shareParams - 共享的参数。 * @returns {Promise} 包含共享资源结果的 Promise 对象。 */ updateResourcesShareSetting(shareParams) { if (!(shareParams instanceof IPortalShareParam)) { return new Promise( function(resolve){ resolve( "shareParams is not instanceof iPortalShareParam !" ); }); } var resourceUrlName = shareParams.resourceType.replace("_","").toLowerCase()+"s"; if(resourceUrlName === "datas"){ resourceUrlName = "mycontent/"+resourceUrlName; } var cloneShareParams = { ids: shareParams.ids, entities: shareParams.entities } var shareUrl = this.iportalUrl + "/web/"+resourceUrlName+"/sharesetting.json"; return this.request("PUT", shareUrl, JSON.stringify(cloneShareParams)).then(function(result) { return result; }); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalShareEntity.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalShareEntity * @aliasclass iPortalShareEntity * @deprecatedclass SuperMap.iPortalShareEntity * @classdesc iPortal 资源共享实体参数。 * @version 10.0.1 * @category iPortal/Online Resources ResourcesShare * @param {Object} shareEntity - 可选参数。 * @param {PermissionType} [shareEntity.permissionType] - 权限类型。 * @param {EntityType} [shareEntity.entityType] - 实体类型。 * @param {string} [shareEntity.entityName] - 实体 Name。对应的 USER(用户)、ROLE(角色)、GROUP(用户组)、IPORTALGROUP(群组)的名称。 * @param {number} [shareEntity.entityId] - 实体的 ID。用于群组的授权。 * @usage */ class IPortalShareEntity { constructor(shareEntity) { shareEntity = shareEntity || {}; this.permissionType = ""; // SEARCH READ READWRITE DOWNLOAD this.entityType = ""; // USER DEPARTMENT IPORTALGROUP this.entityName = "GUEST"; // GUEST or 具体用户 name this.entityId = null; Util.extend(this, shareEntity); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalAddResourceParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalAddResourceParam * @aliasclass iPortalAddResourceParam * @deprecatedclass SuperMap.iPortalAddResourceParam * @classdesc iPortal 添加资源参数。 * @version 10.0.1 * @category iPortal/Online Resources ResourcesShare * @param {Object} params - 可选参数。 * @param {string} [params.rootUrl] - 服务地址。 * @param {Array} [params.tags] - 标签。 * @param {IPortalShareEntity} [params.entities] - 资源的实体共享参数。 * @usage */ class IPortalAddResourceParam { constructor(params) { params = params || {}; this.rootUrl = ""; this.tags = []; this.entities = []; Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalRegisterServiceParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalRegisterServiceParam * @aliasclass iPortalRegisterServiceParam * @deprecatedclass SuperMap.iPortalRegisterServiceParam * @classdesc iPortal 注册服务参数。 * @version 10.0.1 * @category iPortal/Online Resources Data * @param {Object} params - 可选参数。 * @param {string} [params.type] - 服务类型。 * @param {Array} [params.tags] - 服务标签。 * @param {IPortalShareEntity} [params.entities] - 资源的实体共享参数。 * @param {Object} [params.metadata] - 服务元信息。 * @param {Array} [params.addedMapNames] - 地图服务列表。 * @param {Array} [params.addedSceneNames] - 场景服务列表。 * @usage */ class IPortalRegisterServiceParam { constructor(params) { params = params || {}; this.type = ""; // SUPERMAP_REST ARCGIS_REST WMS WFS WCS WPS WMTS OTHERS this.tags = []; this.entities = []; this.metadata = {}; this.addedMapNames = []; this.addedSceneNames = []; Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalAddDataParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalAddDataParam * @aliasclass iPortalAddDataParam * @deprecatedclass SuperMap.iPortalAddDataParam * @classdesc iPortal 上传/注册数据所需的参数。 * @version 10.0.1 * @category iPortal/Online Resources Data * @param {Object} params - 参数。 * @param {string} params.fileName - 文件名称。 * @param {DataItemType} params.type - 数据类型。 * @param {Array} [params.tags] - 数据的标签。 * @param {IPortalDataMetaInfoParam} [params.dataMetaInfo] - 数据元信息。 * @usage */ class IPortalAddDataParam { constructor(params) { params = params || {}; this.fileName = ""; this.type = ""; this.tags = []; this.dataMetaInfo = {}; Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalDataMetaInfoParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalDataMetaInfoParam * @aliasclass iPortalDataMetaInfoParam * @deprecatedclass SuperMap.iPortalDataMetaInfoParam * @classdesc iPortal 上传数据/注册数据元信息所需的参数。 * @version 10.0.1 * @category iPortal/Online Resources Data * @param {Object} params - 参数。 * @param {string} params.xField - X 坐标字段。 * @param {string} params.yField - Y 坐标字段。 * @param {number} params.xIndex - x所在列(关系型存储下CSV或EXCEL数据时必填)。 * @param {number} params.yIndex - y所在列(关系型存储下CSV或EXCEL数据时必填)。 * @param {Array.} [params.fieldTypes] - 设置字段类型(关系型存储下CSV或EXCEL数据时可选填)。默认类型为:WTEXT。该参数按照CSV文件字段顺序从左到右依次设置,其中默认字段类型可省略不设置。例如,CSV文件中有10个字段,如果只需设定第1,2,4个字段,可设置为['a','b',,'c']。 * @param {string} params.separator - 分隔符(关系型存储下CSV数据时必填)。 * @param {boolean} params.firstRowIsHead - 是否带表头(关系型存储下CSV数据时必填)。 * @param {boolean} params.url - HDFS注册目录地址。 * @param {IPortalDataStoreInfoParam} params.dataStoreInfo - 注册数据时的数据存储信息。 * @usage */ class IPortalDataMetaInfoParam { constructor(params) { params = params || {}; this.xField = ""; this.yField = ""; this.fileEncoding = "UTF-8"; this.xIndex = 1; this.yIndex = 1; this.fieldTypes = []; this.separator = ""; this.firstRowIsHead = true; this.url = ""; this.dataStoreInfo = {}; Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalDataStoreInfoParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalDataStoreInfoParam * @aliasclass iPortalDataStoreInfoParam * @deprecatedclass SuperMap.iPortalDataStoreInfoParam * @classdesc iPortal 注册一个HBASE HDFS数据存储类。 * @version 10.0.1 * @category iPortal/Online Resources Data * @param {Object} params - 参数。 * @param {string} params.type - 大数据文件共享类型和空间数据库类型,包括大数据文件共享HDFS 目录(HDFS)和空间数据库HBASE。 * @param {string} params.url - HDFS数据存储目录地址。 * @param {IPortalDataConnectionInfoParam} [params.connectionInfo] - HBASE空间数据库服务的连接信息。 * @usage */ class IPortalDataStoreInfoParam { constructor(params) { params = params || {}; this.type = ""; this.url = ""; this.connectionInfo = {}; Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalDataConnectionInfoParam.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalDataConnectionInfoParam * @aliasclass iPortalDataConnectionInfoParam * @deprecatedclass SuperMap.iPortalDataConnectionInfoParam * @classdesc iPortal HBASE数据源连接信息类。 * @version 10.0.1 * @category iPortal/Online Resources Data * @param {Object} params - 参数。 * @param {string} params.dataBase - 数据源连接的数据库名。 * @param {string} params.server - 服务地址。 * @usage */ class IPortalDataConnectionInfoParam { constructor(params) { params = params || {}; this.dataBase = ""; this.server = ""; Util.extend(this, params); } } ;// CONCATENATED MODULE: ./src/common/iPortal/iPortalUser.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IPortalUser * @aliasclass iPortalUser * @deprecatedclass SuperMap.iPortalUser * @classdesc iPortal 门户中用户信息的封装类。用于管理用户资源,包括可删除,添加资源。 * @version 10.0.1 * @category iPortal/Online Resources * @param {string} iportalUrl - 服务地址。 * @extends {IPortalServiceBase} * @usage */ class IPortalUser extends IPortalServiceBase { constructor(iportalUrl) { super(iportalUrl); this.iportalUrl = iportalUrl; } /** * @function IPortalUser.prototype.deleteResources * @description 删除资源。 * @param {Object} params - 删除资源所需的参数对象:{ids,resourceType}。 * @returns {Promise} 返回包含删除操作状态的 Promise 对象。 */ deleteResources(params) { var resourceName = params.resourceType.replace("_","").toLowerCase(); var deleteResourceUrl = this.iportalUrl+"/web/" + resourceName +"s.json?ids=" + encodeURI(JSON.stringify(params.ids)); if( resourceName === 'data') { deleteResourceUrl = this.iportalUrl + "/web/mycontent/datas/delete.json"; return this.request("POST", deleteResourceUrl, JSON.stringify(params.ids)); } return this.request("DELETE", deleteResourceUrl); } /** * @function IPortalUser.prototype.addMap * @description 添加地图。 * @version 10.1.0 * @param {IPortalAddResourceParam} addMapParams - 添加地图的参数。 * @returns {Promise} 返回包含添加地图结果的 Promise 对象。 */ addMap(addMapParams) { if (!(addMapParams instanceof IPortalAddResourceParam)) { return this.getErrMsgPromise("addMapParams is not instanceof IPortalAddResourceParam !"); } let cloneAddMapParams = { rootUrl: addMapParams.rootUrl, tags: addMapParams.tags, authorizeSetting: addMapParams.entities } let addMapUrl = this.iportalUrl + "/web/maps/batchaddmaps.json"; return this.request("POST", addMapUrl, JSON.stringify(cloneAddMapParams)).then(function(result) { return result; }); } /** * @function IPortalUser.prototype.addScene * @description 添加场景。 * @version 10.1.0 * @param {IPortalAddResourceParam} addSceneParams - 添加场景的参数。 * @returns {Promise} 返回包含添加场景结果的 Promise 对象。 */ addScene(addSceneParams) { if (!(addSceneParams instanceof IPortalAddResourceParam)) { return this.getErrMsgPromise("addSceneParams is not instanceof IPortalAddResourceParam !"); } let cloneAddSceneParams = { rootUrl: addSceneParams.rootUrl, tags: addSceneParams.tags, authorizeSetting: addSceneParams.entities } let addSceneUrl = this.iportalUrl + "/web/scenes/batchaddscenes.json"; return this.request("POST", addSceneUrl, JSON.stringify(cloneAddSceneParams)).then(function(result) { return result; }); } /** * @function IPortalUser.prototype.registerService * @description 注册服务。 * @version 10.1.0 * @param {IPortalRegisterServiceParam} registerParams - 注册服务的参数。 * @returns {Promise} 返回包含注册服务结果的 Promise 对象。 */ registerService(registerParams) { if(!(registerParams instanceof IPortalRegisterServiceParam)) { return this.getErrMsgPromise("registerParams is not instanceof IPortalRegisterServiceParam !"); } let cloneRegisterParams = { type: registerParams.type, tags: registerParams.tags, authorizeSetting: registerParams.entities, metadata: registerParams.metadata, addedMapNames: registerParams.addedMapNames, addedSceneNames: registerParams.addedSceneNames } let registerUrl = this.iportalUrl + "/web/services.json"; return this.request("POST", registerUrl, JSON.stringify(cloneRegisterParams)).then(result => { return result; }); } /** * @function IPortalUser.prototype.getErrMsgPromise * @description 获取包含错误信息的Promise对象。 * @version 10.1.0 * @param {string} errMsg - 传入的错误信息。 * @returns {Promise} 返回包含错误信息的 Promise 对象。 */ getErrMsgPromise(errMsg) { return new Promise(resolve => { resolve(errMsg); }) } /** * @function IPortalUser.prototype.uploadDataRequest * @description 上传数据。 * @version 10.1.0 * @param {number} id - 上传数据的资源ID。 * @param {Object} formData - 请求体为文本数据流。 * @returns {Promise} 返回包含上传数据操作的 Promise 对象。 */ uploadDataRequest(id,formData) { var uploadDataUrl = this.iportalUrl + "/web/mycontent/datas/"+id+"/upload.json"; return this.request("POST",uploadDataUrl,formData); } /** * @function IPortalUser.prototype.addData * @description 上传/注册数据。 * @version 10.1.0 * @param {IPortalAddDataParam} params - 上传/注册数据所需的参数。 * @param {Object} [formData] - 请求体为文本数据流(上传数据时传入)。 * @returns {Promise} 返回上传/注册数据的 Promise 对象。 */ addData(params,formData) { if(!(params instanceof IPortalAddDataParam)){ return this.getErrMsgPromise("params is not instanceof iPortalAddDataParam !"); } var datasUrl = this.iportalUrl + "/web/mycontent/datas.json"; var entity = { fileName:params.fileName, tags:params.tags, type:params.type }; var type = params.type.toLowerCase(); var dataMetaInfo; if(type === "excel" || type === "csv"){ if(!(params.dataMetaInfo instanceof IPortalDataMetaInfoParam)){ return this.getErrMsgPromise("params.dataMetaInfo is not instanceof iPortalDataMetaInfoParam !"); } dataMetaInfo = { xField:params.dataMetaInfo.xField, yField:params.dataMetaInfo.yField } if(type === 'csv') { dataMetaInfo.fileEncoding = params.dataMetaInfo.fileEncoding } entity.coordType = "WGS84"; entity.dataMetaInfo = dataMetaInfo; }else if(type === "hdfs" || type === "hbase") { if(!(params.dataMetaInfo instanceof IPortalDataMetaInfoParam)){ return this.getErrMsgPromise("params.dataMetaInfo is not instanceof iPortalDataMetaInfoParam !"); } if(!(params.dataMetaInfo.dataStoreInfo instanceof IPortalDataStoreInfoParam)){ return this.getErrMsgPromise("params.dataMetaInfo.dataStoreInfo is not instanceof iPortalDataStoreInfoParam !"); } var dataStoreInfo = { type:params.dataMetaInfo.dataStoreInfo.type } switch (type) { case "hdfs": dataStoreInfo.url = params.dataMetaInfo.dataStoreInfo.url; dataMetaInfo = { url: params.dataMetaInfo.url, dataStoreInfo:dataStoreInfo } break; case "hbase": if(!(params.dataMetaInfo.dataStoreInfo.connectionInfo instanceof IPortalDataConnectionInfoParam)){ return this.getErrMsgPromise("params.dataMetaInfo.dataStoreInfo.connectionInfo is not instanceof iPortalDataConnectionInfoParam !"); } dataStoreInfo.connectionInfo = { dataBase:params.dataMetaInfo.dataStoreInfo.connectionInfo.dataBase, server:params.dataMetaInfo.dataStoreInfo.connectionInfo.server, engineType:'HBASE' } dataStoreInfo.datastoreType = "SPATIAL";//该字段SPATIAL表示HBASE注册 dataMetaInfo = { dataStoreInfo:dataStoreInfo } break; } entity.dataMetaInfo = dataMetaInfo; } return this.request("POST",datasUrl,JSON.stringify(entity)).then(res=>{ if(type === "hdfs" || type === "hbase"){ return res; }else { if(res.childID) { return this.uploadDataRequest(res.childID,formData); }else { return res.customResult; } } }) } /** * @function IPortalUser.prototype.publishOrUnpublish * @description 发布/取消发布。 * @version 10.1.0 * @param {Object} options - 发布/取消发布数据服务所需的参数。 * @param {Object} options.dataId - 数据项ID。 * @param {Object} options.serviceType - 发布的服务类型,目前支持发布的服务类型包括:RESTDATA, RESTMAP, RESTREALSPACE, RESTSPATIALANALYST。 * @param {Object} [options.dataServiceId] - 发布的服务 ID。 * @param {boolean} forPublish - 是否取消发布。 * @returns {Promise} 返回发布/取消发布数据服务的 Promise 对象。 */ publishOrUnpublish(option,forPublish){ if(!option.dataId || !option.serviceType) { return this.getErrMsgPromise("option.dataID and option.serviceType are Required!"); } var dataId = option.dataId; var dataServiceId = option.dataServiceId; var serviceType = option.serviceType; var publishUrl = this.iportalUrl + "/web/mycontent/datas/" + dataId + "/publishstatus.json?serviceType=" + serviceType; if (dataServiceId) { publishUrl += "&dataServiceId=" + dataServiceId; } return this.request("PUT",publishUrl,JSON.stringify(forPublish)).then(res=>{ // 发起服务状态查询 if(forPublish) { // 发布服务的结果异步处理 // var publishStateUrl = this.iportalUrl + "web/mycontent/datas/" + dataId + "/publishstatus.rjson"; if (!dataServiceId) { // 发布服务时会回传serviceIDs,发布服务之前serviceIDs为空 dataServiceId = res.customResult; } return dataServiceId; }else { // 取消发布的结果同步处理 return res; } }); } /** * @function IPortalUser.prototype.getDataPublishedStatus * @description 查询服务状态,发起服务状态查询。 * @version 10.1.0 * @param {number} dataId - 查询服务状态的数据项ID。 * @param {string} dataServiceId - 发布的服务ID。 * @returns {Promise} 返回查询服务状态的 Promise 对象。 */ getDataPublishedStatus(dataId,dataServiceId){ var publishStateUrl = this.iportalUrl + "/web/mycontent/datas/" + dataId + "/publishstatus.json?dataServiceId="+dataServiceId+"&forPublish=true"; return this.request("GET",publishStateUrl); } /** * @function IPortalUser.prototype.unPublishedDataService * @description 取消发布。 * @version 10.1.0 * @param {Object} options - 取消发布服务具体参数。 * @param {Object} options.dataId - 数据项ID。 * @param {Object} options.serviceType - 发布的服务类型,目前支持发布的服务类型包括:RESTDATA, RESTMAP, RESTREALSPACE, RESTSPATIALANALYST。 * @param {Object} [options.dataServiceId] - 发布的服务 ID。 * @returns {Promise} 返回取消发布数据服务的 Promise 对象。 */ unPublishDataService(option){ return this.publishOrUnpublish(option,false); } /** * @function IPortalUser.prototype.publishedDataService * @description 发布数据服务。 * @version 10.1.0 * @param {Object} options - 发布数据服务具体参数。 * @param {Object} options.dataId - 数据项ID。 * @param {Object} options.serviceType - 发布的服务类型,目前支持发布的服务类型包括:RESTDATA, RESTMAP, RESTREALSPACE, RESTSPATIALANALYST。 * @param {Object} [options.dataServiceId] - 发布的服务 ID。 * @returns {Promise} 返回发布数据服务的 Promise 对象。 */ publishDataService(option){ return this.publishOrUnpublish(option,true); } } ;// CONCATENATED MODULE: ./src/common/iPortal/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/iServer/CommonServiceBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class CommonServiceBase * @deprecatedclass SuperMap.CommonServiceBase * @category iServer Core * @classdesc 对接 iServer 各种服务的 Service 的基类。 * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class CommonServiceBase { constructor(url, options) { let me = this; this.EVENT_TYPES = ['processCompleted', 'processFailed']; this.events = null; this.eventListeners = null; this.url = null; this.urls = null; this.proxy = null; this.index = null; this.length = null; this.options = null; this.totalTimes = null; this.POLLING_TIMES = 3; this._processSuccess = null; this._processFailed = null; this.isInTheSameDomain = null; this.withCredentials = false; if (Util.isArray(url)) { me.urls = url; me.length = url.length; me.totalTimes = me.length; if (me.length === 1) { me.url = url[0]; } else { me.index = parseInt(Math.random() * me.length); me.url = url[me.index]; } } else { me.totalTimes = 1; me.url = url; } if (Util.isArray(url) && !me.isServiceSupportPolling()) { me.url = url[0]; me.totalTimes = 1; } options = options || {}; this.crossOrigin = options.crossOrigin; this.headers = options.headers; Util.extend(this, options); me.isInTheSameDomain = Util.isInTheSameDomain(me.url); me.events = new Events(me, null, me.EVENT_TYPES, true); if (me.eventListeners instanceof Object) { me.events.on(me.eventListeners); } this.CLASS_NAME = 'SuperMap.CommonServiceBase'; } /** * @function CommonServiceBase.prototype.destroy * @description 释放资源,将引用的资源属性置空。 */ destroy() { let me = this; if (Util.isArray(me.urls)) { me.urls = null; me.index = null; me.length = null; me.totalTimes = null; } me.url = null; me.options = null; me._processSuccess = null; me._processFailed = null; me.isInTheSameDomain = null; me.EVENT_TYPES = null; if (me.events) { me.events.destroy(); me.events = null; } if (me.eventListeners) { me.eventListeners = null; } } /** * @function CommonServiceBase.prototype.request * @description: 该方法用于向服务发送请求。 * @param {Object} options - 参数。 * @param {string} [options.method='GET'] - 请求方式,包括 "GET","POST","PUT","DELETE"。 * @param {string} [options.url] - 发送请求的地址。 * @param {Object} [options.params] - 作为查询字符串添加到 URL 中的一组键值对,此参数只适用于 GET 方式发送的请求。 * @param {string} [options.data] - 发送到服务器的数据。 * @param {function} options.success - 请求成功后的回调函数。 * @param {function} options.failure - 请求失败后的回调函数。 * @param {Object} [options.scope] - 如果回调函数是对象的一个公共方法,设定该对象的范围。 * @param {boolean} [options.isInTheSameDomain] - 请求是否在当前域中。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 */ request(options) { const format = options.scope.format; if (format && !this.supportDataFormat(format)) { throw new Error(`${this.CLASS_NAME} is not surport ${format} format!`); } let me = this; options.url = options.url || me.url; if (this._returnContent(options) && !options.url.includes('returnContent=true')) { options.url = Util.urlAppend(options.url, 'returnContent=true'); } options.proxy = options.proxy || me.proxy; options.withCredentials = options.withCredentials != undefined ? options.withCredentials : me.withCredentials; options.crossOrigin = options.crossOrigin != undefined ? options.crossOrigin : me.crossOrigin; options.headers = options.headers || me.headers; options.isInTheSameDomain = me.isInTheSameDomain; options.withoutFormatSuffix = options.scope.withoutFormatSuffix || false; //为url添加安全认证信息片段 options.url = SecurityManager.appendCredential(options.url); me.calculatePollingTimes(); me._processSuccess = options.success; me._processFailed = options.failure; options.scope = me; options.success = me.getUrlCompleted; options.failure = me.getUrlFailed; me.options = options; me._commit(me.options); } /** * @function CommonServiceBase.prototype.getUrlCompleted * @description 请求成功后执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ getUrlCompleted(result) { let me = this; me._processSuccess(result); } /** * @function CommonServiceBase.prototype.getUrlFailed * @description 请求失败后执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ getUrlFailed(result) { let me = this; if (me.totalTimes > 0) { me.totalTimes--; me.ajaxPolling(); } else { me._processFailed(result); } } /** * * @function CommonServiceBase.prototype.ajaxPolling * @description 请求失败后,如果剩余请求失败次数不为 0,重新获取 URL 发送请求。 */ ajaxPolling() { let me = this, url = me.options.url, re = /^http:\/\/([a-z]{9}|(\d+\.){3}\d+):\d{0,4}/; me.index = parseInt(Math.random() * me.length); me.url = me.urls[me.index]; url = url.replace(re, re.exec(me.url)[0]); me.options.url = url; me.options.isInTheSameDomain = Util.isInTheSameDomain(url); me._commit(me.options); } /** * @function CommonServiceBase.prototype.calculatePollingTimes * @description 计算剩余请求失败执行次数。 */ calculatePollingTimes() { let me = this; if (me.times) { if (me.totalTimes > me.POLLING_TIMES) { if (me.times > me.POLLING_TIMES) { me.totalTimes = me.POLLING_TIMES; } else { me.totalTimes = me.times; } } else { if (me.times < me.totalTimes) { me.totalTimes = me.times; } } } else { if (me.totalTimes > me.POLLING_TIMES) { me.totalTimes = me.POLLING_TIMES; } } me.totalTimes--; } /** * @function CommonServiceBase.prototype.isServiceSupportPolling * @description 判断服务是否支持轮询。 */ isServiceSupportPolling() { let me = this; return !( me.CLASS_NAME === 'SuperMap.REST.ThemeService' || me.CLASS_NAME === 'SuperMap.REST.EditFeaturesService' ); } /** * @function CommonServiceBase.prototype.serviceProcessCompleted * @description 状态完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ serviceProcessCompleted(result) { result = Util.transformResult(result); this.events.triggerEvent('processCompleted', { result: result }); } /** * @function CommonServiceBase.prototype.serviceProcessFailed * @description 状态失败,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ serviceProcessFailed(result) { result = Util.transformResult(result); let error = result.error || result; this.events.triggerEvent('processFailed', { error: error }); } _returnContent(options) { if (options.scope.format === DataFormat.FGB) { return false; } if (options.scope.returnContent) { return true; } return false; } supportDataFormat(foramt) { return this.dataFormat().includes(foramt); } dataFormat() { return [DataFormat.GEOJSON, DataFormat.ISERVER]; } _commit(options) { if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') { if (options.params) { options.url = Util.urlAppend(options.url, Util.getParameterString(options.params || {})); } if (typeof options.data === 'object') { try { options.params = Util.toJSON(options.data); } catch (e) { console.log('不是json对象'); } } else { options.params = options.data; } } FetchRequest.commit(options.method, options.url, options.params, { headers: options.headers, withoutFormatSuffix: options.withoutFormatSuffix, withCredentials: options.withCredentials, crossOrigin: options.crossOrigin, timeout: options.async ? 0 : null, proxy: options.proxy }) .then(function (response) { if (response.text) { return response.text(); } if (response.json) { return response.json(); } return response; }) .then(function (text) { let requestResult = text; if (typeof text === 'string') { requestResult = new JSONFormat().read(text); } if ( !requestResult || requestResult.error || (requestResult.code >= 300 && requestResult.code !== 304) ) { if (requestResult && requestResult.error) { requestResult = { error: requestResult.error }; } else { requestResult = { error: requestResult }; } } if (requestResult && options.scope.format === DataFormat.FGB) { requestResult.newResourceLocation = requestResult.newResourceLocation.replace('.json', '') + '.fgb'; } return requestResult; }) .catch(function (e) { return { error: e }; }) .then((requestResult) => { if (requestResult.error) { var failure = options.scope ? FunctionExt.bind(options.failure, options.scope) : options.failure; failure(requestResult); } else { requestResult.succeed = requestResult.succeed == undefined ? true : requestResult.succeed; var success = options.scope ? FunctionExt.bind(options.success, options.scope) : options.success; success(requestResult); } }); } } /** * 服务器请求回调函数。 * @callback RequestCallback * @category BaseTypes Util * @example * var requestCallback = function (serviceResult){ * console.log(serviceResult.result); * } * new QueryService(url).queryByBounds(param, requestCallback); * @param {Object} serviceResult * @param {Object} serviceResult.result 服务器返回结果。 * @param {Object} serviceResult.object 发布应用程序事件的对象。 * @param {Object} serviceResult.type 事件类型。 * @param {Object} serviceResult.element 接受浏览器事件的 DOM 节点。 */ ;// CONCATENATED MODULE: ./src/common/iServer/GeoCodingParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeoCodingParameter * @deprecatedclass SuperMap.GeoCodingParameter * @category iServer AddressMatch * @classdesc 地理正向匹配参数类。 * @param {Object} options - 参数。 * @param {string} options.address - 地点关键词。 * @param {number} [options.fromIndex] - 设置返回对象的起始索引值。 * @param {number} [options.toIndex] - 设置返回对象的结束索引值。 * @param {Array.} [options.filters] - 过滤字段,限定查询区域。 * @param {string} [options.prjCoordSys] - 查询结果的坐标系。 * @param {number} [options.maxReturn] - 最大返回结果数。 * @usage */ class GeoCodingParameter { constructor(options) { if (options.filters && typeof(options.filters) === 'string') { options.filters = options.filters.split(','); } /** * @member {string} GeoCodingParameter.prototype.address * @description 地点关键词。 */ this.address = null; /** * @member {number} [GeoCodingParameter.prototype.fromIndex] * @description 设置返回对象的起始索引值。 */ this.fromIndex = null; /** * @member {number} [GeoCodingParameter.prototype.toIndex] * @description 设置返回对象的结束索引值。 */ this.toIndex = null; /** * @member {Array.} [GeoCodingParameter.prototype.filters] * @description 过滤字段,限定查询区域。 */ this.filters = null; /** * @member {string} [GeoCodingParameter.prototype.prjCoordSys] * @description 查询结果的坐标系。 */ this.prjCoordSys = null; /** * @member {number} [GeoCodingParameter.prototype.maxReturn] * @description 最大返回结果数。 */ this.maxReturn = null; Util.extend(this, options); } /** * @function GeoCodingParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.address = null; this.fromIndex = null; this.toIndex = null; this.filters = null; this.prjCoordSys = null; this.maxReturn = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/GeoDecodingParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeoDecodingParameter * @deprecatedclass SuperMap.GeoDecodingParameter * @category iServer AddressMatch * @classdesc 地理反向匹配参数类。 * @param {Object} options - 参数。 * @param {number} options.x - 查询位置的横坐标。 * @param {number} options.y - 查询位置的纵坐标。 * @param {number} [options.fromIndex] - 设置返回对象的起始索引值。 * @param {Array.} [options.filters] - 过滤字段,限定查询区域。 * @param {string} [options.prjCoordSys] - 查询结果的坐标系。 * @param {number} [options.maxReturn] - 最大返回结果数。 * @param {number} [options.geoDecodingRadius] - 查询半径。 * @usage */ class GeoDecodingParameter { constructor(options) { if (options.filters) { options.filters = options.filters.split(','); } /** * @member {number} GeoDecodingParameter.prototype.x * @description 查询位置的横坐标。 */ this.x = null; /** * @member {number} GeoDecodingParameter.prototype.y * @description 查询位置的纵坐标。 */ this.y = null; /** * @member {number} [GeoDecodingParameter.prototype.fromIndex] * @description 设置返回对象的起始索引值。 */ this.fromIndex = null; /** * @member {number} [GeoDecodingParameter.prototype.toIndex] * @description 设置返回对象的结束索引值。 */ this.toIndex = null; /** * @member {Array.} [GeoDecodingParameter.prototype.filters] * @description 过滤字段,限定查询区域。 */ this.filters = null; /** * @member {string} [GeoDecodingParameter.prototype.prjCoordSys] * @description 查询结果的坐标系。 */ this.prjCoordSys = null; /** * @member {number} [GeoDecodingParameter.prototype.maxReturn] * @description 最大返回结果数。 */ this.maxReturn = null; /** * @member {number} GeoDecodingParameter.prototype.geoDecodingRadius * @description 查询半径。 */ this.geoDecodingRadius = null; Util.extend(this, options); } /** * @function GeoDecodingParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.x = null; this.y = null; this.fromIndex = null; this.toIndex = null; this.filters = null; this.prjCoordSys = null; this.maxReturn = null; this.geoDecodingRadius = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/AddressMatchService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class AddressMatchService * @deprecatedclass SuperMap.AddressMatchService * @category iServer AddressMatch * @classdesc 地址匹配服务,包括正向匹配和反向匹配。 * @param {string} url - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class AddressMatchService_AddressMatchService extends CommonServiceBase { constructor(url, options) { super(url, options); this.options = options || {}; this.CLASS_NAME = 'SuperMap.AddressMatchService'; } /** * @function AddressMatchService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function AddressMatchService.prototype.code * @param {string} url - 正向地址匹配服务地址。 * @param {GeoCodingParameter} params - 正向地址匹配服务参数。 */ code(url, params) { if (!(params instanceof GeoCodingParameter)) { return; } this.processAsync(url, params); } /** * @function AddressMatchService.prototype.decode * @param {string} url - 反向地址匹配服务地址。 * @param {GeoDecodingParameter} params - 反向地址匹配服务参数。 */ decode(url, params) { if (!(params instanceof GeoDecodingParameter)) { return; } this.processAsync(url, params); } /** * @function AddressMatchService.prototype.processAsync * @description 负责将客户端的动态分段服务参数传递到服务端。 * @param {string} url - 服务地址。 * @param {Object} params - 参数。 */ processAsync(url, params) { this.request({ method: 'GET', url, params, scope: this, success: this.serviceProcessCompleted, failure: this.serviceProcessFailed }); } /** * @function AddressMatchService.prototype.serviceProcessCompleted * @param {Object} result - 服务器返回的结果对象。 * @description 服务流程是否完成 */ serviceProcessCompleted(result) { if (result.succeed) { delete result.succeed; } super.serviceProcessCompleted(result); } /** * @function AddressMatchService.prototype.serviceProcessCompleted * @param {Object} result - 服务器返回的结果对象。 * @description 服务流程是否失败 */ serviceProcessFailed(result) { super.serviceProcessFailed(result); } } ;// CONCATENATED MODULE: ./src/common/iServer/AggregationParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class AggregationParameter * @deprecatedclass SuperMap.AggregationParameter * @classdesc 聚合查询参数设置,该参数仅支持数据来源 Elasticsearch 服务的数据服务。 * @category iServer Data FeatureResults * @param {Object} options - 参数。 * @param {string} options.aggName - 聚合名称。 * @param {string} options.aggFieldName - 聚合字段。 * @usage */ class AggregationParameter { constructor(options) { /** * @member {string} AggregationParameter.prototype.aggName * @description 聚合名称。 */ this.aggName = null; /** * @member {string} AggregationParameter.prototype.aggFieldName * @description 聚合字段。 */ this.aggFieldName = null; this.CLASS_NAME = 'SuperMap.AggregationParameter'; Util.extend(this, options); } destroy() { var me = this; me.aggName = null; me.aggFieldName = null; me.aggType = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/BucketAggParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BucketAggParameter * @deprecatedclass SuperMap.BucketAggParameter * @classdesc 子聚合类查询参数设置,该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 * @category iServer Data FeatureResults * @param {Object} options - 参数。 * @param {Array.} options.subAggs - 子聚合类集合。 * @extends {AggregationParameter} * @usage */ class BucketAggParameter extends AggregationParameter { constructor(options) { super(); /** * @member {Array.} BucketAggParameter.prototype.subAggs * @description 子聚合类集合。 */ this.subAggs = null; this.aggType = null; this.CLASS_NAME = 'SuperMap.BucketAggParameter'; Util.extend(this, options); } destroy() { var me = this; if (me.subAggs) { me.subAggs = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/MetricsAggParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MetricsAggParameter * @deprecatedclass SuperMap.MetricsAggParameter * @classdesc 指标聚合查询参数类,该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 * @category iServer Data FeatureResults * @param {Object} options - 可选参数。 * @param {MetricsAggType} [options.aggType = 'avg'] - 聚合类型。 * @extends {AggregationParameter} * @usage */ class MetricsAggParameter extends AggregationParameter { constructor(option) { super(); /** * @member {MetricsAggType} [MetricsAggParameter.prototype.aggType=MetricsAggType.AVG] * @description 指标聚合类型。 */ this.aggType = MetricsAggType.AVG; Util.extend(this, option); this.CLASS_NAME = 'SuperMap.MetricsAggParameter'; } destroy() { super.destroy(); var me = this; me.aggType = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/AreaSolarRadiationParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class AreaSolarRadiationParameters * @deprecatedclass SuperMap.AreaSolarRadiationParameters * @category iServer SpatialAnalyst SolarRadiationAnalyst * @classdesc 地区太阳辐射参数类。 * @param {Object} options - 参数。 * @param {string} options.dataset - 要用来做地区太阳辐射数据源中数据集的名称。该名称用形如"数据集名称@数据源别名"的形式来表示,例如:JingjinTerrain@Jingjin。 * @param {string} options.targetDatasourceName - 指定的存储结果数据集的数据源名称, 例如:"Jingjin"。 * @param {string} options.totalGridName - 指定地区太阳辐射总辐射量数据集的名称。 * @param {string} options.diffuseDatasetGridName - 指定地区太阳辐射散射辐射量数据集的名称。 * @param {string} options.durationDatasetGridName - 指定地区太阳辐射太阳直射持续时间数据集的名称。 * @param {string} options.directDatasetGridName - 指定地区太阳辐射直射辐射量数据集的名称。 * @param {number} options.latitude - 待计算区域的纬度值。 * @param {string} [options.timeMode = 'MULTIDAYS'] - 时间模式。可选值"WITHINDAY"(单日)或"MULTIDAYS"(多日)。 * @param {number} options.dayStart - 起始日期(年内的第几天)。 * @param {number} options.dayEnd - 结束日期(年内的第几天)。 * @param {number} [options.hourStart] - 起始时间(一天中的第几个小时)。 * @param {number} [options.hourEnd] - 结束时间(一天中的第几个小时)。 * @param {number} [options.transmittance] - 太阳辐射穿过大气的透射率。 * @param {number} [options.hourInterval=0.5] - 计算时的小时间隔(设置的越小计算量越大并且计算结果更精确,如果修改此参数,必须使用整数)。 * @param {number} [options.dayInterval=5] - 计算时的天数间隔(设置的越小计算量越大并且计算结果更精确,必须使用整数)。 * @param {boolean} [options.deleteExistResultDataset=false] - 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 * @usage */ class AreaSolarRadiationParameters { constructor(options) { /** * @member {string} AreaSolarRadiationParameters.prototype.dataset * @description 要用来做地区太阳辐射数据源中数据集的名称。该名称用形如“数据集名称@数据源别名”形式来表示,例如:JingjinTerrain@Jingjin。注:地区太阳辐射数据必须为栅格数据集。 */ this.dataset = null; /** * @member {string} AreaSolarRadiationParameters.prototype.targetDatasourceName * @description 指定的存储结果数据集的数据源名称,例如:"Jingjin"。 */ this.targetDatasourceName = null; /** * @member {string} AreaSolarRadiationParameters.prototype.totalGridName * @description 指定地区太阳辐射总辐射量数据集的名称。 */ this.totalGridName = null; /** * @member {string} AreaSolarRadiationParameters.prototype.diffuseDatasetGridName * @description 指定地区太阳辐射散射辐射量数据集的名称。 */ this.diffuseDatasetGridName = null; /** * @member {string} AreaSolarRadiationParameters.prototype.durationDatasetGridName * @description 指定地区太阳辐射太阳直射持续时间数据集的名称。 */ this.durationDatasetGridName = null; /** * @member {string} AreaSolarRadiationParameters.prototype.directDatasetGridName * @description 指定地区太阳辐射直射辐射量数据集的名称。 */ this.directDatasetGridName = null; /** * @member {number} AreaSolarRadiationParameters.prototype.latitude * @description 待计算区域的纬度值。 */ this.latitude = null; /** * @member {string} [AreaSolarRadiationParameters.prototype.timeMode='MULTIDAYS'] * @description 时间模式。可选值"WITHINDAY"(单日)或"MULTIDAYS"(多日)。 */ this.timeMode = "MULTIDAYS"; /** * @member {number} AreaSolarRadiationParameters.prototype.dayStart * @description 起始日期(年内的第几天)。 */ this.dayStart = null; /** * @member {number} AreaSolarRadiationParameters.prototype.dayEnd * @description 结束日期(年内的第几天)。 */ this.dayEnd = null; /** * @member {number} [AreaSolarRadiationParameters.prototype.hourStart] * @description 起始时间(一天中的第几个小时)。 */ this.hourStart = null; /** * @member {number} [AreaSolarRadiationParameters.prototype.hourEnd] * @description 结束时间(一天中的第几个小时)。 */ this.hourEnd = null; /** * @member {number} [AreaSolarRadiationParameters.prototype.transmittance] * @description 太阳辐射穿过大气的透射率。 */ this.transmittance = null; /** * @member {number} [AreaSolarRadiationParameters.prototype.hourInterval=0.5] * @description 计算时的小时间隔(设置的越小计算量越大并且计算结果更精确, 如果修改此参数,必须使用整数) */ this.hourInterval = null; /** * @member {number} [AreaSolarRadiationParameters.prototype.dayInterval=5] * @description 计算时的天数间隔(设置的越小计算量越大并且计算结果更精确, 必须使用整数) */ this.dayInterval = null; /** * @member {boolean} [AreaSolarRadiationParameters.prototype.deleteExistResultDataset=false] * @description 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 */ this.deleteExistResultDataset = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.AreaSolarRadiationParameters"; } /** * @function AreaSolarRadiationParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.dataset = null; me.zFactor = 1.0; me.averageCurvatureName = null; me.profileCurvatureName = null; me.planCurvatureName = null; me.deleteExistResultDataset = true; } /** * @function AreaSolarRadiationParameters.toObject * @param {AreaSolarRadiationParameters} param - 地区太阳辐射参数类。 * @param {AreaSolarRadiationParameters} tempObj - 地区太阳辐射参数对象。 * @returns {Object} JSON对象。 * @description 将AreaSolarRadiationParameters对象转换成JSON对象。 */ static toObject(param, tempObj) { var parameter = {}; for (var name in param) { if (name !== "dataset") { var name1 = (name === "latitude" || name === "timeMode" || name === "dayStart"); var name2 = (name === "dayEnd" || name === "hourStart" || name === "hourEnd"); var name3 = (name === "transmittance" || name === "hourInterval" || name === "dayInterval"); if (name1 || name2 || name3) { parameter[name] = param[name]; } else { tempObj[name] = param[name]; } } } tempObj["parameter"] = parameter; } } ;// CONCATENATED MODULE: ./src/common/iServer/SpatialAnalystBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SpatialAnalystBase * @deprecatedclass SuperMap.SpatialAnalystBase * @category iServer Core * @classdesc 空间分析服务基类。 * @param {string} url - 地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {CommonServiceBase} * @usage */ class SpatialAnalystBase extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {DataFormat} [SpatialAnalystBase.prototype.format=DataFormat.GEOJSON] * @description 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 */ this.format = options.format || DataFormat.GEOJSON; this.CLASS_NAME = "SuperMap.SpatialAnalystBase"; } /** * @function SpatialAnalystBase.prototype.destroy * @override */ destroy() { super.destroy(); this.format = null; } /** * @function SpatialAnalystBase.prototype.serviceProcessCompleted * @description 分析完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ serviceProcessCompleted(result) { var me = this, analystResult; result = Util.transformResult(result); if (result && me.format === DataFormat.GEOJSON && typeof me.toGeoJSONResult === 'function') { //批量分析时会返回多个结果 if (Util.isArray(result)) { for (var i = 0; i < result.length; i++) { result[i] = me.toGeoJSONResult(result[i]) } analystResult = result; } else { analystResult = me.toGeoJSONResult(result); } } if (!analystResult) { analystResult = result; } me.events.triggerEvent("processCompleted", {result: analystResult}); } /** * @function SpatialAnalystBase.prototype.toGeoJSONResult * @description 将含有 geometry 的数据转换为 GeoJSON 格式。 * @param {Object} result - 服务器返回的结果对象。 * */ toGeoJSONResult(result) { if (!result) { return null; } //批量叠加分析时结果这样处理 if (result.result && result.result.resultGeometry) { result = result.result } var geoJSONFormat = new GeoJSON(); if (result.recordsets) { for (var i = 0, recordsets = result.recordsets, len = recordsets.length; i < len; i++) { if (recordsets[i].features) { recordsets[i].features = geoJSONFormat.toGeoJSON(recordsets[i].features); } } } else if (result.recordset && result.recordset.features) { result.recordset.features =geoJSONFormat.toGeoJSON(result.recordset.features); } if (result.resultGeometry) { result.resultGeometry = geoJSONFormat.toGeoJSON(result.resultGeometry); } if (result.regions) { result.regions = geoJSONFormat.toGeoJSON(result.regions); } return result; } } ;// CONCATENATED MODULE: ./src/common/iServer/AreaSolarRadiationService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class AreaSolarRadiationService * @deprecatedclass SuperMap.AreaSolarRadiationService * @category iServer SpatialAnalyst SolarRadiationAnalyst * @classdesc 地区太阳辐射服务类。 * @param {string} url - 服务的访问地址。如:
http://localhost:8090/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst。
* @param {Object} options - 参数。
* @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 例如: * (start code) * var myAreaSolarRadiationService = new AreaSolarRadiationService(url); * myAreaSolarRadiationService.on({ * "processCompleted": processCompleted, * "processFailed": processFailed * } * ); * (end) * @usage */ class AreaSolarRadiationService extends SpatialAnalystBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.AreaSolarRadiationService"; } /** * @function AreaSolarRadiationService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function AreaSolarRadiationService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {AreaSolarRadiationParameters} parameter - 地区太阳辐射参数。 */ processAsync(parameter) { if (!(parameter instanceof AreaSolarRadiationParameters)) { return; } var me = this; var parameterObject = {}; if (parameter instanceof AreaSolarRadiationParameters) { me.url = Util.urlPathAppend(me.url, `datasets/${parameter.dataset}/solarradiation`); } me.url = Util.urlAppend(me.url, 'returnContent=true'); AreaSolarRadiationParameters.toObject(parameter, parameterObject); var jsonParameters = Util.toJSON(parameterObject); me.request({ method: 'POST', data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/BufferDistance.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BufferDistance * @deprecatedclass SuperMap.BufferDistance * @category iServer SpatialAnalyst BufferAnalyst * @classdesc 缓冲区分析的缓冲距离类。通过该类可以设置缓冲区分析的缓冲距离,距离可以是数值也可以是数值型的字段表达式。 * @param {Object} options - 可选参数。 * @param {string} [options.exp] - 以数值型的字段表达式作为缓冲区分析的距离值。 * @param {number} [options.value=100] - 以数值作为缓冲区分析的距离值。单位:米。 * @usage */ class BufferDistance { constructor(options) { /** * @member {string} [BufferDistance.prototype.exp] * @description 以数值型的字段表达式作为缓冲区分析的距离值。 */ this.exp = null; /** * @member {number} [BufferDistance.prototype.value=100] * @description 以数值作为缓冲区分析的距离值。单位:米。 */ this.value = 100; Util.extend(this, options); this.CLASS_NAME = "SuperMap.BufferDistance"; } /** * @function BufferDistance.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.exp = null; this.value = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/BufferSetting.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BufferSetting * @deprecatedclass SuperMap.BufferSetting * @category iServer SpatialAnalyst BufferAnalyst * @classdesc 缓冲区分析通用设置类。 * @param {Object} options - 可选参数。 * @param {BufferEndType} [options.endType=BufferEndType.FLAT] - 缓冲区端点枚举值。 * @param {BufferDistance} [options.leftDistance=100] - 左侧缓冲距离。 * @param {BufferDistance} [options.rightDistance=100] - 右侧缓冲距离。 * @param {number} [options.semicircleLineSegment=4] - 圆头缓冲圆弧处线段的个数。 * @param {BufferRadiusUnit} [options.radiusUnit=BufferRadiusUnit.METER] - 缓冲半径单位。 * @usage */ class BufferSetting { constructor(options) { /** * @member {BufferEndType} [BufferSetting.prototype.endType = BufferEndType.FLAT] * @description 缓冲区端点枚举值。分为平头和圆头两种。 */ this.endType = BufferEndType.FLAT; /** * @member {BufferDistance} [BufferSetting.prototype.leftDistance=100] * @description 左侧缓冲距离。 * 当为 GeometryBufferAnalyst 时,单位为默认地图的投影系的单位(如3857为米,4326为度), * 当为 DatasetBufferAnalyst 时,单位通过{@link BufferSetting.radiusUnit}设置(默认全部为米)。 */ this.leftDistance = new BufferDistance(); /** * @member {BufferDistance} [BufferSetting.prototype.rightDistance=100] * @description 右侧缓冲距离。 * 当为 GeometryBufferAnalyst 时,单位为默认地图的投影系的单位(如3857为米,4326为度), * 当为 DatasetBufferAnalyst 时,单位通过{@link BufferSetting#radiusUnit}设置(默认全部为米)。 */ this.rightDistance = new BufferDistance(); /** * @member {number} [BufferSetting.prototype.semicircleLineSegment=4] * @description 圆头缓冲圆弧处线段的个数。即用多少个线段来模拟一个半圆。 */ this.semicircleLineSegment = 4; /** * @member {BufferRadiusUnit} [BufferSetting.prototype.radiusUnit = BufferRadiusUnit.METER] * @description 缓冲半径单位,可以是{@link BufferRadiusUnit.METER}、{@link BufferRadiusUnit.MILLIMETER}、 * {@link BufferRadiusUnit.CENTIMETER}、{@link BufferRadiusUnit.DECIMETER}、{@link BufferRadiusUnit.KILOMETER}、 * {@link BufferRadiusUnit.FOOT}、{@link BufferRadiusUnit.INCH}、{@link BufferRadiusUnit.MILE}、{@link BufferRadiusUnit.YARD}。 * 仅对BufferAnalyst有效。 */ this.radiusUnit = BufferRadiusUnit.METER; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.BufferSetting"; } /** * @function BufferSetting.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { let me = this; me.endType = null; if (me.leftDistance) { me.leftDistance.destroy(); me.leftDistance = null; } if (me.rightDistance) { me.rightDistance.destroy(); me.rightDistance = null; } me.semicircleLineSegment = null; me.radiusUnit = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/BufferAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BufferAnalystParameters * @deprecatedclass SuperMap.BufferAnalystParameters * @category iServer SpatialAnalyst BufferAnalyst * @classdesc 缓冲区分析参数基类。 * @param {Object} options - 参数。 * @param {BufferSetting} [options.bufferSetting] - 设置缓冲区通用参数。为缓冲区分析提供必要的参数信息,包括左缓冲距离、右缓冲距离、端点类型、圆头缓冲圆弧处线段的个数信息。 * @usage */ class BufferAnalystParameters { constructor(options) { var me = this; /** * @member {BufferSetting} [BufferAnalystParameters.prototype.bufferSetting] * @description 设置缓冲区通用参数。为缓冲区分析提供必要的参数信息,包括左缓冲距离、右缓冲距离、端点类型、圆头缓冲圆弧处线段的个数信息。 */ me.bufferSetting = new BufferSetting(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.BufferAnalystParameters"; } /** * @function BufferAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.bufferSetting) { me.bufferSetting.destroy(); me.bufferSetting = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/DataReturnOption.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DataReturnOption * @deprecatedclass SuperMap.DataReturnOption * @category iServer Data Dataset * @classdesc 数据返回设置类。 * @param {Object} options - 参数。 * @param {number} [options.expectCount=1000] - 设置返回的最大记录数,小于或者等于 0 时表示返回所有记录数。 * @param {string} [options.dataset] - 设置结果数据集标识,当 dataReturnMode 为 {@link DataReturnMode.DATASET_ONLY}或{@link DataReturnMode.DATASET_AND_RECORDSET}时有效, * 作为返回数据集的名称。该名称用形如“数据集名称@数据源别名”形式来表示。 * @param {DataReturnMode} [options.dataReturnMode=DataReturnMode.RECORDSET_ONLY] - 数据返回模式。 * @param {boolean} [options.deleteExistResultDataset=true] - 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 * @usage */ class DataReturnOption { constructor(options) { /** * @member {number} [DataReturnOption.prototype.expectCount=1000] * @description 设置返回的最大记录数,小于或者等于0时表示返回所有记录数。 */ this.expectCount = 1000; /** * @member {string} [DataReturnOption.prototype.dataset] * @description 设置结果数据集标识,当dataReturnMode为 {@link DataReturnMode.DATASET_ONLY} * 或{@link DataReturnMode.DATASET_AND_RECORDSET}时有效, * 作为返回数据集的名称。该名称用形如"数据集名称@数据源别名"形式来表示。 */ this.dataset = null; /** * @member {DataReturnMode} [DataReturnOption.prototype.dataReturnMode=DataReturnMode.RECORDSET_ONLY] * @description 数据返回模式。 */ this.dataReturnMode = DataReturnMode.RECORDSET_ONLY; /** * @member {boolean} [DataReturnOption.prototype.deleteExistResultDataset=true] * @description 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 */ this.deleteExistResultDataset = true; Util.extend(this, options); this.CLASS_NAME = "SuperMap.DataReturnOption"; } /** * @function DataReturnOption.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.expectCount = null; me.dataset = null; me.dataReturnMode = null; me.deleteExistResultDataset = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/FilterParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FilterParameter * @deprecatedclass SuperMap.FilterParameter * @category iServer Data FeatureResults * @classdesc 查询过滤条件参数类。该类用于设置查询数据集的查询过滤参数。 * @param {Object} options - 参数。 * @param {string} options.attributeFilter - 属性过滤条件。 * @param {string} options.name - 查询数据集名称或者图层名称。 * @param {Array.} [options.joinItems] - 与外部表的连接信息 JoinItem 数组。 * @param {Array.} [options.linkItems] - 与外部表的关联信息 LinkItem 数组。 * @param {Array.} [options.ids] - 查询 id 数组,即属性表中的 SmID 值。 * @param {string} [options.orderBy] - 查询排序的字段,orderBy 的字段须为数值型的。 * @param {string} [options.groupBy] - 查询分组条件的字段。 * @param {Array.} [options.fields] - 查询字段数组。 * @usage */ class FilterParameter { constructor(options) { /** * @member {string} FilterParameter.prototype.attributeFilter * @description 属性过滤条件。 * 相当于 SQL 语句中的 WHERE 子句,其格式为:WHERE <条件表达式>, * attributeFilter 就是其中的“条件表达式”。 * 该字段的用法为 attributeFilter = "过滤条件"。 * 例如,要查询字段 fieldValue 小于100的记录,设置 attributeFilter = "fieldValue < 100"; * 要查询字段 name 的值为“酒店”的记录,设置 attributeFilter = "name like '%酒店%'",等等。 */ this.attributeFilter = null; /** * @member {string} FilterParameter.prototype.name * @description 查询数据集名称或者图层名称,根据实际的查询对象而定。 * 一般情况下该字段为数据集名称,但在进行与地图相关功能的操作时, * 需要设置为图层名称(图层名称格式:数据集名称@数据源别名)。 * 因为一个地图的图层可能是来自于不同数据源的数据集, * 而不同的数据源中可能存在同名的数据集, * 使用数据集名称不能唯一的确定数据集, * 所以在进行与地图相关功能的操作时,该值需要设置为图层名称。 */ this.name = null; /** * @member {Array.} [FilterParameter.prototype.joinItems] * @description 与外部表的连接信息 JoinItem 数组。 */ this.joinItems = null; /** * @member {Array.} [FilterParameter.prototype.linkItems] * @description 与外部表的关联信息 LinkItem 数组。 */ this.linkItems = null; /** * @member {Array.} [FilterParameter.prototype.ids] * @description 查询 id 数组,即属性表中的 SmID 值。 */ this.ids = null; /** * @member {string} [FilterParameter.prototype.orderBy] * @description 查询排序的字段,orderBy的字段须为数值型的。 * 相当于 SQL 语句中的 ORDER BY 子句,其格式为:ORDER BY <列名>, * 列名即属性表中每一列的名称,列又可称为属性,在 SuperMap 中又称为字段。 * 对单个字段排序时,该字段的用法为 orderBy = "字段名"; * 对多个字段排序时,字段之间以英文逗号进行分割,用法为 orderBy = "字段名1, 字段名2"。 * 例如,现有一个国家数据集,它有两个字段分别为“SmArea”和“pop_1994”, * 分别表示国家的面积和1994年的各国人口数量。 * 如果要按照各国人口数量对记录进行排序,则 orderBy = "pop_1994"; * 如果要以面积和人口进行排序,则 orderBy = "SmArea, pop_1994"。 */ this.orderBy = null; /** * @member {string} [FilterParameter.prototype.groupBy] * @description 查询分组条件的字段。 * 相当于 SQL 语句中的 GROUP BY 子句,其格式为:GROUP BY <列名>, * 列名即属性表中每一列的名称,列又可称为属性,在 SuperMap 中又称为字段。 * 对单个字段分组时,该字段的用法为 groupBy = "字段名"; * 对多个字段分组时,字段之间以英文逗号进行分割,用法为 groupBy = "字段名1, 字段名2"。 * 例如,现有一个全球城市数据集,该数据集有两个字段分别为“Continent”和“Country”, * 分别表示某个城市所属的洲和国家。 * 如果要按照国家对全球的城市进行分组,可以设置 groupBy = "Country"; * 如果以洲和国家对城市进行分组,设置 groupBy = "Continent, Country"。 */ this.groupBy = null; /** * @member {Array.} [FilterParameter.prototype.fields] * @description 查询字段数组,如果不设置则使用系统返回的所有字段。 */ this.fields = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.FilterParameter"; } /** * @function FilterParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.attributeFilter = null; me.name = null; if (me.joinItems) { for (let i = 0, joinItems = me.joinItems, len = joinItems.length; i < len; i++) { joinItems[i].destroy(); } me.joinItems = null; } if (me.linkItems) { for (let i = 0, linkItems = me.linkItems, len = linkItems.length; i < len; i++) { linkItems[i].destroy(); } me.linkItems = null; } me.ids = null; me.orderBy = null; me.groupBy = null; me.fields = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/DatasetBufferAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasetBufferAnalystParameters * @deprecatedclass SuperMap.DatasetBufferAnalystParameters * @category iServer SpatialAnalyst BufferAnalyst * @classdesc 数据集缓冲区分析参数类。 * @param {Object} options - 参数。 * @param {string} options.dataset - 要用来做缓冲区分析的数据源中数据集的名称。该名称用形如“数据集名称@数据源别名”形式来表示。 * @param {FilterParameter} [options.filterQueryParameter] - 设置数据集中几何对象的过滤条件。只有满足此条件的几何对象才参与缓冲区分析。 * @param {DataReturnOption} [options.resultSetting] - 结果返回设置类。 * @param {boolean} [options.isAttributeRetained=true] - 是否保留进行缓冲区分析的对象的字段属性。当 isUnion 字段为 false 时该字段有效。 * @param {boolean} [options.isUnion=false] - 是否将缓冲区与源记录集中的对象合并后返回。对于面对象而言,要求源数据集中的面对象不相交。 * @param {BufferSetting} [options.bufferSetting] - 设置缓冲区通用参数。 * * @extends {BufferAnalystParameters} * @usage */ class DatasetBufferAnalystParameters extends BufferAnalystParameters { constructor(options) { super(options); /** * @member {string} DatasetBufferAnalystParameters.prototype.dataset * @description 要用来做缓冲区分析的数据源中数据集的名称。该名称用形如“数据集名称@数据源别名”形式来表示。 */ this.dataset = null; /** * @member {FilterParameter} [DatasetBufferAnalystParameters.prototype.filterQueryParameter] * @description 设置数据集中几何对象的过滤条件。只有满足此条件的几何对象才参与缓冲区分析。 */ this.filterQueryParameter = new FilterParameter(); /** * @member {DataReturnOption} [DatasetBufferAnalystParameters.prototype.resultSetting] * @description 结果返回设置类。 */ this.resultSetting = new DataReturnOption(); /** * @member {boolean} [DatasetBufferAnalystParameters.prototype.isAttributeRetained=true] * @description 是否保留进行缓冲区分析的对象的字段属性。当 isUnion 字段为 false 时该字段有效。 */ this.isAttributeRetained = true; /** * @member {boolean} [DatasetBufferAnalystParameters.prototype.isUnion=false] * @description 是否将缓冲区与源记录集中的对象合并后返回。对于面对象而言,要求源数据集中的面对象不相交。 */ this.isUnion = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.DatasetBufferAnalystParameters"; } /** * @function DatasetBufferAnalystParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.dataset = null; if (me.filterQueryParameter) { me.filterQueryParameter.destroy(); me.filterQueryParameter = null; } if (me.resultSetting) { me.resultSetting.destroy(); me.resultSetting = null; } me.isAttributeRetained = null; me.isUnion = null; } /** * @function DatasetBufferAnalystParameters.toObject * @param {DatasetBufferAnalystParameters} datasetBufferAnalystParameters - 数据集缓冲区分析参数类。 * @param {DatasetBufferAnalystParameters} tempObj - 数据集缓冲区分析参数对象。 * @description 将数据集缓冲区分析参数对象转换为 JSON 对象。 * @returns {Object} JSON 对象。 */ static toObject(datasetBufferAnalystParameters, tempObj) { for (var name in datasetBufferAnalystParameters) { if (name === "bufferSetting") { datasetBufferAnalystParameters.bufferSetting.radiusUnit = datasetBufferAnalystParameters.bufferSetting.radiusUnit.toUpperCase(); tempObj.bufferAnalystParameter = datasetBufferAnalystParameters.bufferSetting; } else if (name === "resultSetting") { tempObj.dataReturnOption = datasetBufferAnalystParameters.resultSetting; } else if (name === "dataset") { continue; } else { tempObj[name] = datasetBufferAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/GeometryBufferAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryBufferAnalystParameters * @deprecatedclass SuperMap.GeometryBufferAnalystParameters * @category iServer SpatialAnalyst BufferAnalyst * @classdesc 几何对象缓冲区分析参数类。 * 对指定的某个几何对象做缓冲区分析。通过该类可以指定要做缓冲区分析的几何对象、缓冲区参数等。 * @param {Object} options - 参数。 * @param {GeoJSONObject} options.sourceGeometry - 要做缓冲区分析的几何对象。 * @param {number} options.sourceGeometrySRID - 缓冲区几何对象投影坐标参数, 如 4326,3857。 * @param {BufferSetting} [options.bufferSetting] - 设置缓冲区通用参数。 * @extends {BufferAnalystParameters} * @usage */ class GeometryBufferAnalystParameters extends BufferAnalystParameters { constructor(options) { super(options); /** * @member {GeoJSONObject} GeometryBufferAnalystParameters.prototype.sourceGeometry * @description 要做缓冲区分析的几何对象。
* 点类型可以是:{@link GeometryPoint}|{@link L.Marker}|{@link L.CircleMarker}|{@link L.Circle}|{@link L.GeoJSON}|{@link ol.geom.Point}|{@link ol.format.GeoJSON}。
* 线类型可以是:{@link GeometryLineString}|{@link GeometryLinearRing}|{@link L.Polyline}|{@link L.GeoJSON}|{@link ol.geom.LineString}|{@link ol.format.GeoJSON}。
* 面类型可以是:{@link GeometryPolygon}|{@link L.Polygon}|{@link L.GeoJSON}|{@link ol.geom.Polygon}|{@link ol.format.GeoJSON}。 */ this.sourceGeometry = null; /** * @member {number} GeometryBufferAnalystParameters.prototype.sourceGeometrySRID * @description 缓冲区几何对象投影坐标参数, 如 4326,3857。 */ this.sourceGeometrySRID = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = " SuperMap.GeometryBufferAnalystParameters"; } /** * @function GeometryBufferAnalystParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.sourceGeometry) { me.sourceGeometry.destroy(); me.sourceGeometry = null; } } /** * @function GeometryBufferAnalystParameters.toObject * @param {GeometryBufferAnalystParameters} geometryBufferAnalystParameters - 几何对象缓冲区分析参数类。 * @param {GeometryBufferAnalystParameters} tempObj - 几何对象缓冲区分析参数对象。 * @description 将几何对象缓冲区分析参数对象转换为 JSON 对象。 * @returns {Object} JSON 对象。 */ static toObject(geometryBufferAnalystParameters, tempObj) { for (var name in geometryBufferAnalystParameters) { if (name === "bufferSetting") { var tempBufferSetting = {}; for (var key in geometryBufferAnalystParameters.bufferSetting) { tempBufferSetting[key] = geometryBufferAnalystParameters.bufferSetting[key]; } tempObj.analystParameter = tempBufferSetting; } else if (name === "sourceGeometry") { tempObj.sourceGeometry = ServerGeometry.fromGeometry(geometryBufferAnalystParameters.sourceGeometry); } else { tempObj[name] = geometryBufferAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/BufferAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BufferAnalystService * @deprecatedclass SuperMap.BufferAnalystService * @category iServer SpatialAnalyst BufferAnalyst * @classdesc 缓冲区分析服务类。 * 该类负责将客户设置的缓冲区分析参数传递给服务端,并接收服务端返回的缓冲区分析结果数据。 * 缓冲区分析结果通过该类支持的事件的监听函数参数获取。 * @param {string} url - 服务的访问地址。如:http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 例如: * (start code) * var myBufferAnalystService = new BufferAnalystService(url, { * eventListeners: { * "processCompleted": bufferCompleted, * "processFailed": bufferFailed * } * }); * (end) * @usage */ class BufferAnalystService extends SpatialAnalystBase { constructor(url, options) { super(url, options); /** * @member {string} BufferAnalystService.prototype.mode * @description 缓冲区分析类型 */ this.mode = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.BufferAnalystService"; } /** * @function BufferAnalystService.prototype.destroy * @override */ destroy() { super.destroy(); this.mode = null; } /** * @method BufferAnalystService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {BufferAnalystParameters} parameter - 缓冲区分析参数 */ processAsync(parameter) { var parameterObject = {}; var me = this; if (parameter instanceof DatasetBufferAnalystParameters) { me.mode = 'datasets'; me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/buffer'); DatasetBufferAnalystParameters.toObject(parameter, parameterObject); } else if (parameter instanceof GeometryBufferAnalystParameters) { me.mode = 'geometry'; me.url = Util.urlPathAppend(me.url, 'geometry/buffer'); GeometryBufferAnalystParameters.toObject(parameter, parameterObject); } var jsonParameters = Util.toJSON(parameterObject); this.returnContent = true; me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } dataFormat() { return [DataFormat.GEOJSON, DataFormat.ISERVER, DataFormat.FGB]; } } ;// CONCATENATED MODULE: ./src/common/iServer/DatasourceConnectionInfo.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ // eslint-disable-line no-unused-vars /** * @class DatasourceConnectionInfo * @deprecatedclass SuperMap.DatasourceConnectionInfo * @category iServer Data Datasource * @classdesc 数据源连接信息类。该类包括了进行数据源连接的所有信息,如所要连接的服务器名称、数据库名称、用户名以及密码等。 * 当保存为工作空间时,工作空间中的数据源的连接信息都将存储到工作空间文件中。对于不同类型的数据源,其连接信息有所区别。 * 所以在使用该类所包含的成员时,请注意该成员所适用的数据源类型。对于从数据源对象中返回的数据连接信息对象,只有 connect 方法可以被修改, * 其他内容是不可以被修改的。对于用户创建的数据源连接信息对象,其内容都可以修改。 * @param {Object} options - 参数。 * @param {string} options.alias - 数据源别名。 * @param {string} options.dataBase - 数据源连接的数据库名。 * @param {boolean} [options.connect] - 数据源是否自动连接数据。 * @param {string} [options.driver] - 使用 ODBC(Open Database Connectivity,开放数据库互连)的数据库的驱动程序名。 * @param {EngineType} [options.engineType] - 数据源连接的引擎类型。 * @param {boolean} [options.exclusive] - 是否以独占方式打开数据源。 * @param {boolean} [options.OpenLinkTable] - 是否把数据库中的其他非 SuperMap 数据表作为 LinkTable 打开。 * @param {string} [options.password] - 登录数据源连接的数据库或文件的密码。 * @param {boolean} [options.readOnly] - 是否以只读方式打开数据源。 * @param {string} [options.server] - 数据库服务器名或 SDB 文件名。 * @param {string} [options.user] - 登录数据库的用户名。 * @usage */ class DatasourceConnectionInfo { constructor(options) { /** * @member {string} DatasourceConnectionInfo.prototype.alias * @description 数据源别名。 */ this.alias = null; /** * @member {boolean} [DatasourceConnectionInfo.prototype.connect] * @description 数据源是否自动连接数据。 */ this.connect = null; /** * @member {string} DatasourceConnectionInfo.prototype.dataBase * @description 数据源连接的数据库名。 */ this.dataBase = null; /** * @member {string} [DatasourceConnectionInfo.prototype.driver] * @description 使用 ODBC(Open Database Connectivity,开放数据库互连) 的数据库的驱动程序名。 * 其中,对于 SQL Server 数据库与 iServer 发布的 WMTS 服务,此为必设参数。 * 对于 SQL Server 数据库,它使用 ODBC 连接,所设置的驱动程序名为 "SQL Server" 或 "SQL Native Client"; * 对于 iServer 发布的 WMTS 服务,设置的驱动名称为 "WMTS"。 */ this.driver = null; /** * @member {EngineType} [DatasourceConnectionInfo.prototype.engineType] * @description 数据源连接的引擎类型。 */ this.engineType = null; /** * @member {boolean} [DatasourceConnectionInfo.prototype.exclusive] * @description 是否以独占方式打开数据源。 */ this.exclusive = null; /** * @member {boolean} [DatasourceConnectionInfo.prototype.OpenLinkTable] * @description 是否把数据库中的其他非 SuperMap 数据表作为 LinkTable 打开。 */ this.OpenLinkTable = null; /** * @member {string} [DatasourceConnectionInfo.prototype.password] * @description 登录数据源连接的数据库或文件的密码。 */ this.password = null; /** * @member {boolean} [DatasourceConnectionInfo.prototype.readOnly] * @description 是否以只读方式打开数据源。 */ this.readOnly = null; /** * @member {string} [DatasourceConnectionInfo.prototype.server] * @description 数据库服务器名、文件名或服务地址。 * 1.对于 SDB 和 UDB 文件,为其文件的绝对路径。注意:当绝对路径的长度超过 UTF-8 编码格式的 260 字节长度,该数据源无法打开。 * 2.对于 Oracle 数据库,其服务器名为其 TNS 服务名称。 * 3.对于 SQL Server 数据库,其服务器名为其系统的 DSN(Database Source Name) 名称。 * 4.对于 PostgreSQL 数据库,其服务器名为 “IP:端口号”,默认的端口号是 5432。 * 5.对于 DB2 数据库,已经进行了编目,所以不需要进行服务器的设置。 * 6.对于 Kingbase 数据库,其服务器名为其 IP 地址。 * 7.对于 GoogleMaps 数据源,其服务器地址,默认设置为 “{@link http://maps.google.com}”,且不可更改。 * 8.对于 SuperMapCould 数据源,为其服务地址。 * 9.对于 MAPWORLD 数据源,为其服务地址,默认设置为 “{@link http://www.tianditu.cn}”,且不可更改。 * 10.对于 OGC 和 REST 数据源,为其服务地址。 */ this.server = null; /** * @member {string} DatasourceConnectionInfo.prototype.user * @description 登录数据库的用户名。 */ this.user = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.DatasourceConnectionInfo"; } /** * @function DatasourceConnectionInfo.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.alias = null; me.connect = null; me.dataBase = null; me.driver = null; me.engineType = null; me.exclusive = null; me.OpenLinkTable = null; me.password = null; me.readOnly = null; me.server = null; me.user = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/OutputSetting.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OutputSetting * @deprecatedclass SuperMap.OutputSetting * @category iServer ProcessingService * @classdesc 分布式分析输出类型设置类。 * @param {Object} options - 参数。 * @param {DatasourceConnectionInfo} options.datasourceInfo - 数据源连接信息。 * @param {string} [options.datasetName='analystResult'] - 结果数据集名称。 * @param {OutputType} [options.type=OutputType.UDB] - 输出类型。 * @param {string} [options.outputPath] - 分析结果输出路径。 * @usage */ class OutputSetting { constructor(options) { /** * @member {OutputType} OutputSetting.prototype.type * @description 分布式分析的输出类型。 */ this.type = OutputType.UDB; /** * @member {string} [OutputSetting.prototype.datasetName='analystResult'] * @description 分布式分析的输出结果数据集名称。 */ this.datasetName = "analystResult"; /** * @member {DatasourceConnectionInfo} OutputSetting.prototype.datasourceInfo * @description 分布式分析的输出结果数据源连接信息。 */ this.datasourceInfo = null; /** * @member {string} [OutputSetting.prototype.outputPath] * @description 分布式分析的分析结果输出路径。 */ this.outputPath = ""; Util.extend(this, options); this.CLASS_NAME = "SuperMap.OutputSetting"; } /** * @function OutputSetting.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.type = null; me.datasetName = null; me.outputPath = null; if (me.datasourceInfo instanceof DatasourceConnectionInfo) { me.datasourceInfo.destroy(); me.datasourceInfo = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/MappingParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MappingParameters * @deprecatedclass SuperMap.MappingParameters * @category iServer ProcessingService * @classdesc 分析后结果可视化的参数类。 * @param {Object} options - 参数。 * @param {Array.} [options.items] - 栅格分段专题图子项数组。 * @param {number} [options.numericPrecision=1] - 精度,此字段用于设置分析结果标签专题图中标签数值的精度,如“1”表示精确到小数点的后一位。 * @param {RangeMode} [options.rangeMode=RangeMode.EQUALINTERVAL] - 专题图分段模式。 * @param {number} [options.rangeCount] - 专题图分段个数。 * @param {ColorGradientType} [options.colorGradientType=ColorGradientType.YELLOW_RED] - 专题图颜色渐变模式。 * @usage */ class MappingParameters { constructor(options) { /** * @member {Array.} [MappingParameters.prototype.items] * @description 栅格分段专题图子项数组。 */ this.items = null; /** * @member {number} [MappingParameters.prototype.numericPrecision=1] * @description 精度,此字段用于设置分析结果标签专题图中标签数值的精度,如“1”表示精确到小数点的后一位。 */ this.numericPrecision = 1; /** * @member {RangeMode} [MappingParameters.prototype.RangeMode=RangeMode.EQUALINTERVAL] * @description 专题图分段模式。 */ this.rangeMode = RangeMode.EQUALINTERVAL; /** * @member {number} [MappingParameters.prototype.rangeCount] * @description 专题图分段个数。 */ this.rangeCount = ""; /** * @member {ColorGradientType} [MappingParameters.prototype.colorGradientType=ColorGradientType.YELLOW_RED] * @description 专题图颜色渐变模式。 */ this.colorGradientType = ColorGradientType.YELLOW_RED; Util.extend(this, options); this.CLASS_NAME = "SuperMap.MappingParameters"; } /** * @function MappingParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.items) { if (me.items.length > 0) { for (var item in me.items) { me.items[item].destroy(); me.items[item] = null; } } me.items = null; } me.numericPrecision = null; me.rangeMode = null; me.rangeCount = null; me.colorGradientType = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/BuffersAnalystJobsParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BuffersAnalystJobsParameter * @deprecatedclass SuperMap.BuffersAnalystJobsParameter * @category iServer ProcessingService BufferAnalyst * @classdesc 缓冲区分析任务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} [options.bounds] - 分析范围(默认为全图范围)。 * @param {string} [options.distance='15'] - 缓冲距离,或缓冲区半径。 * @param {string} [options.distanceField='pickup_latitude'] - 缓冲区分析距离字段。 * @param {AnalystSizeUnit} [options.distanceUnit=AnalystSizeUnit.METER] - 缓冲距离单位单位。 * @param {OutputSetting} [options.output] - 输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class BuffersAnalystJobsParameter { constructor(options) { /** * @member {string} BuffersAnalystJobsParameter.prototype.datasetName * @description 数据集名。 */ this.datasetName = ''; /** * @member {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} BuffersAnalystJobsParameter.prototype.bounds * @description 分析范围。 */ this.bounds = ''; /** * @member {string} [BuffersAnalystJobsParameter.prototype.distance='15'] * @description 缓冲距离,或称为缓冲区半径。当缓冲距离字段为空时,此参数有效。 */ this.distance = ''; /** * @member {string} [BuffersAnalystJobsParameter.prototype.distanceField='pickup_latitude'] * @description 缓冲距离字段。 */ this.distanceField = ''; /** * @member {AnalystSizeUnit} [BuffersAnalystJobsParameter.prototype.distanceUnit=AnalystSizeUnit.METER] * @description 缓冲距离单位。 */ this.distanceUnit = AnalystSizeUnit.METER; /** * @member {string} BuffersAnalystJobsParameter.prototype.dissolveField * @description 融合字段,根据字段值对缓冲区结果面对象进行融合。 */ this.dissolveField = ''; /** * @member {OutputSetting} [BuffersAnalystJobsParameter.prototype.output] * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [BuffersAnalystJobsParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; if (!options) { return this; } Util.extend(this, options); this.CLASS_NAME = 'SuperMap.BuffersAnalystJobsParameter'; } /** * @function BuffersAnalystJobsParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.datasetName = null; this.bounds = null; this.distance = null; this.distanceField = null; this.distanceUnit = null; this.dissolveField = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters) { this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function BuffersAnalystJobsParameter.toObject * @param {BuffersAnalystJobsParameter} BuffersAnalystJobsParameter - 缓冲区分析任务参数。 * @param {Object} tempObj - 目标对象。 * @description 生成缓冲区分析任务对象。 */ static toObject(BuffersAnalystJobsParameter, tempObj) { for (var name in BuffersAnalystJobsParameter) { if (name === 'datasetName') { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = BuffersAnalystJobsParameter[name]; continue; } if (name === 'output') { tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = BuffersAnalystJobsParameter[name]; continue; } tempObj['analyst'] = tempObj['analyst'] || {}; if (name === 'bounds' && BuffersAnalystJobsParameter[name]) { tempObj['analyst'][name] = BuffersAnalystJobsParameter[name].toBBOX(); } else { tempObj['analyst'][name] = BuffersAnalystJobsParameter[name]; } if (name === 'mappingParameters') { tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = BuffersAnalystJobsParameter[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/ProcessingServiceBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ProcessingServiceBase * @deprecatedclass SuperMap.ProcessingServiceBase * @category iServer Core * @classdesc 分布式分析服务基类 * @extends {CommonServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {Events} options.events - 处理所有事件的对象。 * @param {number} options.index - 服务访问地址在数组中的位置。 * @param {number} options.length - 服务访问地址数组长度。 * @param {Object} [options.eventListeners] - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ProcessingServiceBase extends CommonServiceBase { constructor(url, options) { options = options || {}; /* * Constant: EVENT_TYPES * {Array.} * 此类支持的事件类型 * - *processCompleted* 创建成功后触发的事件。 * - *processFailed* 创建失败后触发的事件 。 * - *processRunning* 创建过程的整个阶段都会触发的事件,用于获取创建过程的状态 。 */ options.EVENT_TYPES = ["processCompleted", "processFailed", "processRunning"]; super(url, options); this.CLASS_NAME = "SuperMap.ProcessingServiceBase"; } /** * @function ProcessingServiceBase.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function ProcessingServiceBase.prototype.getJobs * @description 获取分布式分析任务。 * @param {string} url - 资源地址。 */ getJobs(url) { var me = this; FetchRequest.get(SecurityManager.appendCredential(url), null, { proxy: me.proxy }).then(function (response) { return response.json(); }).then(function (result) { me.events.triggerEvent("processCompleted", { result: result }); }).catch(function (e) { me.eventListeners.processFailed({ error: e }); }); } /** * @function ProcessingServiceBase.prototype.addJob * @description 添加分布式分析任务。 * @param {string} url - 资源根地址。 * @param {Object} params - 创建一个空间分析的请求参数。 * @param {string} paramType - 请求参数类型。 * @param {number} seconds - 开始创建后,获取创建成功结果的时间间隔。 */ addJob(url, params, paramType, seconds) { var me = this, parameterObject = null; if (params && params instanceof paramType) { parameterObject = new Object(); paramType.toObject(params, parameterObject); } let headers = Object.assign({ 'Content-Type': 'application/x-www-form-urlencoded' }, me.headers || {}) var options = { proxy: me.proxy, headers, withCredentials: me.withCredentials, crossOrigin: me.crossOrigin, isInTheSameDomain: me.isInTheSameDomain }; FetchRequest.post(SecurityManager.appendCredential(url), JSON.stringify(parameterObject), options).then(function (response) { return response.json(); }).then(function (result) { if (result.succeed) { me.serviceProcessCompleted(result, seconds); } else { me.serviceProcessFailed(result); } }).catch(function (e) { me.serviceProcessFailed({ error: e }); }); } serviceProcessCompleted(result, seconds) { result = Util.transformResult(result); seconds = seconds || 1000; var me = this; if (result) { var id = setInterval(function () { FetchRequest.get(SecurityManager.appendCredential(result.newResourceLocation), { _t: new Date().getTime() }) .then(function (response) { return response.json(); }).then(function (job) { me.events.triggerEvent("processRunning", { id: job.id, state: job.state }); if (job.state.runState === 'LOST' || job.state.runState === 'KILLED' || job.state.runState === 'FAILED') { clearInterval(id); me.events.triggerEvent("processFailed", { error: job.state.errorMsg, state: job.state.runState }); } if (job.state.runState === 'FINISHED' && job.setting.serviceInfo) { clearInterval(id); me.events.triggerEvent("processCompleted", { result: job }); } }).catch(function (e) { clearInterval(id); me.events.triggerEvent("processFailed", { error: e }); }); }, seconds); } } serviceProcessFailed(result) { super.serviceProcessFailed(result); } } ;// CONCATENATED MODULE: ./src/common/iServer/BuffersAnalystJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BuffersAnalystJobsService * @deprecatedclass SuperMap.BuffersAnalystJobsService * @category iServer ProcessingService BufferAnalyst * @classdesc 缓冲区分析服务类 * @extends {ProcessingServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class BuffersAnalystJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/buffers'); this.CLASS_NAME = 'SuperMap.BuffersAnalystJobsService'; } /** *@override */ destroy() { super.destroy(); } /** * @function BuffersAnalystJobsService.prototype.getBufferJobs * @description 获取缓冲区分析所有任务 */ getBuffersJobs() { super.getJobs(this.url); } /** * @function BuffersAnalystJobsService.prototype.getBufferJob * @description 获取指定id的缓冲区分析服务 * @param {string} id - 指定要获取数据的id。 */ getBuffersJob(id) { super.getJobs(Util.urlPathAppend(this.url, id)); } /** * @function BuffersAnalystJobsService.prototype.addBufferJob * @description 新建缓冲区分析服务 * @param {BuffersAnalystJobsParameter} params - 创建一个空间分析的请求参数。 * @param {number} seconds - 开始创建后,获取创建成功结果的时间间隔。 */ addBuffersJob(params, seconds) { super.addJob(this.url, params, BuffersAnalystJobsParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/BurstPipelineAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BurstPipelineAnalystParameters * @deprecatedclass SuperMap.BurstPipelineAnalystParameters * @category iServer NetworkAnalyst BurstAnalyse * @classdesc 爆管分析参数类。 * @param {Object} options - 参数。 * @param {Array.} options.sourceNodeIDs - 指定的设施点 ID 数组。 * @param {number} [options.edgeID] - 指定的弧段ID,edgeID 与 nodeID 必须指定一个。 * @param {number} [options.nodeID] - 指定的结点ID,edgeID 与 nodeID 必须指定一个。 * @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。 * @usage */ class BurstPipelineAnalystParameters { constructor(options) { var me = this; /** * @member {Array.} BurstPipelineAnalystParameters.prototype.sourceNodeIDs * @description 指定的设施点 ID 数组。 */ this.sourceNodeIDs = null; /** * @member {number} [BurstPipelineAnalystParameters.prototype.edgeID] * @description 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。 */ this.edgeID = null; /** * @member {number} [BurstPipelineAnalystParameters.prototype.nodeID] * @description 指定的结点 ID,edgeID 与 nodeID 必须指定一个。 */ this.nodeID = null; /** * @member {boolean} [BurstPipelineAnalystParameters.prototype.isUncertainDirectionValid=false] * @description 指定不确定流向是否有效。 * 指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行。 * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 */ this.isUncertainDirectionValid = false; Util.extend(me, options); this.CLASS_NAME = "SuperMap.BurstPipelineAnalystParameters"; } /** * @function BurstPipelineAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.sourceNodeIDs = null; me.edgeID = null; me.nodeID = null; me.isUncertainDirectionValid = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/NetworkAnalystServiceBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class NetworkAnalystServiceBase * @deprecatedclass SuperMap.NetworkAnalystServiceBase * @category iServer Core * @classdesc 网络分析服务基类。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class NetworkAnalystServiceBase extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {DataFormat} [NetworkAnalystServiceBase.prototype.format=DataFormat.GEOJSON] * @description 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式,参数格式为 "ISERVER","GEOJSON" */ this.format = DataFormat.GEOJSON; this.CLASS_NAME = "SuperMap.NetworkAnalystServiceBase"; } /** * @function NetworkAnalystServiceBase.prototype.destroy * @description 释放资源,将引用的资源属性置空。 */ destroy() { super.destroy(); this.format = null; } /** * @function NetworkAnalystServiceBase.prototype.serviceProcessCompleted * @description 分析完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ serviceProcessCompleted(result) { var me = this, analystResult; result = Util.transformResult(result); if (result && me.format === DataFormat.GEOJSON && typeof me.toGeoJSONResult === 'function') { analystResult = me.toGeoJSONResult(result); } if (!analystResult) { analystResult = result; } me.events.triggerEvent("processCompleted", {result: analystResult}); } /** * @function NetworkAnalystServiceBase.prototype.toGeoJSONResult * @description 将含有 geometry 的数据转换为 GeoJSON 格式。只处理结果中的路由,由子类实现。 * @param {Object} result - 服务器返回的结果对象。 * @returns {GeoJSONObject} GeoJSON 对象。 */ toGeoJSONResult(result) { // eslint-disable-line no-unused-vars return null; } } ;// CONCATENATED MODULE: ./src/common/iServer/BurstPipelineAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BurstPipelineAnalystService * @deprecatedclass SuperMap.BurstPipelineAnalystService * @category iServer NetworkAnalyst BurstAnalyse * @classdesc 爆管分析服务类,即将给定弧段或节点作为爆管点来进行分析,返回关键结点 ID 数组、普通结点 ID 数组及其上下游弧段 ID 数组。 * @extends {NetworkAnalystServiceBase} * @param {string} url - 网络分析服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}, * 例如: "http://localhost:8090/iserver/services/test/rest/networkanalyst/WaterNet@FacilityNet"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class BurstPipelineAnalystService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.BurstPipelineAnalystService"; } /** * @function BurstPipelineAnalystService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function BurstPipelineAnalystService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @params {BurstPipelineAnalystParameters} params - 爆管分析参数类 */ processAsync(params) { if (!(params instanceof BurstPipelineAnalystParameters)) { return null; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'burstAnalyse'); jsonObject = { sourceNodeIDs: params.sourceNodeIDs, isUncertainDirectionValid: params.isUncertainDirectionValid }; //必传参数不正确,就终止 if (params.edgeID !== null && params.nodeID !== null) { throw new Error('edgeID and nodeID cannot be null at the same time.'); } if (params.edgeID === null && params.nodeID === null) { throw new Error('edgeID and nodeID cannot be null at the same time.'); } if (params.edgeID !== null) { jsonObject.edgeID = params.edgeID; } else { jsonObject.nodeID = params.nodeID; } me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/ChartFeatureInfoSpecsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChartFeatureInfoSpecsService * @deprecatedclass SuperMap.ChartFeatureInfoSpecsService * @category iServer Map Chart * @classdesc 海图物标信息服务类,通过该服务类可以查询到服务端支持的所有海图物标信息。 * 用户可以通过两种方式获取查询结果: * 一种是通过监听 ChartFeatureInfoSpecsEvent.PROCESS_COMPLETE 事件; * 另一种是使用 AsyncResponder 类实现异步处理。 * @extends {CommonServiceBase} * @param {string} url - 地图(特指海图)服务地址。 * 如:"http://localhost:8090/iserver/services/map-ChartW/rest/maps/海图"。 * 发送请求格式类似于:"http://localhost:8090/iserver/services/map-ChartW/rest/maps/海图/chartFeatureInfoSpecs.json"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式,参数格式为"ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ChartFeatureInfoSpecsService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.ChartFeatureInfoSpecsService"; } /** * @function ChartFeatureInfoSpecsService.prototype.destroy * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function ChartFeatureInfoSpecsService.prototype.processAsync * @description 根据地图(特指海图)服务地址与服务端完成异步通讯,获取物标信息。 * 当查询物标信息成功时,将触发 ChartFeatureInfoSpecsEvent.PROCESS_COMPLETE * 事件。用可以通过户两种方式获取图层信息: * 1. 通过 AsyncResponder 类获取(推荐使用); * 2. 通过监听 ChartFeatureInfoSpecsEvent.PROCESS_COMPLETE 事件获取。 */ processAsync() { var me = this, method = "GET"; if (!me.isTempLayers) { Util.urlPathAppend(me.url,'chartFeatureInfoSpecs'); } me.request({ method: method, params: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/ChartQueryFilterParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChartQueryFilterParameter * @deprecatedclass SuperMap.ChartQueryFilterParameter * @category iServer Map Chart * @classdesc 海图查询过滤参数类,用于设置海图查询的过滤参数。包括:物标代码、物标可应用对象的选择(是否查询点、线或面)、属性字段过滤条件。 * @param {Object} options - 参数。 * @param {string} options.attributeFilter - 属性字段过滤条件。 * @param {number} options.chartFeatureInfoSpecCode - 查询的物标代号。 * @param {boolean} [options.isQueryPoint] - 是否查询点。 * @param {boolean} [options.isQueryLine] - 是否查询线。 * @param {boolean} [options.isQueryRegion] - 是否查询面。 * @usage */ class ChartQueryFilterParameter { constructor(options) { /** * @member {boolean} [ChartQueryFilterParameter.prototype.isQueryPoint] * @description 是否查询点。 */ this.isQueryPoint = null; /** * @member {boolean} [ChartQueryFilterParameter.prototype.isQueryLine] * @description 是否查询线。 */ this.isQueryLine = null; /** * @member {boolean} [ChartQueryFilterParameter.prototype.isQueryRegion] * @description 是否查询面。 */ this.isQueryRegion = null; /** * @member {string} ChartQueryFilterParameter.prototype.attributeFilter * @description 属性字段过滤条件。 */ this.attributeFilter = null; /** * @member {number} ChartQueryFilterParameter.prototype.chartFeatureInfoSpecCode * @description 查询的物标代号。 */ this.chartFeatureInfoSpecCode = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.ChartQueryFilterParameter"; } /** * @function ChartQueryFilterParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.isQueryPoint = null; me.isQueryLine = null; me.isQueryRegion = null; me.attributeFilter = null; me.chartFeatureInfoSpecCode = null; } /** * @function ChartQueryFilterParameter.prototype.toJson * @description 将属性信息转化成 JSON 格式字符串。 */ toJson() { var json = ""; json += "\"isQueryPoint\":" + this.isQueryPoint + ","; json += "\"isQueryLine\":" + this.isQueryLine + ","; json += "\"isQueryRegion\":" + this.isQueryRegion + ","; if (this.attributeFilter) { json += "\"attributeFilter\": \"" + this.attributeFilter + "\","; } json += "\"chartFeatureInfoSpecCode\":" + this.chartFeatureInfoSpecCode; json = "{" + json + "}"; return json; } } ;// CONCATENATED MODULE: ./src/common/iServer/ChartQueryParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChartQueryParameters * @deprecatedclass SuperMap.ChartQueryParameters * @category iServer Map Chart * @classdesc 海图查询参数类,该类用于设置海图查询时的相关参数,海图查询分为海图属性查询和海图范围查询两类,通过属性 queryMode 指定查询模式。 * 必设属性有:queryMode、chartLayerNames、chartQueryFilterParameters。当进行海图范围查询时,必设属性还包括 bounds。 * @param {Object} options - 参数。 * @param {string} options.queryMode - 海图查询模式类型,支持两种查询方式:海图属性查询("ChartAttributeQuery")和海图空间查询("ChartBoundsQuery")。 * @param {Array.} options.chartLayerNames - 查询的海图图层的名称。 * @param {Array.} options.chartQueryFilterParameters - 海图查询过滤参数。包括:物标代码、物标可应用对象的选择(是否查询点、线或面)、属性字段过滤条件。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} options.bounds - 海图查询范围。当进行海图范围查询时,此为必选参数。 * @param {boolean} [options.returnContent=true] - 获取或设置是返回查询结果记录集 recordsets,还是返回查询结果的资源 resourceInfo。 * @param {number} [options.startRecord=0] - 查询起始记录位置。 * @param {number} [options.expectCount] - 期望查询结果返回的记录数,该值大于0。 * @usage */ class ChartQueryParameters { constructor(options) { /** * @member {string} ChartQueryParameters.prototype.queryMode * @description 海图查询模式类型,支持两种查询方式:海图属性查询("ChartAttributeQuery")和海图空间查询("ChartBoundsQuery")。 */ this.queryMode = null; /** * @member {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} ChartQueryParameters.prototype.bounds * @description 海图查询范围。 */ this.bounds = null; /** * @member {Array.} ChartQueryParameters.prototype.chartLayerNames * @description 查询的海图图层的名称。 */ this.chartLayerNames = null; /** * @member {Array.} ChartQueryParameters.prototype.chartQueryFilterParameters * @description 海图查询过滤参数。包括:物标代码、物标可应用对象的选择(是否查询点、线或面)、属性字段过滤条件。 */ this.chartQueryFilterParameters = null; /** * @member {boolean} [ChartQueryParameters.prototype.returnContent=true] * @description 获取或设置是返回查询结果记录集 recordsets,还是返回查询结果的资源 resourceInfo。 */ this.returnContent = true; /** * @member {number} [ChartQueryParameters.prototype.startRecord=0] * @description 查询起始记录位置。 */ this.startRecord = 0; /** * @member {number} [ChartQueryParameters.prototype.expectCount] * @description 期望查询结果返回的记录数,该值大于0。 */ this.expectCount = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.ChartQueryParameters"; } /** * @function ChartQueryParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.queryMode = null; me.bounds = null; me.chartLayerNames = null; me.chartQueryFilterParameters = null; me.returnContent = true; me.startRecord = 0; me.expectCount = null; } /** * @function ChartQueryParameters.prototype.getVariablesJson * @description 将属性信息转换成能够被服务识别的 JSON 格式字符串。 * @returns {string} JSON 字符串。 */ getVariablesJson() { var json = ""; json += "\"queryMode\":\"" + this.queryMode + "\","; if (this.chartLayerNames && this.chartLayerNames.length) { var chartLayersArray = []; var layerLength = this.chartLayerNames.length; for (var i = 0; i < layerLength; i++) { chartLayersArray.push("\"" + this.chartLayerNames[i] + "\""); } var layerNames = "[" + chartLayersArray.join(",") + "]"; json += "\"chartLayerNames\":" + layerNames + ","; } if (this.queryMode === "ChartBoundsQuery" && this.bounds) { json += "\"bounds\":" + "{" + "\"leftBottom\":" + "{" + "\"x\":" + this.bounds.left + "," + "\"y\":" + this.bounds.bottom + "}" + "," + "\"rightTop\":" + "{" + "\"x\":" + this.bounds.right + "," + "\"y\":" + this.bounds.top + "}" + "},"; } if (this.chartQueryFilterParameters && this.chartQueryFilterParameters.length) { var chartParamArray = []; var chartLength = this.chartQueryFilterParameters.length; for (var j = 0; j < chartLength; j++) { var chartQueryFilterParameter = this.chartQueryFilterParameters[j]; if (!(chartQueryFilterParameter instanceof ChartQueryFilterParameter)) { continue; } chartParamArray.push(chartQueryFilterParameter.toJson()); } var chartParamsJson = "[" + chartParamArray.join(",") + "]"; chartParamsJson = "\"chartQueryParams\":" + chartParamsJson + ","; chartParamsJson += "\"startRecord\":" + this.startRecord + ","; chartParamsJson += "\"expectCount\":" + this.expectCount; chartParamsJson = "{" + chartParamsJson + "}"; json += "\"chartQueryParameters\":" + chartParamsJson; } json = "{" + json + "}"; return json; } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryParameters * @deprecatedclass SuperMap.QueryParameters * @category iServer Map QueryResults * @classdesc 查询参数基类。距离查询、SQL 查询、几何地物查询等各自的参数均继承此类。 * @param {Object} options - 参数。 * @param {Array.} options.queryParams - 查询过滤条件参数数组。 * @param {string} [options.customParams] - 自定义参数,供扩展使用。 * @param {Object} [options.prjCoordSys] - 自定义参数,供 SuperMap Online 提供的动态投影查询扩展使用。如 {"epsgCode":3857}。 * @param {number} [options.expectCount=100000] - 期望返回结果记录个数。 * @param {GeometryType} [options.networkType=GeometryType.LINE] - 网络数据集对应的查询类型。 * @param {QueryOption} [options.queryOption=QueryOption.ATTRIBUTEANDGEOMETRY] - 查询结果类型枚举类。 * @param {number} [options.startRecord=0] - 查询起始记录号。 * @param {number} [options.holdTime=10] - 资源在服务端保存的时间,单位为分钟。 * @param {boolean} [options.returnCustomResult=false] - 仅供三维使用。 * @param {boolean} [options.returnFeatureWithFieldCaption = false] - 返回的查询结果要素字段标识是否为字段别名。为 false 时,返回的是字段名;为 true 时,返回的是字段别名。 * @usage */ class QueryParameters { constructor(options) { if (!options) { return; } /** * @member {string} [QueryParameters.prototype.customParams] * @description 自定义参数,供扩展使用。 */ this.customParams = null; /** * @member {Object} [QueryParameters.prototype.prjCoordSys] * @description 自定义参数,供 SuperMap Online 提供的动态投影查询扩展使用。如 {"epsgCode":3857} */ this.prjCoordSys = null; /** * @member {number} [QueryParameters.prototype.expectCount=100000] * @description 期望返回结果记录个数,默认返回100000条查询记录, * 如果实际不足100000条则返回实际记录条数。 */ this.expectCount = 100000; /** * @member {GeometryType} [QueryParameters.prototype.networkType=GeometryType.LINE] * @description 网络数据集对应的查询类型,分为点和线两种类型。 */ this.networkType = REST_GeometryType.LINE; /** * @member {QueryOption} [QueryParameters.prototype.queryOption=QueryOption.ATTRIBUTEANDGEOMETRY] * @description 查询结果类型枚举类。 * 该类描述查询结果返回类型,包括只返回属性、 * 只返回几何实体以及返回属性和几何实体。 */ this.queryOption = QueryOption.ATTRIBUTEANDGEOMETRY; /** * @member {Array.} QueryParameters.prototype.queryParams * @description 查询过滤条件参数数组。 * 该类用于设置查询数据集的查询过滤参数。 */ this.queryParams = null; /** * @member {number} [QueryParameters.prototype.startRecord=0] * @description 查询起始记录号。 */ this.startRecord = 0; /** * @member {number} [QueryParameters.prototype.holdTime=10] * @description 资源在服务端保存的时间,单位为分钟。 */ this.holdTime = 10; /** * @member {boolean} [QueryParameters.prototype.returnCustomResult=false] * @description 仅供三维使用。 */ this.returnCustomResult = false; /** * @member {boolean} [QueryParameters.prototype.returnFeatureWithFieldCaption=false] * @description 返回的查询结果要素字段标识是否为字段别名。为 false 时,返回的是字段名;为 true 时,返回的是字段别名。 */ this.returnFeatureWithFieldCaption = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.QueryParameters"; } /** * @function QueryParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.customParams = null; me.expectCount = null; me.networkType = null; me.queryOption = null; if (me.queryParams) { for (var i = 0, qps = me.queryParams, len = qps.length; i < len; i++) { qps[i].destroy(); } me.queryParams = null; } me.startRecord = null; me.holdTime = null; me.returnCustomResult = null; me.prjCoordSys = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/ChartQueryService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChartQueryService * @deprecatedclass SuperMap.ChartQueryService * @category iServer Map Chart * @classdesc 海图查询服务类。该类负责将海图查询所需参数(ChartQueryParameters)传递至服务端,并获取服务端的返回结果。 * 用户可以通过两种方式获取查询结果: * 1.通过 AsyncResponder 类获取(推荐使用); * 2.通过监听 QueryEvent.PROCESS_COMPLETE 事件获取。 * @extends {CommonServiceBase} * @param {string} url - 地图查询服务访问地址。如:"http://localhost:8090/iserver/services/map-ChartW/rest/maps/海图"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为"ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * 下面示例显示了如何进行海图属性查询: * var nameArray = ["GB4X0000_52000"]; * var chartQueryFilterParameter = new ChartQueryFilterParameter({ * isQueryPoint:true, * isQueryLine:true, * isQueryRegion:true, * attributeFilter:"SmID<10", * chartFeatureInfoSpecCode:1 * }); * * var chartQueryParameters = new ChartQueryParameters({ * queryMode:"ChartAttributeQuery", * chartLayerNames:nameArray, * returnContent:true, * chartQueryFilterParameters:[chartQueryFilterParameter] * }); * * var chartQueryService = new ChartQueryService(url); * * chartQueryService.events.on({ * "processCompleted":processCompleted, * "processFailed":processFailed * }); * chartQueryService.processAsync(chartQueryParameters); * @usage */ class ChartQueryService extends CommonServiceBase { constructor(url, options) { super(url, options); options = options || {}; /** * @member {boolean} ChartQueryService.prototype.returnContent * @description 是否立即返回新创建资源的表述还是返回新资源的URI。 */ this.returnContent = null; /** * @member {DataFormat} ChartQueryService.prototype.format * @description 查询结果返回格式,目前支持iServerJSON 和GeoJSON两种格式 * 参数格式为"ISERVER","GEOJSON",GEOJSON */ this.format = DataFormat.GEOJSON; Util.extend(this, options); var me = this; if (options.format) { me.format = options.format.toUpperCase(); } if (!me.url) { return; } me.url = Util.urlPathAppend(me.url, 'queryResults'); this.CLASS_NAME = "SuperMap.ChartQueryService"; } /** * @function ChartQueryService.prototype.destroy * @override */ destroy() { var me = this; CommonServiceBase.prototype.destroy.apply(this, arguments); me.returnContent = null; me.format = null; } /** * @function ChartQueryService.prototype.processAsync * @description 使用服务地址 URL 实例化 ChartQueryService 对象。 * @param {ChartQueryParameters} params - 查询参数。 */ processAsync(params) { //todo重点需要添加代码的地方 if (!(params instanceof ChartQueryParameters)) { return; } var me = this, jsonParameters; me.returnContent = params.returnContent; jsonParameters = params.getVariablesJson(); if (me.returnContent) { me.url = Util.urlAppend(me.url, 'returnContent=true'); } me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ChartQueryService.prototype.serviceProcessCompleted * @description 查询完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ serviceProcessCompleted(result) { var me = this; result = Util.transformResult(result); if (result && result.recordsets && me.format === DataFormat.GEOJSON) { for (var i = 0, recordsets = result.recordsets, len = recordsets.length; i < len; i++) { if (recordsets[i].features) { var geoJSONFormat = new GeoJSON(); recordsets[i].features = geoJSONFormat.toGeoJSON(recordsets[i].features); } } } me.events.triggerEvent("processCompleted", {result: result}); } /** * @function ChartQueryService.prototype.getQueryParameters * @description 将 JSON 对象表示的查询参数转化为 QueryParameters 对象。 * @param {Object} params - JSON 字符串表示的查询参数。 * @returns {QueryParameters} 返回查询结果 */ getQueryParameters(params) { return new QueryParameters({ queryMode: params.queryMode, bounds: params.bounds, chartLayerNames: params.chartLayerNames, chartQueryFilterParameters: params.chartQueryFilterParameters, returnContent: params.returnContent }); } } ;// CONCATENATED MODULE: ./src/common/iServer/ClipParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ClipParameter * @deprecatedclass SuperMap.ClipParameter * @category iServer SpatialAnalyst InterpolationAnalyst * @classdesc 用于裁剪的参数。优先使用用户指定的裁剪区域多边形进行裁剪,也可以通过指定数据源和数据集名,从而使用指定数据集的边界多边形进行裁剪。 * @param {Object} options - 可选参数。 * @param {string} [options.clipDatasetName] - 裁剪的数据集名。 * @param {string} [options.clipDatasourceName] - 裁剪的数据集所在数据源的名字。 * @param {GeometryPolygon|L.Polygon|L.GeoJSON|ol.geom.Polygon|ol.format.GeoJSON|GeoJSONObject} [options.clipRegion] - 用户指定的裁剪区域。 * @param {boolean} [options.isClipInRegion=true] - 是否对裁剪区内的数据集进行裁剪。 * @param {boolean} [options.isExactClip=true] - 是否使用精确裁剪。 * @usage */ class ClipParameter { constructor(options) { /** * @member {string} ClipParameter.prototype.clipDatasetName * @description 用于裁剪的数据集名,clipDatasetName 与 clipRegion 必须设置一个。 */ this.clipDatasetName = null; /** * @member {string} ClipParameter.prototype.clipDatasourceName * @description 用于裁剪的数据集所在数据源的名字。当 clipRegion 不设置时起作用。 */ this.clipDatasourceName = null; /** * @member {GeometryPolygon|L.Polygon|L.GeoJSON|ol.geom.Polygon|ol.format.GeoJSON|GeoJSONObject} ClipParameter.prototype.clipRegion * @description 用户指定的裁剪区域,优先使用,clipDatasetName 与 clipRegion 必须设置一个。 */ this.clipRegion = null; /** * @member {boolean} [ClipParameter.prototype.isClipInRegion=true] * @description 是否对裁剪区内的数据集进行裁剪。若为 true,则对裁剪区域内的结果进行裁剪,若为 false,则对裁剪区域外的结果进行裁剪。 */ this.isClipInRegion = true; /** * @member {boolean} [ClipParameter.prototype.isExactClip=true] * @description 是否使用精确裁剪。 */ this.isExactClip = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ClipParameter"; } /** * @function ClipParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.clipDatasetName = null; me.clipDatasourceName = null; me.clipRegion = null; me.isClipInRegion = null; me.isExactClip = null; } /** * @function ClipParameter.prototype.toJSON * @description 将 ClipParameter 对象转化为 JSON 字符串。 * @returns {string} 返回转换后的 JSON 字符串。 */ toJSON() { return Util.toJSON({ isClipInRegion: this.isClipInRegion, clipDatasetName: this.clipDatasetName, clipDatasourceName: this.clipDatasourceName, isExactClip: this.isExactClip, clipRegion: ServerGeometry.fromGeometry(this.clipRegion) }); } } ;// CONCATENATED MODULE: ./src/common/iServer/ColorDictionary.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ColorDictionary * @deprecatedclass SuperMap.ColorDictionary * @category iServer Map Theme * @classdesc 颜色对照表类。颜色对照表中的键名为具体的高程值,键值表示该高程值要显示的颜色。 * 对于栅格图层中高程值小于颜色对照表中高程最小值的点使用颜色对照表中高程最小值对应的颜色, * 对于栅格图层中高程值大于颜色对照表中高程最大值的点使用颜色对照表中高程最大值对应的颜色, * 对于栅格图层中高程值在颜色对照表中没有对应颜色的点,则查找颜色对照表中与当前高程值相邻的两个高程对应的颜色, * 然后通过渐变运算要显示的颜色。如果设置了颜色对照表的话,则颜色表设置无效。 * @param {Object} options - 参数。 * @param {number} options.elevation - 高程值。 * @param {ServerColor} options.color - 服务端颜色类。 * @usage */ class ColorDictionary { constructor(options) { options = options || {}; /** * @member {number} ColorDictionary.prototype.elevation * @description 高程值。 */ this.elevation = null; /** * @member {ServerColor} ColorDictionary.prototype.color * @description 服务端颜色类。 */ this.color = null; Util.extend(this, options); var me = this, c = me.color; if (c) { me.color = new ServerColor(c.red, c.green, c.blue); } this.CLASS_NAME = "SuperMap.ColorDictionary"; } /** * @function ColorDictionary.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { Util.reset(this); } /** * @function ColorDictionary.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} JSON 对象。 */ toServerJSONObject() { var dataObj = {}; dataObj = Util.copyAttributes(dataObj, this); return dataObj; } } ;// CONCATENATED MODULE: ./src/common/iServer/TransportationAnalystResultSetting.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TransportationAnalystResultSetting * @deprecatedclass SuperMap.TransportationAnalystResultSetting * @category iServer NetworkAnalyst * @classdesc 交通网络分析结果参数类。通过该类设置交通网络分析返回的结果,包括是否返回图片、是否返回弧段空间信息、是否返回结点空间信息等。 * @param {Object} options - 可选参数。 * @param {boolean} [options.returnEdgeFeatures=false] - 是否在分析结果中包含弧段要素集合。 * @param {boolean} [options.returnEdgeGeometry=false] - 返回的弧段要素集合中是否包含几何对象信息。 * @param {boolean} [options.returnEdgeIDs=false] - 返回结果中是否包含经过弧段 ID 集合。 * @param {boolean} [options.returnNodeFeatures=false] - 是否在分析结果中包含结点要素集合。 * @param {boolean} [options.returnNodeGeometry=false] - 返回的结点要素集合中是否包含几何对象信息。 * @param {boolean} [options.returnNodeIDs=false] - 返回结果中是否包含经过结点 ID 集合。 * @param {boolean} [options.returnPathGuides=false] - 返回分析结果中是否包含行驶导引集合。 * @param {boolean} [options.returnRoutes=false] - 返回分析结果中是否包含路由对象的集合。 * @usage */ class TransportationAnalystResultSetting { constructor(options) { if (!options) { return; } /** * @member {boolean} TransportationAnalystResultSetting.prototype.returnEdgeFeatures * @description 是否在分析结果中包含弧段要素集合。弧段要素包括弧段的空间信息和属性信息。 */ this.returnEdgeFeatures = false; /** * @member {boolean} [TransportationAnalystResultSetting.prototype.returnEdgeGeometry=false] * @description 返回的弧段要素集合中是否包含几何对象信息。 */ this.returnEdgeGeometry = false; /** * @member {boolean} [TransportationAnalystResultSetting.prototype.returnEdgeIDs=false] * @description 返回结果中是否包含经过弧段 ID 集合。 */ this.returnEdgeIDs = false; /** * @member {boolean} [TransportationAnalystResultSetting.prototype.returnNodeFeatures=false] * @description 是否在分析结果中包含结点要素集合。 * 结点要素包括结点的空间信息和属性信息。其中返回的结点要素是否包含空间信息可通过 returnNodeGeometry 字段设置。 */ this.returnNodeFeatures = false; /** * @member {boolean} [TransportationAnalystResultSetting.prototype.returnNodeGeometry=false] * @description 返回的结点要素集合中是否包含几何对象信息。 */ this.returnNodeGeometry = false; /** * @member {boolean} [TransportationAnalystResultSetting.prototype.returnNodeIDs=false] * @description 返回结果中是否包含经过结点 ID 集合。 */ this.returnNodeIDs = false; /** * @member {boolean} TransportationAnalystResultSetting.prototype.returnPathGuides * @description 返回分析结果中是否包含行驶导引集合。 */ this.returnPathGuides = false; /** * @member {boolean} TransportationAnalystResultSetting.prototype.returnRoutes * @description 返回分析结果中是否包含路由对象的集合。 */ this.returnRoutes = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.TransportationAnalystResultSetting"; } /** * @function TransportationAnalystResultSetting.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.returnEdgeFeatures = null; me.returnEdgeGeometry = null; me.returnEdgeIDs = null; me.returnNodeFeatures = null; me.returnNodeGeometry = null; me.returnNodeIDs = null; me.returnPathGuides = null; me.returnRoutes = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/TransportationAnalystParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TransportationAnalystParameter * @deprecatedclass SuperMap.TransportationAnalystParameter * @category iServer NetworkAnalyst * @classdesc 交通网络分析通用参数类。该类主要用来提供交通网络分析所需的通用参数。 * 通过本类可以设置障碍边、障碍点、权值字段信息的名称标识、转向权值字段等信息,还可以对分析结果包含的内容进行一些设置。 * @param {Object} options - 参数。 * @param {Array.} options.barrierEdgeIDs - 网络分析中障碍弧段的 ID 数组。 * @param {Array.} options.barrierNodeIDs - 网络分析中障碍点的 ID 数组。 * @param {string} options.turnWeightField - 转向权重字段的名称。 * @param {TransportationAnalystResultSetting} options.resultSetting - 分析结果返回内容。 * @param {Array.>} [options.barrierPoints] - 网络分析中 Point2D 类型的障碍点数组。 * @param {string} [options.weightFieldName] - 阻力字段的名称。 * @usage */ class TransportationAnalystParameter { constructor(options) { if (!options) { return; } /** * @member {Array.} TransportationAnalystParameter.prototype.barrierEdgeIDs * @description 网络分析中障碍弧段的 ID 数组。弧段设置为障碍边之后,表示双向都不通。 */ this.barrierEdgeIDs = null; /** * @member {Array.} TransportationAnalystParameter.prototype.barrierNodeIDs * @description 网络分析中障碍点的 ID 数组。结点设置为障碍点之后,表示任何方向都不能通过此结点。 */ this.barrierNodeIDs = null; /** * @member {Array.>} TransportationAnalystParameter.prototype.barrierPoints * @description 网络分析中 Point2D 类型的障碍点数组。障碍点表示任何方向都不能通过此点。
* 当各网络分析参数类中的 isAnalyzeById 属性设置为 false 时,该属性才生效。 */ this.barrierPoints = null; /** * @member {string} [TransportationAnalystParameter.prototype.weightFieldName] * @description 阻力字段的名称,标识了进行网络分析时所使用的阻力字段,例如表示时间、长度等的字段都可以用作阻力字段。 * 该字段默值为服务器发布的所有耗费字段的第一个字段。 */ this.weightFieldName = null; /** * @member {string} TransportationAnalystParameter.prototype.turnWeightField * @description 转向权重字段的名称。 */ this.turnWeightField = null; /** * @member {TransportationAnalystResultSetting} TransportationAnalystParameter.prototype.resultSetting * @description 分析结果返回内容。 */ this.resultSetting = new TransportationAnalystResultSetting(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.TransportationAnalystParameter"; } /** * @function TransportationAnalystParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.barrierEdgeIDs = null; me.barrierNodeIDs = null; me.weightFieldName = null; me.turnWeightField = null; if (me.resultSetting) { me.resultSetting.destroy(); me.resultSetting = null; } if (me.barrierPoints && me.barrierPoints.length) { for (var i in me.barrierPoints) { me.barrierPoints[i].destroy(); } } me.barrierPoints = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/ComputeWeightMatrixParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ComputeWeightMatrixParameters * @deprecatedclass SuperMap.ComputeWeightMatrixParameters * @category iServer NetworkAnalyst WeightMatrix * @classdesc 耗费矩阵分析参数类。根据交通网络分析参数中的耗费字段返回一个耗费矩阵。该矩阵是一个二维数组,用来存储任意两点间的资源消耗。 * @param {Object} options - 参数。 * @param {boolean} [options.isAnalyzeById=false] - 是否通过节点 ID 指定路径分析的结点。 * @param {Array.>} options.nodes - 要计算耗费矩阵的点数组。 * @param {TransportationAnalystParameter} [options.parameter] - 交通网络分析通用参数。 * @usage */ class ComputeWeightMatrixParameters { constructor(options) { /** * @member {boolean} [ComputeWeightMatrixParameters.prototype.isAnalyzeById=false] * @description 是否通过节点 ID 指定路径分析的结点,即通过坐标点指定。 */ this.isAnalyzeById = false; /** * @member {Array.>} ComputeWeightMatrixParameters.prototype.nodes * @description 要计算耗费矩阵的点数组。 * 当 {@link ComputeWeightMatrixParameters.isAnalyzeById} = false 时,nodes 应为点的坐标数组; * 当 {@link ComputeWeightMatrixParameters.isAnalyzeById} = true 时,nodes 应为点的 ID 数组。 */ this.nodes = null; /** * @member {TransportationAnalystParameter} ComputeWeightMatrixParameters.prototype.parameter * @description 交通网络分析通用参数。 */ this.parameter = new TransportationAnalystParameter(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.ComputeWeightMatrixParameters"; } /** * @function ComputeWeightMatrixParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.isAnalyzeById = null; me.nodes = null; if (me.parameter) { me.parameter.destroy(); me.parameter = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/ComputeWeightMatrixService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ComputeWeightMatrixService * @deprecatedclass SuperMap.ComputeWeightMatrixService * @category iServer NetworkAnalyst WeightMatrix * @classdesc 耗费矩阵分析服务类。 * 耗费矩阵是根据交通网络分析参数中的耗费字段来计算一个二维数组, * 用来存储指定的任意两点间的资源消耗。 * 耗费矩阵分析结果通过该类支持的事件的监听函数参数获取 * @extends {NetworkAnalystServiceBase} * @example * var mycomputeWeightMatrixService = new ComputeWeightMatrixService(url,{ * eventListeners: { * "processCompleted": computeWeightMatrixCompleted, * "processFailed": computeWeightMatrixnError * } * }); * @param {string} url - 耗费矩阵分析服务地址。请求服务的URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ComputeWeightMatrixService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.ComputeWeightMatrixService"; } /** * @function ComputeWeightMatrixService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function ComputeWeightMatrixService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {ComputeWeightMatrixParameters} params - 耗费矩阵分析参数类 */ processAsync(params) { if (!(params instanceof ComputeWeightMatrixParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'weightmatrix'); jsonObject = { parameter: Util.toJSON(params.parameter), nodes: me.getJson(params.isAnalyzeById, params.nodes) }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ComputeWeightMatrixService.prototype.getJson * @description 将对象转化为JSON字符串。 * @param {boolean} isAnalyzeById - 是否通过id分析 * @param {Array.} params - 分析参数数组 * @returns {string} 转化后的JSON字符串。 */ getJson(isAnalyzeById, params) { var jsonString = "[", len = params ? params.length : 0; if (isAnalyzeById === false) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += '{"x":' + params[i].x + ',"y":' + params[i].y + '}'; } } else if (isAnalyzeById === true) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += params[i]; } } jsonString += ']'; return jsonString; } } ;// CONCATENATED MODULE: ./src/common/iServer/DataFlowService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DataFlowService * @deprecatedclass SuperMap.DataFlowService * @category iServer DataFlow * @classdesc 数据流服务类。 * @extends {CommonServiceBase} * @param {string} url - 数据流服务地址。 * @param {Object} options - 参数。 * @param {function} options.style - 设置数据加载样式。 * @param {function} [options.onEachFeature] - 设置每个数据加载popup等。 * @param {GeoJSONObject} [options.geometry] - 指定几何范围,该范围内的要素才能被订阅。 * @param {Object} [options.excludeField] - 排除字段。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class DataFlowService_DataFlowService extends CommonServiceBase { constructor(url, options) { options = options || {}; /* * @constant EVENT_TYPES * {Array.} * 此类支持的事件类型 */ options.EVENT_TYPES = ["broadcastSocketConnected", "broadcastSocketClosed", "broadcastSocketError", "broadcastFailed", "broadcastSucceeded", "subscribeSocketConnected", "subscribeSocketClosed", "subscribeSocketError", "messageSucceeded", "setFilterParamSucceeded"] super(url, options); /** * @member {GeoJSONObject} DataFlowService.prototype.geometry * @description 指定几何范围,该范围内的要素才能被订阅。 */ this.geometry = null; /** * @member {Object} DataFlowService.prototype.prjCoordSys * @description 动态投影参数。 */ this.prjCoordSys = null; /** * @member {Object} DataFlowService.prototype.excludeField * @description 排除字段。 */ this.excludeField = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.DataFlowService"; } /** * @function DataFlowService.prototype.initBroadcast * @description 初始化广播。 * @returns {DataFlowService} */ initBroadcast() { var me = this; this.broadcastWebSocket = this._connect(Util.urlPathAppend(me.url, 'broadcast')); this.broadcastWebSocket.onopen = function (e) { me.broadcastWebSocket.isOpen = true; e.eventType = 'broadcastSocketConnected'; me.events.triggerEvent('broadcastSocketConnected', e); }; this.broadcastWebSocket.onclose = function (e) { if (me.broadcastWebSocket) { me.broadcastWebSocket.isOpen = false; } e.eventType = 'broadcastSocketClosed'; me.events.triggerEvent('broadcastSocketClosed', e); }; this.broadcastWebSocket.onerror = function (e) { e.eventType = 'broadcastSocketError'; me.events.triggerEvent('broadcastSocketError', e); }; return this; } /** * @function DataFlowService.prototype.broadcast * @description 加载广播数据。 * @param {GeoJSONObject} geoJSONFeature - JSON 格式的要素数据。 */ broadcast(geoJSONFeature) { if (!this.broadcastWebSocket||!this.broadcastWebSocket.isOpen) { this.events.triggerEvent('broadcastFailed'); return; } this.broadcastWebSocket.send(JSON.stringify(geoJSONFeature)); this.events.triggerEvent('broadcastSucceeded'); } /** * @function DataFlowService.prototype.initSubscribe * @description 初始化订阅数据。 * @returns {DataFlowService} DataFlowService的实例对象。 */ initSubscribe() { var me = this; this.subscribeWebSocket = this._connect(Util.urlPathAppend(me.url, 'subscribe')); this.subscribeWebSocket.onopen = function (e) { me.subscribeWebSocket.send(me._getFilterParams()); e.eventType = 'subscribeSocketConnected'; me.events.triggerEvent('subscribeSocketConnected', e); }; this.subscribeWebSocket.onclose = function (e) { e.eventType = 'subscribeWebSocketClosed'; me.events.triggerEvent('subscribeWebSocketClosed', e); }; this.subscribeWebSocket.onerror = function (e) { e.eventType = 'subscribeSocketError'; me.events.triggerEvent('subscribeSocketError', e); }; this.subscribeWebSocket.onmessage = function (e) { me._onMessage(e); }; return this; } /** * @function DataFlowService.prototype.setExcludeField * @description 设置排除字段。 * @param {Object} excludeField - 排除字段。 * @returns {DataFlowService} DataFlowService的实例对象。 */ setExcludeField(excludeField) { this.excludeField = excludeField; this.subscribeWebSocket.send(this._getFilterParams()); return this; } /** * @function DataFlowService.prototype.setGeometry * @description 设置添加的几何要素数据。 * @param {GeoJSONObject} geometry - 指定几何范围,该范围内的要素才能被订阅。 * @returns {DataFlowService} DataFlowService的实例对象。 */ setGeometry(geometry) { this.geometry = geometry; this.subscribeWebSocket.send(this._getFilterParams()); return this; } /** * @function DataFlowService.prototype.unSubscribe * @description 结束订阅数据。 */ unSubscribe() { if (!this.subscribeWebSocket) { return; } this.subscribeWebSocket.close(); this.subscribeWebSocket = null; } /** * @function DataFlowService.prototype.unBroadcast * @description 结束加载广播。 */ unBroadcast() { if (!this.broadcastWebSocket) { return; } this.broadcastWebSocket.close(); this.broadcastWebSocket = null; } /** * @function DataFlowService.prototype.destroy * @override */ destroy() { CommonServiceBase.prototype.destroy.apply(this, arguments); var me = this; me.geometry = null; me.prjCoordSys = null; me.excludeField = null; this.unBroadcast(); this.unSubscribe(); } _getFilterParams() { var filter = { filterParam: { prjCoordSys: this.prjCoordSys, excludeField: this.excludeField, geometry: this.geometry } }; return Util.toJSON(filter); } _onMessage(e) { if (e.data && e.data.indexOf("filterParam") >= 0) { var filterParam = JSON.parse(e.data); e.filterParam = filterParam; e.eventType = 'setFilterParamSucceeded'; this.events.triggerEvent('setFilterParamSucceeded', e); return; } var feature = JSON.parse(e.data); e.featureResult = feature; e.eventType = 'messageSucceeded'; this.events.triggerEvent('messageSucceeded', e); } _connect(url) { url = SecurityManager.appendCredential(url); if ("WebSocket" in window) { return new WebSocket(url); } else if ("MozWebSocket" in window) { var mozWebSocket = window.MozWebSocket; return new mozWebSocket(url); } else { console.log("no WebSocket"); return null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/DatasetInfo.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasetInfo * @deprecatedclass SuperMap.DatasetInfo * @category iServer Data Dataset * @classdesc 数据集信息类。 * 数据集一般为存储在一起的相关数据的集合;根据数据类型的不同,分为矢量数据集、栅格数据集(griddataset)和 * 影像数据集(image dataset),以及为了处理特定问题而设计的数据集,如拓扑数据集,网络数据集等。 * 数据集是 GIS 数据组织的最小单位。其中矢量数据集是由同种类型空间要素组成的集合, * 所以也可以称为要素集。根据要素的空间特征的不同,矢量数据集又分为点数据集, * 线数据集,面数据集等,各矢量数据集是空间特征和性质相同的数据组织起来的集合。 * 目前版本支持的数据集主要有点数据集,线数据集,面数据集,文本数据集,复合数据集(CAD 数据集)、 * 网络数据集,栅格数据集(grid dataset)和影像数据集(image dataset)。 * @param {Object} options - 参数。 * @param {Bounds} [options.bounds] - 数据集范围。 * @param {string} [options.dataSourceName] - 数据源名称。 * @param {string} [options.description] - 数据集的描述信息。 * @param {string} [options.encodeType] - 数据集存储时的压缩编码方式。 * @param {boolean} [options.isReadOnly] - 数据集是否为只读。 * @param {string} options.name - 数据集名称。 * @param {Object} [options.prjCoordSys] - 数据集的投影信息。如:prjCoordSys={"epsgCode":3857}。 * @param {string} [options.tableName] - 表名。 * @param {string} options.type - 数据集类型。主要有点数据集,线数据集,面数据集,文本数据集,复合数据集(CAD 数据集)、网络数据集,栅格数据集(grid dataset)和影像数据集(image dataset)。 * @usage */ class DatasetInfo { constructor(options) { options = options || {}; /** * @member {Bounds} [DatasetInfo.prototype.bounds] * @description 数据集范围,该字段只读。 */ this.bounds = null; /** * @member {string} [DatasetInfo.prototype.dataSourceName] * @description 数据源名称,该字段只读。 */ this.dataSourceName = null; /** * @member {string} [DatasetInfo.prototype.description] * @description 数据集的描述信息。 */ this.description = null; /** * @member {string} [DatasetInfo.prototype.encodeType] * @description 数据集存储时的压缩编码方式,该字段只读。 */ this.encodeType = null; /** * @member {boolean} [DatasetInfo.prototype.isReadOnly] * @description 数据集是否为只读。 */ this.isReadOnly = null; /** * @member {string} DatasetInfo.prototype.name * @description 数据集名称,该字段必须且只读。 */ this.name = null; /** * @member {Object} [DatasetInfo.prototype.prjCoordSys] * @description 数据集的投影信息。 */ this.prjCoordSys = null; /** * @member {string} [DatasetInfo.prototype.tableName] * @description 表名,该字段只读。 */ this.tableName = null; /** * @member {string} DatasetInfo.prototype.type * @description 数据集类型,该字段必设。主要有点数据集,线数据集,面数据集,文本数据集,复合数据集(CAD 数据集)、网络数据集,栅格数据集(grid dataset)和影像数据集(image dataset)。 */ this.type = null; Util.extend(this, options); var b = this.bounds; if (b) { this.bounds = new Bounds(b.leftBottom.x, b.leftBottom.y, b.rightTop.x, b.rightTop.y); } this.CLASS_NAME = "SuperMap.DatasetInfo"; } /** * @function DatasetInfo.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { Util.reset(this); } /** * @function DatasetInfo.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} JSON 对象。 */ toServerJSONObject() { var dataObj = {}; dataObj = Util.copyAttributes(dataObj, this); if (dataObj.bounds) { if (dataObj.bounds.toServerJSONObject) { dataObj.bounds = dataObj.bounds.toServerJSONObject(); } } return dataObj; } } ;// CONCATENATED MODULE: ./src/common/iServer/OverlayAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OverlayAnalystParameters * @deprecatedclass SuperMap.OverlayAnalystParameters * @category iServer SpatialAnalyst OverlayAnalyst * @classdesc 叠加分析参数基类。数据集叠加分析参数和几何对象叠加分析参数均继承此基类。 * @param {Object} options - 参数。 * @usage */ class OverlayAnalystParameters { constructor(options) { /** * @member {OverlayOperationType} [OverlayAnalystParameters.prototype.operation=OverlayOperationType.UNION] * @description 指定叠加分析操作类型。 */ this.operation = OverlayOperationType.UNION; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.OverlayAnalystParameters"; } /** * @function OverlayAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.operation = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/DatasetOverlayAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasetOverlayAnalystParameters * @deprecatedclass SuperMap.DatasetOverlayAnalystParameters * @category iServer SpatialAnalyst OverlayAnalyst * @classdesc 数据集叠加分析参数类。 * @param {Object} options - 参数。 * @param {string} options.operateDataset -数据集名称。 * @param {string} options.sourceDataset - 源数据集名称。 * @param {Array.} [options.operateDatasetFields] - 叠加分析中操作数据集保留在结果数据集中的字段名列表。 * @param {FilterParameter} [options.operateDatasetFilter] - 设置操作数据集中空间对象过滤条件。 * @param {Array.} [options.operateRegions] - 操作面对象集合,表示与这些面对象进行叠加分析。与 operateDataset 参数互斥,冲突时以 operateDataset 为准。 * @param {Array.} [options.sourceDatasetFields] - 叠加分析中源数据集保留在结果数据集中的字段名列表。 * @param {FilterParameter} [options.sourceDatasetFilter] - 设置源数据集中空间对象过滤条件。 * @param {number} [options.tolerance=0] - 容限。 * @param {OverlayOperationType} options.operation - 叠加操作枚举值。 * @param {DataReturnOption} [options.resultSetting] - 结果返回设置类。 * @extends {GetFeaturesParametersBase} * @usage */ class DatasetOverlayAnalystParameters extends OverlayAnalystParameters { constructor(options) { super(options); /** * @member {string} DatasetOverlayAnalystParameters.prototype.operateDataset * @description 叠加分析中操作数据集的名称。 */ this.operateDataset = null; /** * @member {Array.} [DatasetOverlayAnalystParameters.prototype.operateDatasetFields] * @description 叠加分析中操作数据集保留在结果数据集中的字段名列表。 */ this.operateDatasetFields = []; /** * @member {FilterParameter} DatasetOverlayAnalystParameters.prototype.operateDatasetFilter * @description 设置操作数据集中空间对象过滤条件。 */ this.operateDatasetFilter = new FilterParameter(); /** * @member {Array.} [DatasetOverlayAnalystParameters.prototype.operateRegions] * @description 操作面对象集合,表示与这些面对象进行叠加分析。与 operateDataset 参数互斥,冲突时以 operateDataset 为准。 */ this.operateRegions = []; /** * @member {string} DatasetOverlayAnalystParameters.prototype.sourceDataset * @description 叠加分析中源数据集的名称。 */ this.sourceDataset = null; /** * @member {Array.} [DatasetOverlayAnalystParameters.prototype.sourceDatasetFields] * @description 叠加分析中源数据集保留在结果数据集中的字段名列表。 */ this.sourceDatasetFields = []; /** * @member {FilterParameter} [DatasetOverlayAnalystParameters.prototype.filterQueryParameter] * @description 设置源数据集中空间对象过滤条件。 */ this.sourceDatasetFilter = new FilterParameter(); /** * @member {number} [DatasetOverlayAnalystParameters.prototype.tolerance=0] * @description 容限。 */ this.tolerance = 0; /** * @member {DataReturnOption} [DatasetOverlayAnalystParameters.prototype.resultSetting] * @description 结果返回设置类。 */ this.resultSetting = new DataReturnOption(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.DatasetOverlayAnalystParameters"; } /** * @function DatasetOverlayAnalystParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.operateDataset = null; me.operateDatasetFields = null; if (me.operateDatasetFilter) { me.operateDatasetFilter.destroy(); me.operateDatasetFilter = null; } if (me.operateRegions) { for (var i = 0, opRegions = me.operateRegions, len = opRegions.length; i < len; i++) { opRegions[i].destroy(); } me.operateRegions = null; } me.sourceDataset = null; me.sourceDatasetFields = null; if (me.sourceDatasetFilter) { me.sourceDatasetFilter.destroy(); me.sourceDatasetFilter = null; } me.tolerance = null; if (me.resultSetting) { me.resultSetting.destroy(); me.resultSetting = null; } } /** * @function DatasetOverlayAnalystParameters.toObject * @param {DatasetOverlayAnalystParameters} datasetOverlayAnalystParameters - 数据集叠加分析参数类。 * @param {DatasetOverlayAnalystParameters} tempObj - 数据集叠加分析参数对象。 * @description 将数据集叠加分析参数类转换为 JSON 对象。 * @returns {Object} JSON 对象。 */ static toObject(datasetOverlayAnalystParameters, tempObj) { for (var name in datasetOverlayAnalystParameters) { if (name === "sourceDataset") { continue; } else if (name === "operateRegions") { tempObj.operateRegions = []; var ors = datasetOverlayAnalystParameters.operateRegions; for (var index in ors) { if (ors.hasOwnProperty(index)) { //icl542 tempObj.operateRegions[index] = ServerGeometry.fromGeometry(ors[index]); } } } else if (name === "resultSetting") { tempObj.dataReturnOption = datasetOverlayAnalystParameters.resultSetting; } else { tempObj[name] = datasetOverlayAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/SurfaceAnalystParametersSetting.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SurfaceAnalystParametersSetting * @deprecatedclass SuperMap.SurfaceAnalystParametersSetting * @category iServer SpatialAnalyst SurfaceAnalyst * @classdesc 表面分析参数设置类。 * 通过该类可以设置表面分析提取等值线、提取等值面的一些参数,包括基准值、等值距、光滑度、光滑方法等。 * @param {Object} options - 参数。 * @param {GeometryPolygon|L.Polygon|ol.geom.Polygon|GeoJSONObject} [options.clipRegion] - 裁剪面对象,如果不需要对操作结果进行裁剪,可以使用 null 值取代该参数。 * @param {number} [options.datumValue=0] - 提取等值线、提取等值面的基准值。 * @param {Array.} options.expectedZValues - 期望分析结果的 Z 值集合。 * @param {number} [options.interval=0] - 等值距。等值距是两条等值线之间的间隔值。 * @param {number} [options.resampleTolerance=0] - 重采样容限。 * @param {SmoothMethod} [options.smoothMethod=SmoothMethod.BSPLINE] - 光滑处理所使用的方法。 * @param {number} [options.smoothness=0] - 等值线或等值面的边界线的光滑度。 * @usage */ class SurfaceAnalystParametersSetting { constructor(options) { /** * @member {GeometryPolygon|L.Polygon|ol.geom.Polygon|GeoJSONObject} [SurfaceAnalystParametersSetting.prototype.clipRegion] * @description 获取或设置裁剪面对象,如果不需要对操作结果进行裁剪,可以使用 null 值取代该参数。 */ this.clipRegion = null; /** * @member {number} [SurfaceAnalystParametersSetting.prototype.datumValue=0] * @description 获取或设置表面分析中提取等值线、提取等值面的基准值。 * 基准值是作为一个生成等值线的初始起算值,并不一定是最小等值线的值。例如,高程范围为 220 -1550 的 DEM 栅格数据, * 如果设基准值为 0,等值距为 50,则提取等值线时,以基准值 0 为起点,等值距 50 为间隔提取等值线, * 因为给定高程的最小值是 220,所以,在给定范围内提取等值线的最小高程是 250。 * 提取等值线的结果是:最小等值线值为 250,最大等值线值为 1550。 */ this.datumValue = 0; /** * @member {Array.} SurfaceAnalystParametersSetting.prototype.expectedZValues * @description 获取或设置期望分析结果的 Z 值集合。 * Z 值集合存储一系列数值,该数值为待提取等值线的值。即仅高程值在 Z 值集合中的等值线会被提取。 */ this.expectedZValues = null; /** * @member {number} [SurfaceAnalystParametersSetting.prototype.interval=0] * @description 获取或设置等值距。等值距是两条等值线之间的间隔值。 */ this.interval = 0; /** * @member {number} [SurfaceAnalystParametersSetting.prototype.resampleTolerance=0] * @description 获取或设置重采样容限。 * 容限值越大,采样结果数据越简化。当分析结果出现交叉时,可通过调整重采样容限为较小的值来处理。 */ this.resampleTolerance = 0; /** * @member {SmoothMethod} [SurfaceAnalystParametersSetting.prototype.smoothMethod=SmoothMethod.BSPLINE] * @description 获取或设置光滑处理所使用的方法。 */ this.smoothMethod = SmoothMethod.BSPLINE; /** * @member {number} [SurfaceAnalystParametersSetting.prototype.smoothness=0] * @description 获取或设置表面分析中等值线或等值面的边界线的光滑度。 * 以为 0-5 为例,光滑度为 0 表示不进行光滑操作,值越大表示光滑度越高。 * 随着光滑度的增加,提取的等值线越光滑,当然光滑度越大, * 计算所需的时间和占用的内存也就越大。而且,当等值距较小时, * 光滑度太高会出现等值线相交的问题。 */ this.smoothness = 0; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.SurfaceAnalystParametersSetting"; } /** * @function SurfaceAnalystParametersSetting.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.clipRegion) { me.clipRegion.destroy(); me.clipRegion = null; } me.datumValue = null; me.expectedZValues = null; me.interval = null; me.resampleTolerance = null; me.smoothMethod = null; me.smoothness = null; } /** * @function SurfaceAnalystParametersSetting.prototype.toJSON * @description 将对象转化为 JSON 字符串。 * @returns {string} 对象 JSON 字符串。 */ toJSON() { let json = "'datumValue':" + Util.toJSON(this.datumValue); json += ",'interval':" + Util.toJSON(this.interval); json += ",'resampleTolerance':" + Util.toJSON(this.resampleTolerance); json += ",'smoothMethod':" + Util.toJSON(this.smoothMethod); json += ",'smoothness':" + Util.toJSON(this.smoothness); if (this.expectedZValues != null) { json += "," + "'expectedZValues':" + Util.toJSON(this.expectedZValues); } if (this.clipRegion != null) { var serverGeometry = this.clipRegion; if (this.clipRegion instanceof Geometry_Geometry && this.clipRegion.components) { serverGeometry = ServerGeometry.fromGeometry(this.clipRegion) } json += ",'clipRegion':" + Util.toJSON(serverGeometry); } return "{" + json + "}"; } } ;// CONCATENATED MODULE: ./src/common/iServer/SurfaceAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SurfaceAnalystParameters * @deprecatedclass SuperMap.SurfaceAnalystParameters * @category iServer SpatialAnalyst SurfaceAnalyst * @classdesc 表面分析提取操作参数类。通过该类可以为进行表面分析提供参数信息,包括表面分析的方法提取等值线、提取等值面和中间结果的分辨率, * {@link DatasetSurfaceAnalystParameters} 和 {@link GeometrySurfaceAnalystParameters} 继承自该类。 * @param {Object} options - 参数。 * @param {SurfaceAnalystParametersSetting} options.extractParameter - 表面分析参数设置类。 * @param {number} options.resolution - 指定中间结果(栅格数据集)的分辨率。 * @param {DataReturnOption} options.resultSetting - 结果返回设置类。 * @param {SurfaceAnalystMethod} [options.surfaceAnalystMethod=SurfaceAnalystMethod.ISOLINE] - 获取或设置表面分析的提取方法,提取等值线和提取等值面。 * @usage */ class SurfaceAnalystParameters { constructor(options) { /** * @member {number} SurfaceAnalystParameters.prototype.resolution * @description 获取或设置指定中间结果(栅格数据集)的分辨率。 */ this.resolution = 0; /** * @member {SurfaceAnalystParametersSetting} SurfaceAnalystParameters.prototype.extractParameter * @description 获取或设置表面分析参数。 * 在进行点数据集进行提取等值面分析时,暂时不支持 SurfaceAnalystParametersSetting 类中的 expectedZValues 字段。 */ this.extractParameter = new SurfaceAnalystParametersSetting(); /** * @member {DataReturnOption} SurfaceAnalystParameters.prototype.resultSetting * @description 结果返回设置类。 */ this.resultSetting = new DataReturnOption(); /** * @member {SurfaceAnalystMethod} [SurfaceAnalystParameters.prototype.surfaceAnalystMethod=SurfaceAnalystMethod.ISOLINE] * @description 获取或设置表面分析的提取方法,提取等值线和提取等值面。 */ this.surfaceAnalystMethod = SurfaceAnalystMethod.ISOLINE; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.SurfaceAnalystParameters"; } /** * @function SurfaceAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.resolution = null; if (me.extractParameter) { me.extractParameter.destroy(); me.extractParameter = null; } if (me.resultSetting) { me.resultSetting.destroy(); me.resultSetting = null; } me.surfaceAnalystMethod = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/DatasetSurfaceAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasetSurfaceAnalystParameters * @deprecatedclass SuperMap.DatasetSurfaceAnalystParameters * @category iServer SpatialAnalyst SurfaceAnalyst * @classdesc 数据集表面分析参数类。该类对数据集表面分析所用到的参数进行设置。 * @param {Object} options - 参数。 * @param {string} options.dataset - 数据集名称。 * @param {string} options.zValueFieldName - 字段名称。 * @param {number} options.resolution - 指定中间结果(栅格数据集)的分辨率。 * @param {SurfaceAnalystParametersSetting} options.extractParameter - 表面分析参数设置类。获取或设置表面分析参数。 * @param {FilterParameter} [options.filterQueryParameter] - 查询过滤条件参数。 * @param {DataReturnOption} [options.resultSetting] - 结果返回设置类。 * @param {SurfaceAnalystMethod} [options.surfaceAnalystMethod=SurfaceAnalystMethod.ISOLINE] - 表面分析的提取方法,提取等值线和提取等值面。 * @extends {SurfaceAnalystParameters} * @usage */ class DatasetSurfaceAnalystParameters extends SurfaceAnalystParameters { constructor(options) { super(options); /** * @member {string} DatasetSurfaceAnalystParameters.prototype.dataset * @description 要用来做数据集表面分析的数据源中数据集的名称。该名称用形如 "数据集名称@数据源别名" 形式来表示,例如:Country@World。 */ this.dataset = null; /** * @member {FilterParameter} DatasetSurfaceAnalystParameters.prototype.filterQueryParameter * @description 获取或设置查询过滤条件参数。 */ this.filterQueryParameter = new FilterParameter(); /** * @member {string} DatasetSurfaceAnalystParameters.prototype.zValueFieldName * @description 获取或设置用于提取操作的字段名称。提取等值线时,将使用该字段中的值,对点记录集中的点数据进行插值分析,得到栅格数据集(中间结果),接着从栅格数据集提取等值线。 */ this.zValueFieldName = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.DatasetSurfaceAnalystParameters"; } /** * @function DatasetSurfaceAnalystParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.dataset = null; if (me.filterQueryParameter) { me.filterQueryParameter.destroy(); me.filterQueryParameter = null; } me.zValueFieldName = null; } /** * @function DatasetSurfaceAnalystParameters.toObject * @param {DatasetSurfaceAnalystParameters} datasetSurfaceAnalystParameters - 数据集表面分析参数类。 * @param {DatasetSurfaceAnalystParameters} tempObj - 数据集表面分析参数对象。 * @description 将数据集表面分析参数对象转换为 JSON 对象。 * @returns JSON 对象。 */ static toObject(datasetSurfaceAnalystParameters, tempObj) { for (var name in datasetSurfaceAnalystParameters) { if (name === "filterQueryParameter") { tempObj.filterQueryParameter = datasetSurfaceAnalystParameters.filterQueryParameter; } if (name === "extractParameter") { if (datasetSurfaceAnalystParameters.extractParameter.clipRegion instanceof Geometry_Geometry && datasetSurfaceAnalystParameters.extractParameter.clipRegion.components) { datasetSurfaceAnalystParameters.extractParameter.clipRegion = ServerGeometry.fromGeometry(datasetSurfaceAnalystParameters.extractParameter.clipRegion); } tempObj.extractParameter = datasetSurfaceAnalystParameters.extractParameter; } else if (name === "dataset") { continue; } else if (name === "surfaceAnalystMethod") { continue; } else { tempObj[name] = datasetSurfaceAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/ThiessenAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThiessenAnalystParameters * @deprecatedclass SuperMap.ThiessenAnalystParameters * @category iServer SpatialAnalyst ThiessenPolygonAnalyst * @classdesc 泰森多边形分析参数基类。 * @param {Object} options - 可选参数。 * @param {GeometryPolygon|L.Polygon|ol.geom.Polygon|GeoJSONObject} [options.clipRegion] - 结果数据裁剪区域,可以为 null,表示不对结果进行裁剪。 * @param {boolean} [options.createResultDataset=false] - 是否返回结果数据集。 * @param {string} [options.resultDatasetName] - 指定结果数据集名称。 * @param {string} [options.resultDatasourceName] - 指定结果数据集所在数据源,默认为当前数据源。 * @param {boolean} [options.returnResultRegion=true] - 是否返回分析得到的多边形面数组。 * @usage */ class ThiessenAnalystParameters { constructor(options) { if (!options) { return; } /** * @member {GeometryPolygon|L.Polygon|ol.geom.Polygon|GeoJSONObject} [ThiessenAnalystParameters.prototype.clipRegion] * @description 结果数据裁剪区域,可以为 null,表示不对结果进行裁剪。 */ this.clipRegion = null; /** * @member {boolean} [ThiessenAnalystParameters.prototype.createResultDataset=false] * @description 是否返回结果数据集。如果为 true,则必须设置属性 resultDatasetName 和 resultDatasourceName。 */ this.createResultDataset = false; /** * @member {string} ThiessenAnalystParameters.prototype.resultDatasetName * @description 指定结果数据集名称。 */ this.resultDatasetName = null; /** * @member {string} ThiessenAnalystParameters.prototype.resultDatasourceName * @description 指定结果数据集所在数据源。 */ this.resultDatasourceName = null; /** * @member {boolean} ThiessenAnalystParameters.prototype.returnResultRegion * @description 是否返回分析得到的多边形面数组。 */ this.returnResultRegion = true; Util.extend(this, options); this.CLASS_NAME = "SuperMap.ThiessenAnalystParameters"; } /** * @function ThiessenAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.clipRegion) { me.clipRegion.destroy(); me.clipRegion = null; } me.createResultDataset = null; me.resultDatasetName = null; me.resultDatasourceName = null; me.returnResultRegion = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/DatasetThiessenAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasetThiessenAnalystParameters * @deprecatedclass SuperMap.DatasetThiessenAnalystParameters * @category iServer SpatialAnalyst ThiessenAnalyst * @classdesc 数据集泰森多边形分析参数类。 * @param {Object} options - 参数。 * @param {FilterParameter} [options.filterQueryParameter] - 过滤参数类,即对数据集中的所有点进行分析。 * @extends {ThiessenAnalystParameters} * @usage */ class DatasetThiessenAnalystParameters extends ThiessenAnalystParameters { constructor(options) { super(options); /** * @member {FilterParameter} [DatasetThiessenAnalystParameters.prototype.filterQueryParameter] * @description 过滤条件,对待分析数据集中的点进行过滤,即对数据集中的所有点进行分析。 * @example * var filterQueryParameter = new FilterParameter({ * name: "Countries@World", * attributeFilter: "SmID>100" * }); */ this.filterQueryParameter = null; /** * @member {string} DatasetThiessenAnalystParameters.prototype.dataset * @description 数据集名称待分析的数据集名称,请使用 "datasetName@datasourceName" 格式来表示。 */ this.dataset = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.DatasetThiessenAnalystParameters"; } /** * @function DatasetThiessenAnalystParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.filterQueryParameter) { me.filterQueryParameter.destroy(); me.filterQueryParameter = null; } } /** * @function DatasetThiessenAnalystParameters.toObject * @param {DatasetThiessenAnalystParameters} datasetThiessenAnalystParameters - 泰森多边形分析服务参数类。 * @param {DatasetThiessenAnalystParameters} tempObj - 泰森多边形分析服务参数对象。 * @description 将泰森多边形分析服务参数对象转换为 JSON 对象。 * @returns JSON 对象。 */ static toObject(datasetThiessenAnalystParameters, tempObj) { for (var name in datasetThiessenAnalystParameters) { if (name === "clipRegion") { tempObj.clipRegion = ServerGeometry.fromGeometry(datasetThiessenAnalystParameters.clipRegion); } else { tempObj[name] = datasetThiessenAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/DatasourceService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasourceService * @deprecatedclass SuperMap.DatasourceService * @category iServer Data Datasource * @classdesc 数据源查询服务。 * @param {string} url - 服务地址。如访问World Data服务,只需将url设为:http://localhost:8090/iserver/services/data-world/rest/data 即可。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {string} options.datasource - 要查询的数据集所在的数据源名称。 * @param {string} options.dataset - 要查询的数据集名称。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {CommonServiceBase} * @usage */ class DatasourceService_DatasourceService extends CommonServiceBase { constructor(url, options) { super(url, options); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.DatasourceService"; } /** * @function DatasourceService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function DatasourceService.prototype.getDatasourceService * @description 获取指定数据源信息。 */ getDatasourceService(datasourceName) { var me = this; me.url = Util.urlPathAppend(me.url,`datasources/name/${datasourceName}`); me.request({ method: "GET", data: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function DatasourceService.prototype.getDatasourcesService * @description 获取所有数据源信息。 */ getDatasourcesService() { var me = this; me.url = Util.urlPathAppend(me.url,`datasources`); me.request({ method: "GET", data: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function DatasourceService.prototype.setDatasourceService * @description 更新数据源信息。 */ setDatasourceService(params) { if (!params) { return; } var me = this; var jsonParamsStr = Util.toJSON(params); me.request({ method: "PUT", data: jsonParamsStr, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/DensityKernelAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DensityKernelAnalystParameters * @deprecatedclass SuperMap.DensityKernelAnalystParameters * @category iServer SpatialAnalyst DensityAnalyst * @classdesc 核密度分析参数类。 * @param {Object} options - 参数。 * @param {string} options.dataset - 要用来做核密度分析数据源中数据集的名称。该名称用形如 "数据集名称@数据源别名" 形式来表示,例如:BaseMap_P@Jingjin。 * @param {string} options.fieldName - 用于进行核密度分析的测量值的字段名称,核密度分析不支持文本类型的字段。 * @param {string} options.resultGridName - 指定结果数据集名称。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} [options.bounds] - 核密度分析的范围,用于确定结果栅格数据集的范围。如果缺省,则默认为原数据集的范围。 * @param {number} [options.searchRadius] - 栅格邻域内用于计算密度的查找半径,单位与当前数据集相同。默认值为当前数据集的长宽中的最大值除30。 * @param {number} [options.resultGridDatasetResolution] - 密度分析结果栅格数据的分辨率,单位与当前数据集相同。默认值为当前数据集的长宽中的最小值除500。 * @param {string} [options.targetDatasource] - 指定的存储结果数据集的数据源,默认为当前分析的数据集所在的数据源。 * @param {boolean} [options.deleteExistResultDataset=false] - 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 * @usage */ class DensityKernelAnalystParameters { constructor(options) { /** * @member {string} DensityKernelAnalystParameters.prototype.dataset * @description 要用来做核密度分析数据源中数据集的名称。 * 该名称用形如 "数据集名称@数据源别名" 形式来表示,例如:Railway@Changchun。 * 注:核密度分析支持点数据集和线数据集。 */ this.dataset = null; /** * @member {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} [DensityKernelAnalystParameters.prototype.bounds] * @description 核密度分析的范围,用于确定结果栅格数据集的范围。 * 如果缺省,则默认为原数据集的范围。 */ this.bounds = null; /** * @member {string} DensityKernelAnalystParameters.prototype.fieldName * @description 用于进行核密度分析的测量值的字段名称,核密度分析不支持文本类型的字段。 */ this.fieldName = null; /** * @member {number} [DensityKernelAnalystParameters.prototype.resultGridDatasetResolution] * @description 密度分析结果栅格数据的分辨率,单位与当前数据集相同。默认值为当前数据集的长宽中的最小值除500。 */ this.resultGridDatasetResolution = null; /** * @member {number} [DensityKernelAnalystParameters.prototype.searchRadius] * @description 栅格邻域内用于计算密度的查找半径,单位与当前数据集相同。默认值为当前数据集的长宽中的最大值除30。 */ this.searchRadius = null; /** * @member {string} [DensityKernelAnalystParameters.prototype.targetDatasource] * @description 指定的存储结果数据集的数据源,默认为当前分析的数据集所在的数据源。 */ this.targetDatasource = null; /** * @member {string} DensityKernelAnalystParameters.prototype.resultGridName * @description 指定结果数据集名称。 */ this.resultGridName = null; /** * @member {boolean} [DensityKernelAnalystParameters.prototype.deleteExistResultDataset=false] * @description 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 */ this.deleteExistResultDataset = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.DensityKernelAnalystParameters"; } /** * @function DensityKernelAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.dataset = null; me.bounds = null; me.fieldName = null; me.resultGridDatasetResolution = null; me.searchRadius = null; me.targetDatasource = null; me.resultGridName = null; me.deleteExistResultDataset = null; } /** * @function DensityKernelAnalystParameters.toObject * @param {DensityKernelAnalystParameters} densityKernelAnalystParameters -核密度分析参数类。 * @param {DensityKernelAnalystParameters} tempObj - 核密度分析参数对象。 * @description 将核密度分析参数对象转换成 JSON 对象。 * @returns JSON 对象。 */ static toObject(densityKernelAnalystParameters, tempObj) { for (var name in densityKernelAnalystParameters) { if (name !== "dataset") { tempObj[name] = densityKernelAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/DensityAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DensityAnalystService * @deprecatedclass SuperMap.DensityAnalystService * @category iServer SpatialAnalyst DensityAnalyst * @classdesc * 密度分析服务类,密度分析可计算每个输出栅格像元周围圆形邻域内输入的点或线对象的密度。 * 密度分析,在某种意义上来说,相当于在表面上将输入的点线对象的测量值散开来,将每个点或线对象的测量量分布在整个研究区域,并计算输出栅格中每个像元的密度值。目前提供1种密度分析:核密度分析(Kernel)。 * @param {string} url - 服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst 。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 例如: * var myDensityAnalystService = new DensityAnalystService(url); * myDensityAnalystService.on({ * "processCompleted": processCompleted, * "processFailed": processFailed * } * ); * @usage */ class DensityAnalystService extends SpatialAnalystBase { constructor(url, options) { super(url, options); /** * @member {string} DensityAnalystService.prototype.mode * @description 密度分析类型。 */ this.mode = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.DensityAnalystService"; } /** * @function DensityAnalystService.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); this.mode = null; } /** * @function DensityAnalystService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {DensityKernelAnalystParameters} parameter - 核密度分析参数。 */ processAsync(parameter) { var me = this; var parameterObject = new Object(); if (parameter instanceof DensityKernelAnalystParameters) { me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/densityanalyst/kernel'); me.mode = "kernel"; } DensityKernelAnalystParameters.toObject(parameter, parameterObject); var jsonParameters = Util.toJSON(parameterObject); me.url = Util.urlAppend(me.url, 'returnContent=true'); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/EditFeaturesParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class EditFeaturesParameters * @deprecatedclass SuperMap.EditFeaturesParameters * @category iServer Data Feature * @classdesc 数据集添加、修改、删除参数类。 * @param {Object} options - 参数。 * @param {Array.} options.features - 当前需要创建或者是修改的要素集。 * @param {boolean} [options.returnContent=false] - 是否返回要素内容。如果为true则返回创建要素的 ID 数组,否则返回 featureResult 资源的 URI。 * @param {EditType} [options.editType=EditType.ADD] - POST 动作类型 (ADD、UPDATE、DELETE)。 * @param {Array.} [options.IDs] - 删除要素时的要素的 ID 数组。 * @usage */ class EditFeaturesParameters { constructor(options) { /** * @member {string} EditFeaturesParameters.prototype.dataSourceName * @description 当前需要创建或者是修改的要素的数据源。 */ this.dataSourceName = null; /** * @member {string} EditFeaturesParameters.prototype.dataSetName * @description 当前需要创建或者是修改的要素的数据集。 */ this.dataSetName = null; /** * @member {Array.} EditFeaturesParameters.prototype.features * @description 当前需要创建或者是修改的要素集。 */ this.features = null; /** * @member {EditType} [EditFeaturesParameters.prototype.editType=EditType.ADD] * @description 要素集更新类型 (add、update、delete)。 */ this.editType = EditType.ADD; /** * @member {Array.} [EditFeaturesParameters.prototype.IDs] * @description 执行删除时要素集 ID 集合。 */ this.IDs = null; /** * @member {boolean} [EditFeaturesParameters.prototype.returnContent=false] * @description 要素添加时,isUseBatch 不传或传为 false 的情况下有效。 * true 表示直接返回新创建的要素的 ID 数组;false 表示返回创建的 featureResult 资源的 URI。 */ this.returnContent = false; /** * @member {boolean} [EditFeaturesParameters.prototype.isUseBatch=false] * @description 是否使用批量添加要素功能,要素添加时有效。批量添加能够提高要素编辑效率。true 表示批量添加;false 表示不使用批量添加。 */ this.isUseBatch = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.EditFeaturesParameters"; } /** * @function EditFeaturesParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.dataSourceName = null; me.dataSetName = null; me.features = null; me.editType = null; me.IDs = null; me.returnContent = null; } /** * @function EditFeaturesParameters.prototype.toJsonParameters * @description 将 EditFeaturesParameters 对象参数转换为 JSON 字符串。 * @param {EditFeaturesParameters} params - 地物编辑参数。 * @returns {string} JSON 字符串。 */ static toJsonParameters(params) { var feature, len, features, editType = params.editType; if (editType === EditType.DELETE) { if (params.IDs === null) { return; } features = {ids: params.IDs}; } else { features = []; if (params.features) { len = params.features.length; for (var i = 0; i < len; i++) { feature = params.features[i]; feature.geometry = ServerGeometry.fromGeometry(feature.geometry); features.push(feature); } } } return Util.toJSON(features); } } ;// CONCATENATED MODULE: ./src/common/iServer/EditFeaturesService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class EditFeaturesService * @deprecatedclass SuperMap.EditFeaturesService * @category iServer Data Feature * @classdesc 数据服务中数据集添加、更新、删除服务类。 * @extends {CommonServiceBase} * @param {string} url - 服务端的数据服务资源地址。请求数据服务中数据集编辑服务,URL 应为:
* http://{服务器地址}:{服务端口号}/iserver/services/{数据服务名}/rest/data/datasources/name/{数据源名}/datasets/name/{数据集名} 。
* 例如:http://localhost:8090/iserver/services/data-jingjin/rest/data/datasources/name/Jingjin/datasets/name/Landuse_R * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [format] -查询结果返回格式,目前支持iServerJSON 和GeoJSON两种格式。参数格式为"ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * var myService = new EditFeaturesService(url, {eventListeners: { * "processCompleted": editFeatureCompleted, * "processFailed": editFeatureError * } * }; * @usage */ class EditFeaturesService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {boolean} [EditFeaturesService.prototype.returnContent=false] * @description要素添加时,isUseBatch 不传或传为 false 的情况下有效。true 表示直接返回新创建的要素的 ID 数组;false 表示返回创建的 featureResult 资源的 URI。 */ this.returnContent = false; /** * @member {boolean} [EditFeaturesService.prototype.isUseBatch=false] * @description 是否使用批量添加要素功能,要素添加时有效。 * 批量添加能够提高要素编辑效率。 * true 表示批量添加;false 表示不使用批量添加。 */ this.isUseBatch = false; if (options) { Util.extend(this, options); } this.url = Util.urlPathAppend(this.url, 'features'); this.CLASS_NAME = "SuperMap.EditFeaturesService"; } /** * @function EditFeaturesService.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.returnContent = null; me.isUseBatch = null; me.fromIndex = null; me.toIndex = null; } /** * @function EditFeaturesService.prototype.processAsync * @description 负责将客户端的更新参数传递到服务端。 * @param {EditFeaturesParameters} params - 编辑要素参数。 */ processAsync(params) { if (!(params instanceof EditFeaturesParameters)) { return; } var me = this, method = "POST", ids = "", editType = params.editType, jsonParameters = null; me.returnContent = params.returnContent; me.isUseBatch = params.isUseBatch; jsonParameters = EditFeaturesParameters.toJsonParameters(params); if (editType === EditType.DELETE) { ids = Util.toJSON(params.IDs); jsonParameters = ids; var urlWithIds = Util.urlAppend(me.url, Util.getParameterString({ids})) if(FetchRequest.urlIsLong(urlWithIds)) { me.url = Util.urlAppend(me.url, Util.getParameterString({_method: 'DELETE'})); method = "POST"; } else{ me.url = urlWithIds; method = "DELETE"; } } else if (editType === EditType.UPDATE) { method = "PUT"; } else { if (me.isUseBatch) { me.url = Util.urlAppend(me.url, `isUseBatch=${me.isUseBatch}`); me.returnContent = false; } if (me.returnContent) { me.url = Util.urlAppend(me.url, 'returnContent=true'); method = "POST"; } } me.request({ method: method, data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalyst3DParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalyst3DParameters * @deprecatedclass SuperMap.FacilityAnalyst3DParameters * @category iServer FacilityAnalyst3D * @classdesc 最近设施分析参数基类。最近设施分析是指在网络上给定一个事件点和一组设施点,查找从事件点到设施点(或从设施点到事件点)以最小耗费能到达的最佳路径。 * 设施点一般为学校、超市、加油站等服务设施;事件点为需要服务设施的事件位置。例如事件发生点是一起交通事故,要求查找在 10 分钟内能到达的最近医院, * 超过 10 分钟能到达的都不予考虑。此例中,事故发生地即是一个事件点,周边的医院则是设施点。最近设施查找实际上也是一种路径分析,因此对路径分析起作用的障碍边、障碍点、转向表、耗费等属性在最近设施分析时同样可设置。 * @param {Object} options - 参数。 * @param {string} options.weightName - 指定的权值字段信息对象的名称。 * @param {number} [options.edgeID] - 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。 * @param {number} [options.nodeID] - 指定的结点 ID,edgeID 与 nodeID 必须指定一个。 * @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行; * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 * @usage */ class FacilityAnalyst3DParameters { constructor(options) { /** * @member {number} [FacilityAnalyst3DParameters.prototype.edgeID] * @description 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。 */ this.edgeID = null; /** * @member {number} [FacilityAnalyst3DParameters.prototype.nodeID] * @description 指定的结点 ID,edgeID 与 nodeID 必须指定一个。 */ this.nodeID = null; /** * @member {string} FacilityAnalyst3DParameters.prototype.weightName * @description 指定的权值字段信息对象的名称。 */ this.weightName = null; /** * @member {boolean} [FacilityAnalyst3DParameters.prototype.isUncertainDirectionValid=false] * @description 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行; * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 */ this.isUncertainDirectionValid = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.FacilityAnalyst3DParameters"; } /** * @function FacilityAnalyst3DParameters.prototype.destroy * @description 释放资源,将资源的属性置空。 */ destroy() { var me = this; me.edgeID = null; me.nodeID = null; me.weightName = null; me.isUncertainDirectionValid = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystSinks3DParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystSinks3DParameters * @deprecatedclass SuperMap.FacilityAnalystSinks3DParameters * @category iServer FacilityAnalyst3D Sinks * @classdesc 最近设施分析参数类(汇查找资源)。最近设施分析是指在网络上给定一个事件点和一组设施点,查找从事件点到设施点(或从设施点到事件点)以最小耗费能到达的最佳路径。 * 设施点一般为学校、超市、加油站等服务设施;事件点为需要服务设施的事件位置。例如事件发生点是一起交通事故,要求查找在10分钟内能到达的最近医院,超过10分钟能到达的都不予考虑。此例中,事故发生地即是一个事件点,周边的医院则是设施点。最近设施查找实际上也是一种路径分析,因此对路径分析起作用的障碍边、障碍点、转向表、耗费等属性在最近设施分析时同样可设置。 * @extends {FacilityAnalyst3DParameters} * @param {Object} options - 参数。 * @param {string} options.weightName - 指定的权值字段信息对象的名称。 * @param {number} [options.edgeID] - 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。 * @param {number} [options.nodeID] - 指定的结点 ID,edgeID 与 nodeID 必须指定一个。 * @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行; * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 * @usage */ class FacilityAnalystSinks3DParameters extends FacilityAnalyst3DParameters { constructor(options) { super(options); this.CLASS_NAME = "SuperMap.FacilityAnalystSinks3DParameters"; } /** * @function FacilityAnalystSinks3DParameters.prototype.destroy * @override */ destroy() { super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystSinks3DService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystSinks3DService * @deprecatedclass SuperMap.FacilityAnalystSinks3DService * @category iServer FacilityAnalyst3D Sinks * @classdesc 最近设施分析服务类(汇查找资源)
* 最近设施分析是指在网络上给定一个事件点和一组设施点, * 查找从事件点到设施点(或从设施点到事件点)以最小耗费能到达的最佳路径。 * 该类负责将客户端指定的最近设施分析参数传递给服务端,并接收服务端返回的结果数据。 * 最近设施分析结果通过该类支持的事件的监听函数参数获取 * @extends {CommonServiceBase} * @example * var myFacilityAnalystSinks3DService = new FacilityAnalystSinks3DService(url, { * eventListeners: { * "processCompleted": facilityAnalystSinks3DCompleted, * "processFailed": facilityAnalystSinks3DError * } * }); * @param {string} url - 网络分析服务地址。请求网络分析服务,URL应为:
* http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源};
* 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。
* @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FacilityAnalystSinks3DService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FacilityAnalystSinks3DService"; } /** * @function FacilityAnalystSinks3DService.prototype.destroy * @override */ destroy() { CommonServiceBase.prototype.destroy.apply(this, arguments); } /** * @function FacilityAnalystSinks3DService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FacilityAnalystSinks3DParameters} params - 最近设施分析参数类(汇查找资源) */ processAsync(params) { if (!(params instanceof FacilityAnalystSinks3DParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'sinks'); jsonObject = { edgeID: params.edgeID, nodeID: params.nodeID, weightName: params.weightName, isUncertainDirectionValid: params.isUncertainDirectionValid }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystSources3DParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystSources3DParameters * @deprecatedclass SuperMap.FacilityAnalystSources3DParameters * @category iServer FacilityAnalyst3D Sources * @classdesc 最近设施分析参数类(源查找资源)。最近设施分析是指在网络上给定一个事件点和一组设施点,查找从事件点到设施点(或从设施点到事件点)以最小耗费能到达的最佳路径。 * 设施点一般为学校、超市、加油站等服务设施;事件点为需要服务设施的事件位置。例如事件发生点是一起交通事故,要求查找在10分钟内能到达的最近医院,超过10分钟能到达的都不予考虑。此例中,事故发生地即是一个事件点,周边的医院则是设施点。最近设施查找实际上也是一种路径分析,因此对路径分析起作用的障碍边、障碍点、转向表、耗费等属性在最近设施分析时同样可设置。 * @extends {FacilityAnalyst3DParameters} * @param {Object} options - 参数。 * @param {string} options.weightName - 指定的权值字段信息对象的名称。 * @param {number} [options.edgeID] - 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。 * @param {number} [options.nodeID] - 指定的结点 ID,edgeID 与 nodeID 必须指定一个。 * @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行; * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 * @usage */ class FacilityAnalystSources3DParameters extends FacilityAnalyst3DParameters { constructor(options) { super(options); this.CLASS_NAME = "SuperMap.FacilityAnalystSources3DParameters"; } /** * @function FacilityAnalystSources3DParameters.prototype.destroy * @override */ destroy() { super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystSources3DService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystSources3DService * @deprecatedclass SuperMap.FacilityAnalystSources3DService * @category iServer FacilityAnalyst3D Sources * @classdesc 最近设施分析服务类(源查找资源) * 最近设施分析是指在网络上给定一个事件点和一组设施点, * 查找从事件点到设施点(或从设施点到事件点)以最小耗费能到达的最佳路径。 * 该类负责将客户端指定的最近设施分析参数传递给服务端,并接收服务端返回的结果数据。 * 最近设施分析结果通过该类支持的事件的监听函数参数获取。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FacilityAnalystSources3DService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FacilityAnalystSources3DService"; } /** * @function FacilityAnalystSources3DService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FacilityAnalystSources3DService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FacilityAnalystSources3DParameters} params - 最近设施分析参数类(源查找资源) */ processAsync(params) { if (!(params instanceof FacilityAnalystSources3DParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'sources'); jsonObject = { edgeID: params.edgeID, nodeID: params.nodeID, weightName: params.weightName, isUncertainDirectionValid: params.isUncertainDirectionValid }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystStreamParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystStreamParameters * @deprecatedclass SuperMap.FacilityAnalystStreamParameters * @category iServer NetworkAnalyst UpstreamCirticalFaclilities * @classdesc 上游/下游关键设施查找资源参数类。 * @param {Object} options - 参数。 * @param {Array.} options.sourceNodeIDs - 指定的设施点 ID 数组。 * @param {number} options.queryType - 分析类型,只能是 0 (上游关键设施查询) 或者是 1(下游关键设施查询)。 * @param {number} [options.edgeID] - 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。 * @param {number} [options.nodeID] - 指定的结点 ID,edgeID 与 nodeID 必须指定一个。 * @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。 * @usage */ class FacilityAnalystStreamParameters { constructor(options) { /** * @member {Array.} [FacilityAnalystStreamParameters.prototype.sourceNodeIDs] * @description 指定的设施点 ID 数组。 */ this.sourceNodeIDs = null; /** * @member {number} [FacilityAnalystStreamParameters.prototype.edgeID] * @description 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。 */ this.edgeID = null; /** * @member {number} [FacilityAnalystStreamParameters.prototype.nodeID] * @description 指定的结点 ID,edgeID 与 nodeID 必须指定一个。 */ this.nodeID = null; /** * @member {boolean} [FacilityAnalystStreamParameters.prototype.isUncertainDirectionValid=false] * @description 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行; * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 */ this.isUncertainDirectionValid = false; /** * @member {number} FacilityAnalystStreamParameters.prototype.queryType * @description 分析类型,只能是 0 (上游关键设施查询) 或者是 1(下游关键设施查询)。 */ this.queryType = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.FacilityAnalystStreamParameters"; } /** * @function FacilityAnalystStreamParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.edgeID = null; me.nodeID = null; me.weightName = null; me.isUncertainDirectionValid = null; me.type = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystStreamService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystStreamService * @deprecatedclass SuperMap.FacilityAnalystStreamService * @category iServer NetworkAnalyst UpstreamCirticalFaclilities * @classdesc 上游/下游 关键设施查找资源服务类:即查找给定弧段或节点的上游/下游中的关键设施结点,返回关键结点 ID 数组及其下游弧段 ID 数组。 * @extends NetworkAnalystServiceBase * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如: "http://localhost:8090/iserver/services/test/rest/networkanalyst/WaterNet@FacilityNet"; * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FacilityAnalystStreamService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FacilityAnalystStreamService"; } /** * @function FacilityAnalystStreamService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FacilityAnalystStreamService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FacilityAnalystStreamParameters} params - 上游/下游关键设施查找资源参数类。 */ processAsync(params) { if (!(params instanceof FacilityAnalystStreamParameters)) { return; } var me = this, jsonObject; //URL 通过参数类型来判断是 上游 还是下游 查询 if (params.queryType === 0) { me.url = Util.urlPathAppend(me.url, 'upstreamcirticalfaclilities'); } else if (params.queryType === 1) { me.url = Util.urlPathAppend(me.url, 'downstreamcirticalfaclilities'); } else { return; } jsonObject = { sourceNodeIDs: params.sourceNodeIDs, isUncertainDirectionValid: params.isUncertainDirectionValid }; if (params.edgeID !== null && params.nodeID !== null) { return; } if (params.edgeID === null && params.nodeID === null) { return; } if (params.edgeID !== null) { jsonObject.edgeID = params.edgeID; } else { jsonObject.nodeID = params.nodeID; } me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystTracedown3DParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystTracedown3DParameters * @deprecatedclass SuperMap.FacilityAnalystTracedown3DParameters * @category iServer FacilityAnalyst3D TraceDownResult * @classdesc 下游追踪资源参数类。 * @extends {FacilityAnalyst3DParameters} * @param {Object} options - 参数。 * @param {string} options.weightName - 指定的权值字段信息对象的名称。 * @param {number} [options.edgeID] - 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。 * @param {number} [options.nodeID] - 指定的结点 ID,edgeID 与 nodeID 必须指定一个。 * @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行; * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 * @usage */ class FacilityAnalystTracedown3DParameters extends FacilityAnalyst3DParameters { constructor(options) { super(options); this.CLASS_NAME = "SuperMap.FacilityAnalystTracedown3DParameters"; } /** * @function FacilityAnalystTracedown3DParameters.prototype.destroy * @override */ destroy() { super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystTracedown3DService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystTracedown3DService * @deprecatedclass SuperMap.FacilityAnalystTracedown3DService * @category iServer FacilityAnalyst3D TraceDownResult * @classdesc 下游追踪资源服务类 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FacilityAnalystTracedown3DService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FacilityAnalystTracedown3DService"; } /** * @function FacilityAnalystTracedown3DService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FacilityAnalystTracedown3DService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FacilityAnalystTracedown3DParameters} params - 下游追踪资源参数类。 */ processAsync(params) { if (!(params instanceof FacilityAnalystTracedown3DParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'tracedownresult'); jsonObject = { edgeID: params.edgeID, nodeID: params.nodeID, weightName: params.weightName, isUncertainDirectionValid: params.isUncertainDirectionValid }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystTraceup3DParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystTraceup3DParameters * @deprecatedclass SuperMap.FacilityAnalystTraceup3DParameters * @category iServer FacilityAnalyst3D TraceUpResult * @classdesc 上游追踪资源参数类。 * @extends {FacilityAnalyst3DParameters} * @param {Object} options - 参数。 * @param {string} options.weightName - 指定的权值字段信息对象的名称。 * @param {number} [options.edgeID] - 指定的弧段ID,edgeID 与 nodeID 必须指定一个。 * @param {number} [options.nodeID] - 指定的结点ID,edgeID 与 nodeID 必须指定一个。 * @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行; * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 * @usage */ class FacilityAnalystTraceup3DParameters extends FacilityAnalyst3DParameters { constructor(options) { super(options); this.CLASS_NAME = "SuperMap.FacilityAnalystTraceup3DParameters"; } /** * @function FacilityAnalystTraceup3DParameters.prototype.destroy * @override */ destroy() { super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystTraceup3DService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystTraceup3DService * @deprecatedclass SuperMap.FacilityAnalystTraceup3DService * @category iServer FacilityAnalyst3D TraceUpResult * @classdesc 上游追踪资源服务类 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FacilityAnalystTraceup3DService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FacilityAnalystTraceup3DService"; } /** * @function FacilityAnalystTraceup3DService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FacilityAnalystTraceup3DService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FacilityAnalystTraceup3DParameters} params - 上游追踪资源参数类 */ processAsync(params) { if (!(params instanceof FacilityAnalystTraceup3DParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'traceupresult'); jsonObject = { edgeID: params.edgeID, nodeID: params.nodeID, weightName: params.weightName, isUncertainDirectionValid: params.isUncertainDirectionValid }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystUpstream3DParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystUpstream3DParameters * @deprecatedclass SuperMap.FacilityAnalystUpstream3DParameters * @category iServer FacilityAnalyst3D UpstreamCirticalFaclilities * @classdesc 上游关键设施查找资源参数类。 * @extends {FacilityAnalyst3DParameters} * @param {Object} options - 参数。 * @param {Array.} options.sourceNodeIDs - 指定的设施点 ID 数组。 * @param {number} [options.edgeID] - 指定的弧段ID。edgeID 与 nodeID 必须指定一个。 * @param {number} [options.nodeID] - 指定的结点ID。edgeID 与 edgeID 必须指定一个。 * @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行; * 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。 * @usage */ class FacilityAnalystUpstream3DParameters extends FacilityAnalyst3DParameters { constructor(options) { super(options); options = options || {}; this.sourceNodeIDs = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.FacilityAnalystUpstream3DParameters"; } /** * @function FacilityAnalystUpstream3DParameters.prototype.destroy * @override */ destroy() { super.destroy(); this.sourceNodeIDs = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/FacilityAnalystUpstream3DService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FacilityAnalystUpstream3DService * @deprecatedclass SuperMap.FacilityAnalystUpstream3DService * @category iServer FacilityAnalyst3D UpstreamCirticalFaclilities * @classdesc 上游关键设施查找资源服务类 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FacilityAnalystUpstream3DService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FacilityAnalystUpstream3DService"; } /** * @function FacilityAnalystUpstream3DService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FacilityAnalystUpstream3DService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FacilityAnalystUpstream3DParameters} params - 上游关键设施查找资源参数类 */ processAsync(params) { if (!(params instanceof FacilityAnalystUpstream3DParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'upstreamcirticalfaclilities'); jsonObject = { sourceNodeIDs: params.sourceNodeIDs, edgeID: params.edgeID, nodeID: params.nodeID, isUncertainDirectionValid: params.isUncertainDirectionValid }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FieldParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FieldParameters * @deprecatedclass SuperMap.FieldParameters * @category iServer Data Field * @classdesc 字段信息查询参数类。 * @param {Object} options - 参数。 * @param {string} options.datasource - 数据源名称。 * @param {string} options.dataset - 数据集名称。 * @usage */ class FieldParameters { constructor(options) { /** * @member {string} FieldParameters.prototype.datasource * @description 要查询的数据集所在的数据源名称。 */ this.datasource = null; /** * @member {string} FieldParameters.prototype.dataset * @description 要查询的数据集名称。 */ this.dataset = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.FieldParameters"; } /** * @function FieldParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.datasource = null; me.dataset = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/FieldStatisticsParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FieldStatisticsParameters * @deprecatedclass SuperMap.FieldStatisticsParameters * @category iServer Data Field * @classdesc 字段统计信息查询参数类。 * @param {Object} options - 参数。 * @param {string} options.datasource - 数据源名称。 * @param {string} options.dataset - 数据集名称。 * @param {string} options.fieldName - 字段名。 * @param {(string.|Array.>)} statisticMode - 字段统计方法类型。 * @extends {FieldParameters} * @usage */ class FieldStatisticsParameters extends FieldParameters { constructor(options) { super(options); /** * @member {string} FieldStatisticsParameters.prototype.fieldName * @description 字段名。 */ this.fieldName = null; /** * @member {(string.|Array.>)} FieldStatisticsParameters.prototype.statisticMode * @description 字段统计方法类型。 */ this.statisticMode = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.FieldStatisticsParameters"; } /** * @function FieldStatisticsParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.fieldName = null; me.statisticMode = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/FieldStatisticService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FieldStatisticService * @deprecatedclass SuperMap.FieldStatisticService * @category iServer Data Field * @classdesc 字段查询统计服务类。用来完成对指定数据集指定字段的查询统计分析,即求平均值,最大值等。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。如访问 World Map 服务,只需将 url 设为:http://localhost:8090/iserver/services/data-world/rest/data 即可。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format] - 查询结果返回格式,目前支持 iServerJSON 和GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {string} options.datasource - 数据集所在的数据源名称。 * @param {string} options.dataset - 数据集名称。 * @param {string} options.field - 查询统计的目标字段名称。 * @param {StatisticMode} options.statisticMode - 字段查询统计的方法类型。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * var myService = new FieldStatisticService(url, {eventListeners: { * "processCompleted": fieldStatisticCompleted, * "processFailed": fieldStatisticError * }, * datasource: "World", * dataset: "Countries", * field: "SmID", * statisticMode: StatisticMode.AVERAGE * }; * @usage */ class FieldStatisticService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {string} FieldStatisticService.prototype.datasource * @description 数据集所在的数据源名称。 */ this.datasource = null; /** * @member {string} FieldStatisticService.prototype.dataset * @description 数据集名称。 */ this.dataset = null; /** * @member {string} FieldStatisticService.prototype.field * @description 查询统计的目标字段名称。 */ this.field = null; /** * @member {StatisticMode} FieldStatisticService.prototype.statisticMode * @description 字段查询统计的方法类型。 */ this.statisticMode = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.FieldStatisticService"; } /** * @function FieldStatisticService.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.datasource = null; me.dataset = null; me.field = null; me.statisticMode = null; } /** * @function FieldStatisticService.prototype.processAsync * @description 执行服务,进行指定字段的查询统计。 */ processAsync() { var me = this, fieldStatisticURL = "datasources/" + me.datasource + "/datasets/" + me.dataset + "/fields/" + me.field + "/" + me.statisticMode; me.url = Util.urlPathAppend(me.url, fieldStatisticURL); me.request({ method: "GET", data: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FindClosestFacilitiesParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindClosestFacilitiesParameters * @deprecatedclass SuperMap.FindClosestFacilitiesParameters * @category iServer NetworkAnalyst ClosestFacility * @classdesc 最近设施分析参数类。 * @param {Object} options - 参数。 * @param {GeometryPoint|L.LatLng|L.Point|ol.geom.Point|mapboxgl.LngLat|mapboxgl.Point|Array.} options.event - 事件点,一般为需要获得服务设施服务的事件位置。 * @param {Array.>} options.facilities - 设施点集合,一般为提供服务的服务设施位置。 * @param {number} [options.expectFacilityCount=1] - 要查找的设施点数量。 * @param {boolean} [options.fromEvent=false] - 是否从事件点到设施点进行查找。 * @param {boolean} [options.isAnalyzeById=false] - 事件点和设施点是否通过节点 ID 号来指定。 * @param {number} [options.maxWeight=0] - 权值的最大限值。单位与该类中 parameter 字段(交通网络分析通用参数)中设置的耗费字段一致。 * @param {TransportationAnalystParameter} [options.parameter] - 交通网络分析通用参数。 * @usage */ class FindClosestFacilitiesParameters { constructor(options) { /** * @member {GeometryPoint|L.LatLng|L.Point|ol.geom.Point|mapboxgl.LngLat|mapboxgl.Point|Array.} FindClosestFacilitiesParameters.prototype.event * @description 事件点,一般为需要获得服务设施服务的事件位置。 * 可以通过两种方式赋予事件点:当该类中字段 isAnalyzeById = true 时,应输入事件点 ID 号;当 isAnalyzeById = false 时,应输入事件点坐标。 */ this.event = null; /** * @member {number} [FindClosestFacilitiesParameters.prototype.expectFacilityCount=1] * @description 要查找的设施点数量。 */ this.expectFacilityCount = 1; /** * @member {Array.>} [FindClosestFacilitiesParameters.prototype.facilities=false] * @description 设施点集合,一般为提供服务的服务设施位置。 * 可以通过两种方式赋予设施点:当该类中字段 isAnalyzeById = true 时,应输入设施点 ID 号;当 isAnalyzeById = false 时,应输入设施点坐标。 */ this.facilities = null; /** * @member {boolean} [FindClosestFacilitiesParameters.prototype.fromEvent=false] * @description 是否从事件点到设施点进行查找。最近设施分析主要是通过设施点和事件点之间最优的路线来分析在一定范围内哪个或哪些设施与事件点有最优路线的关系。 * 这个行走线路是通过网络图层进行网络分析算法计算出来的两点间的最优路线。由于存在从 A 点到 B 点与从 B 点到 A 点的耗费不一样的情况,因此起止点不同可能会得到不同的最优路线。因此在进行最近设施分析之前,需要设置获取的最优路线的方向,即是以事件点作为起点到最近设施点的方向分析,还是以最近设施点为起点到事件点的方向分析。如果需要以事件点作为起点到设施点方向进行查找,设置该字段值为 true;设置为 false,表示从设施点到事件点进行查找。 */ this.fromEvent = false; /** * @member {boolean} [FindClosestFacilitiesParameters.prototype.isAnalyzeById=false] * @description 事件点和设施点是否通过节点 ID 号来指定,设置为 false,表示通过坐标点指定事件点和设施点。 */ this.isAnalyzeById = false; /** * @member {number} [FindClosestFacilitiesParameters.prototype.maxWeight=0] * @description 权值的最大限值。单位与该类中 parameter 字段(交通网络分析通用参数)中设置的耗费字段一致。 * 例如事件发生点是一起交通事故,要求查找在 10 分钟内能到达的最近医院,超过 10 分钟能到达的都不予考虑。 * 那么需要将网络分析参数中 parameter.weightFieldName 设置为表示时间的字段,然后设置查找范围的半径值为10。 */ this.maxWeight = 0; /** * @member {TransportationAnalystParameter} [FindClosestFacilitiesParameters.prototype.parameter] * @description 交通网络分析通用参数。通过本类可以设置障碍边、障碍点、权值字段信息的名称标识、转向权值字段等信息。 * 它为 TransportationAnalystParameter 类型,虽然为可选参数,但是如果不设置其中的 resultSetting 字段, * 则返回结果空间信息等都为空。 */ this.parameter = new TransportationAnalystParameter(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.FindClosestFacilitiesParameters"; } /** * @function FindClosestFacilitiesParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.event = null; me.expectFacilityCount = null; me.facilities = null; me.fromEvent = null; me.isAnalyzeById = null; me.maxWeight = null; if (me.parameter) { me.parameter.destroy(); me.parameter = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/FindClosestFacilitiesService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindClosestFacilitiesService * @deprecatedclass SuperMap.FindClosestFacilitiesService * @category iServer NetworkAnalyst ClosestFacility * @classdesc 最近设施分析服务类。 * 最近设施分析是指在网络上给定一个事件点和一组设施点, * 查找从事件点到设施点(或从设施点到事件点)以最小耗费能到达的最佳路径。 * 该类负责将客户端指定的最近设施分析参数传递给服务端,并接收服务端返回的结果数据。 * 最近设施分析结果通过该类支持的事件的监听函数参数获取 * @extends {NetworkAnalystServiceBase} * @example * var myfindClosestFacilitiesService = new FindClosestFacilitiesService(url, { * eventListeners: { * "processCompleted": findClosestFacilitiesCompleted, * "processFailed": findClosestFacilitiesError * } * }); * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FindClosestFacilitiesService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FindClosestFacilitiesService"; } /** * @function FindClosestFacilitiesService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FindClosestFacilitiesService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FindClosestFacilitiesParameters} params - 最近设施分析服务参数类 */ processAsync(params) { if (!(params instanceof FindClosestFacilitiesParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'closestfacility'); jsonObject = { expectFacilityCount: params.expectFacilityCount, fromEvent: params.fromEvent, maxWeight: params.maxWeight, parameter: Util.toJSON(params.parameter), event: Util.toJSON(params.event), facilities: me.getJson(params.isAnalyzeById, params.facilities) }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function FindClosestFacilitiesService.prototype.getJson * @description 将对象转化为JSON字符串。 * @param {boolean} isAnalyzeById - 是否通过ID来分析 * @param {Array.} params - 分析参数数组 * @returns {Object} 转化后的JSON字符串。 */ getJson(isAnalyzeById, params) { var jsonString = "[", len = params ? params.length : 0; if (isAnalyzeById === false) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += '{"x":' + params[i].x + ',"y":' + params[i].y + '}'; } } else if (isAnalyzeById === true) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += params[i]; } } jsonString += ']'; return jsonString; } /** * @function FindClosestFacilitiesService.prototype.toGeoJSONResult * @description 将含有 geometry 的数据转换为 GeoJSON 格式。 * @param {Object} result - 服务器返回的结果对象。 */ toGeoJSONResult(result) { if (!result || !result.facilityPathList) { return result; } var geoJSONFormat = new GeoJSON(); result.facilityPathList.map(function (path) { if (path.route) { path.route = geoJSONFormat.toGeoJSON(path.route); } if (path.pathGuideItems) { path.pathGuideItems = geoJSONFormat.toGeoJSON(path.pathGuideItems); } if (path.edgeFeatures) { path.edgeFeatures = geoJSONFormat.toGeoJSON(path.edgeFeatures); } if (path.nodeFeatures) { path.nodeFeatures = geoJSONFormat.toGeoJSON(path.nodeFeatures); } return path; }); return result; } } ;// CONCATENATED MODULE: ./src/common/iServer/FindLocationParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindLocationParameters * @deprecatedclass SuperMap.FindLocationParameters * @category iServer NetworkAnalyst Location * @classdesc 选址分区分析参数类。 * @param {Object} options - 参数。 * @param {string} options.turnWeightField - 转向权值字段的名称。 * @param {string} options.weightName - 阻力字段的名称,标识了进行网络分析时所使用的阻力字段。 * @param {Array.} options.supplyCenters - 资源供给中心集合。 * @param {number} [options.expectedSupplyCenterCount=1] - 期望用于最终设施选址的资源供给中心数量。 * @param {boolean} [options.isFromCenter=false] - 是否从中心点开始分配资源。 * @usage */ class FindLocationParameters { constructor(options) { /** * @member {number} [FindLocationParameters.prototype.expectedSupplyCenterCount=1] * @description 期望用于最终设施选址的资源供给中心数量。 * 当输入值为 0 时,最终设施选址的资源供给中心数量默认为覆盖分析区域内的所需最少的供给中心数。 */ this.expectedSupplyCenterCount = null; /** * @member {boolean} [FindLocationParameters.prototype.isFromCenter=false] * @description 是否从中心点开始分配资源。 * 由于网路数据中的弧段具有正反阻力,即弧段的正向阻力值与其反向阻力值可能不同, * 因此,在进行分析时,从资源供给中心开始分配资源到需求点与从需求点向资源供给中心分配这两种分配形式下,所得的分析结果会不同。 */ this.isFromCenter = false; /** * @member {Array.} FindLocationParameters.prototype.supplyCenters * @description 资源供给中心集合。 * 资源供给中心是提供资源和服务的设施,对应于网络结点, * 资源供给中心的相关信息包括资源量、最大阻力值、资源供给中心类型,资源供给中心在网络中所处结点的 ID 等,以便在进行选址分区分析时使用。 */ this.supplyCenters = null; /** * @member {string} FindLocationParameters.prototype.turnWeightField * @description 转向权值字段的名称。 */ this.turnWeightField = null; /** * @member {string} FindLocationParameters.prototype.weightName * @description 阻力字段的名称,标识了进行网络分析时所使用的阻力字段。 */ this.weightName = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.FindLocationParameters"; } /** * @function FindLocationParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.expectedSupplyCenterCount = null; me.isFromCenter = null; me.turnWeightField = null; me.weightName = null; if (me.supplyCenters) { for (var i = 0, supplyCenters = me.supplyCenters, len = supplyCenters.length; i < len; i++) { supplyCenters[i].destroy(); } me.supplyCenters = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/FindLocationService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindLocationService * @deprecatedclass SuperMap.FindLocationService * @category iServer NetworkAnalyst Location * @classdesc 选址分区分析服务类。 * 选址分区分析是为了确定一个或多个待建设施的最佳或最优位置,使得设施可以用一种最经济有效的方式为需求方提供服务或者商品。 * 选址分区不仅仅是一个选址过程,还要将需求点的需求分配到相应的新建设施的服务区中,因此称之为选址与分区。 * 选址分区分析结果通过该类支持的事件的监听函数参数获取 * @extends {NetworkAnalystServiceBase} * @example * (start code) * var findLocationService = new FindLocationService(url, { * eventListeners: { * "processCompleted": findLocationCompleted, * "processFailed": findLocationError * } * }); * (end) * @param {string} url - 服务地址。 * 如 http://localhost:8090/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun 。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FindLocationService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FindLocationService"; } /** * @function FindLocationService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FindLocationService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FindLocationParameters} params - 选址分区分析服务参数类 */ processAsync(params) { if (!(params instanceof FindLocationParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'location'); jsonObject = { isFromCenter: params.isFromCenter, expectedSupplyCenterCount: params.expectedSupplyCenterCount, weightName: params.weightName, turnWeightField: params.turnWeightField, returnEdgeFeature: true, returnEdgeGeometry: true, returnNodeFeature: true, mapParameter: Util.toJSON(params.mapParameter), supplyCenters: me.getCentersJson(params.supplyCenters) }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function FindLocationService.prototype.getCentersJson * @description 将数组对象转化为JSON字符串。 * @param {Array} params - 需要转换的参数 * @returns {string} 转化后的JSON字符串。 */ getCentersJson(params) { var json = "[", len = params ? params.length : 0; for (var i = 0; i < len; i++) { if (i > 0) { json += ","; } json += Util.toJSON(params[i]); } json += "]"; return json; } /** * @function FindLocationService.prototype.toGeoJSONResult * @description 将含有 geometry 的数据转换为 GeoJSON 格式。 * @param {Object} result - 服务器返回的结果对象。 */ toGeoJSONResult(result) { if (!result) { return null; } var geoJSONFormat = new GeoJSON(); if (result.demandResults) { result.demandResults = geoJSONFormat.toGeoJSON(result.demandResults); } if (result.supplyResults) { result.supplyResults = geoJSONFormat.toGeoJSON(result.supplyResults); } return result; } } ;// CONCATENATED MODULE: ./src/common/iServer/FindMTSPPathsParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindMTSPPathsParameters * @deprecatedclass SuperMap.FindMTSPPathsParameters * @category iServer NetworkAnalyst MTSPPath * @classdesc 多旅行商分析参数类。 * @param {Object} options - 参数。 * @param {Array.>} options.centers - 配送中心集合。 * @param {Array.>} options.nodes - 配送目标集合。 * @param {boolean} [options.hasLeastTotalCost=false] - 配送模式是否为总花费最小方案。 * @param {boolean} [options.isAnalyzeById=false] - 是否通过节点 ID 号来指定配送中心点和配送目的点,即通过坐标点指定。 * @param {TransportationAnalystParameter} [options.parameter] - 交通网络分析通用参数。 * @usage */ class FindMTSPPathsParameters { constructor(options) { /** * @member {Array.>} FindMTSPPathsParameters.prototype.centers * @description 配送中心集合。 * 当 FindMTSPPathsParameters.isAnalyzeById = false 时,centers 应为点的坐标数组; * 当 FindMTSPPathsParameters.isAnalyzeById = true 时,centers 应为点的 ID 数组。 */ this.centers = null; /** * @member {boolean} [FindMTSPPathsParameters.prototype.hasLeastTotalCost=false] * @description 配送模式是否为总花费最小方案。 * 若为 true,则按照总花费最小的模式进行配送,此时可能会出现某几个配送中心点配送的花费较多而其他配送中心点的花费很少的情况。 * 若为 false,则为局部最优,此方案会控制每个配送中心点的花费,使各个中心点花费相对平均,此时总花费不一定最小。 */ this.hasLeastTotalCost = false; /** * @member {boolean} [FindMTSPPathsParameters.prototype.isAnalyzeById=false] * @description 是否通过节点 ID 号来指定配送中心点和配送目的点,即通过坐标点指定。 */ this.isAnalyzeById = false; /** * @member {Array.>} FindMTSPPathsParameters.prototype.nodes * @description 配送目标集合。 * 当 FindMTSPPathsParameters.isAnalyzeById = false 时,nodes 应为点的坐标数组; * 当 FindMTSPPathsParameters.isAnalyzeById = true 时,nodes 应为点的 ID 数组。 */ this.nodes = null; /** * @member {TransportationAnalystParameter} [FindMTSPPathsParameters.prototype.parameter] * @description 交通网络分析通用参数。 * 通过本类可以设置障碍边、障碍点、权值字段信息的名称标识、转向权值字段等信息。 * TransportationAnalystParameter 类型,它虽然为可选参数,但是如果不设置其中的 resultSetting 字段,则返回结果空间信息等都为空。 */ this.parameter = new TransportationAnalystParameter(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.FindMTSPPathsParameters"; } /** * @function FindMTSPPathsParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.centers = null; me.hasLeastTotalCost = null; me.isAnalyzeById = null; me.nodes = null; me.maxWeight = null; if (me.parameter) { me.parameter.destroy(); me.parameter = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/FindMTSPPathsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindMTSPPathsService * @deprecatedclass SuperMap.FindMTSPPathsService * @category iServer NetworkAnalyst MTSPPath * @classdesc 多旅行商分析服务类 * 多旅行商分析也称为物流配送,是指在网络数据集中,给定 M 个配送中心点和 N 个配送目的地(M,N 为大于零的整数)。 * 查找经济有效的配送路径,并给出相应的行走路线。 * 物流配送功能就是解决如何合理分配配送次序和送货路线,使配送总花费达到最小或每个配送中心的花费达到最小。 * 该类负责将客户端指定的多旅行商分析参数传递给服务端,并接收服务端返回的结果数据。 * 多旅行商分析结果通过该类支持的事件的监听函数参数获取。 * @extends {NetworkAnalystServiceBase} * @example * var myFindMTSPPathsService = new FindMTSPPathsService(url, { * eventListeners: { * "processCompleted": findMTSPPathsCompleted, * "processFailed": findMTSPPathsError * } * }); * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 互服务时所需可选参数。如: * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FindMTSPPathsService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FindMTSPPathsService"; } /** * @function FindMTSPPathsService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FindMTSPPathsService..prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FindMTSPPathsParameters} params - 多旅行商分析服务参数类 */ processAsync(params) { if (!(params instanceof FindMTSPPathsParameters)) { return; } var me = this, jsonObject, //end = me.url.substr(me.url.length - 1, 1), centers = me.getJson(params.isAnalyzeById, params.centers), nodes = me.getJson(params.isAnalyzeById, params.nodes); me.url = Util.urlPathAppend(me.url, 'mtsppath'); jsonObject = { centers: centers, nodes: nodes, parameter: Util.toJSON(params.parameter), hasLeastTotalCost: params.hasLeastTotalCost }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function FindMTSPPathsService.prototype.getJson * @description 将对象转化为JSON字符串。 * @param {boolean} isAnalyzeById - 是否通过id分析 * @param {Array} params - 需要转换的数字 * @returns {Object} 转化后的JSON字符串。 */ getJson(isAnalyzeById, params) { var jsonString = "[", len = params ? params.length : 0; if (isAnalyzeById === false) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += '{"x":' + params[i].x + ',"y":' + params[i].y + '}'; } } else if (isAnalyzeById === true) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += params[i]; } } jsonString += ']'; return jsonString; } /** * @function FindMTSPPathsService.prototype.toGeoJSONResult * @description 将含有 geometry 的数据转换为 GeoJSON 格式。 * @param {Object} result - 服务器返回的结果对象。 */ toGeoJSONResult(result) { if (!result || !result.pathList) { return null; } var geoJSONFormat = new GeoJSON(); result.pathList.map(function (path) { if (path.route) { path.route = geoJSONFormat.toGeoJSON(path.route); } if (path.pathGuideItems) { path.pathGuideItems = geoJSONFormat.toGeoJSON(path.pathGuideItems); } if (path.edgeFeatures) { path.edgeFeatures = geoJSONFormat.toGeoJSON(path.edgeFeatures); } if (path.nodeFeatures) { path.nodeFeatures = geoJSONFormat.toGeoJSON(path.nodeFeatures); } return path; }); return result; } } ;// CONCATENATED MODULE: ./src/common/iServer/FindPathParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindPathParameters * @deprecatedclass SuperMap.FindPathParameters * @category iServer NetworkAnalyst Path * @classdesc 最佳路径分析参数类。最佳路径是在网络数据集中指定一些结点,按照顺序访问结点从而求解起止点之间阻抗最小的路径。 * 例如如果要顺序访问 1、2、3、4 四个结点,则需要分别找到1、2结点间的最佳路径 R1—2,2、3 间的最佳路径 R2—3 和 3、4 结点间的最佳路径 R3—4, * 顺序访问 1、2、3、4 四个结点的最佳路径就是 R = R1—2 + R2—3 + R3—4。 * 阻抗就是指从一点到另一点的耗费,在实际应用中我们可以将距离、时间、花费等作为阻抗条件。 * 阻抗最小也就可以理解为从一点到另一点距离最短、时间最少、花费最低等。当两点间距离最短时为最短路径,它是最佳路径问题的一个特例。 * 阻抗值通过 {@link TransportationAnalystParameter#weightFieldName}设置。 * 计算最佳路径除了受阻抗影响外,还受转向字段的影响。转向值通过 {@link TransportationAnalystParameter#turnWeightField} 设置。 * * @param {Object} options - 参数。 * @param {Array.>} options.nodes - 最佳路径分析经过的结点或设施点数组。该字段至少包含两个点。 * @param {boolean} [options.isAnalyzeById=false] - 是否通过节点 ID 指定路径分析的结点。 * @param {boolean} [options.hasLeastEdgeCount=false] - 是否按照弧段数最少的进行最佳路径分析。 * @param {TransportationAnalystParameter} [options.parameter] - 交通网络分析通用参数。 * @usage */ class FindPathParameters { constructor(options) { /** * @member {boolean} [FindPathParameters.prototype.isAnalyzeById=false] * @description 是否通过节点 ID 指定路径分析的结点。 * 指定路径分析经过的结点或设施点有两种方式:输入结点 ID 号或直接输入点坐标。 * 当该字段为 true 时,表示通过结点 ID 指定途经点,即 FindPathParameters.nodes = [ID1,ID2,...]; * 反之表示通过结点坐标指定途经点,即 FindPathParameters.nodes = [{x1,y1},{x2,y2},...] 。 */ this.isAnalyzeById = false; /** * @member {boolean} [FindPathParameters.prototype.hasLeastEdgeCount=false] * @description 是否按照弧段数最少的进行最佳路径分析。 * true 表示按照弧段数最少进行分析,返回弧段数最少的路径中一个阻抗最小的最佳路径; * false 表示直接返回阻抗最小的路径,而不考虑弧段的多少。 */ this.hasLeastEdgeCount = null; /** * @member {Array.>} FindPathParameters.prototype.nodes * @description 最佳路径分析经过的结点或设施点数组,必设字段。该字段至少包含两个点。 * 当 FindPathParameters.isAnalyzeById = false 时,nodes 应为点的坐标数组; * 当 FindPathParameters.isAnalyzeById = true 时,nodes 应为点的 ID 数组。 */ this.nodes = null; /** * @member {TransportationAnalystParameter} FindPathParameters.prototype.parameter * @description 交通网络分析通用参数。 */ this.parameter = new TransportationAnalystParameter(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.FindPathParameters"; } /** * @function FindPathParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.isAnalyzeById = null; me.hasLeastEdgeCount = null; me.nodes = null; if (me.parameter) { me.parameter.destroy(); me.parameter = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/FindPathService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindPathService * @deprecatedclass SuperMap.FindPathService * @category iServer NetworkAnalyst Path * @classdesc 最佳路径分析服务类。 * 最佳路径是在网络数据集中指定一些节点,按照节点的选择顺序, * 顺序访问这些节点从而求解起止点之间阻抗最小的路经。 * 该类负责将客户端指定的最佳路径分析参数传递给服务端,并接收服务端返回的结果数据。 * 最佳路径分析结果通过该类支持的事件的监听函数参数获取 * @extends {NetworkAnalystServiceBase} * @example * var myFindPathService = new FindPathService(url, { * eventListeners: { * "processCompleted": findPathCompleted, * "processFailed": findPathError * } * }); * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FindPathService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FindPathService"; } /** * @function FindPathService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FindPathService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FindPathParameters} params - 最佳路径分析服务参数类 */ processAsync(params) { if (!(params instanceof FindPathParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'path'); jsonObject = { hasLeastEdgeCount: params.hasLeastEdgeCount, parameter: Util.toJSON(params.parameter), nodes: me.getJson(params.isAnalyzeById, params.nodes) }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function FindPathService.prototype.getJson * @description 将对象转化为JSON字符串。 * @param {boolean} isAnalyzeById - 是否通过id分析 * @param {Array} params - 需要转换的数字 * @returns {Object} 转化后的JSON字符串。 */ getJson(isAnalyzeById, params) { var jsonString = "[", len = params ? params.length : 0; if (isAnalyzeById === false) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += '{"x":' + params[i].x + ',"y":' + params[i].y + '}'; } } else if (isAnalyzeById === true) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += params[i]; } } jsonString += ']'; return jsonString; } /** * @function FindMTSPPathsService.prototype.toGeoJSONResult * @description 将含有 geometry 的数据转换为 GeoJSON 格式。 * @param {Object} result - 服务器返回的结果对象。 */ toGeoJSONResult(result) { if (!result || !result.pathList || result.pathList.length < 1) { return null; } var geoJSONFormat = new GeoJSON(); result.pathList.forEach(function (path) { if (path.route) { path.route = geoJSONFormat.toGeoJSON(path.route); } if (path.pathGuideItems) { path.pathGuideItems = geoJSONFormat.toGeoJSON(path.pathGuideItems); } if (path.edgeFeatures) { path.edgeFeatures = geoJSONFormat.toGeoJSON(path.edgeFeatures); } if (path.nodeFeatures) { path.nodeFeatures = geoJSONFormat.toGeoJSON(path.nodeFeatures); } }); return result; } } ;// CONCATENATED MODULE: ./src/common/iServer/FindServiceAreasParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindServiceAreasParameters * @deprecatedclass SuperMap.FindServiceAreasParameters * @category iServer NetworkAnalyst ServiceArea * @classdesc 服务区分析参数类。 * 服务区分析是以指定服务站点为中心,在一定服务范围内查找网络上服务站点能够提供服务的区域范围。 * 例如:计算某快餐店能够在30分钟内送达快餐的区域。 * @param {Object} options - 参数。 * @param {Array.} options.weights - 每个服务站点提供服务的阻力半径,超过这个阻力半径的区域不予考虑,其单位与阻力字段一致。 * @param {Array.>} options.centers - 服务站点数组。 * @param {boolean} [options.isAnalyzeById=false] - 是否通过节点 ID 指定路径分析的结点。 * @param {boolean} [options.isCenterMutuallyExclusive=false] - 是否中心点互斥。 * @param {boolean} [options.isFromCenter=false] - 是否从中心点开始分析。 * @param {TransportationAnalystParameter} [options.parameter] - 交通网络分析通用参数。 * @usage */ class FindServiceAreasParameters { constructor(options) { /** * @member {boolean} [FindServiceAreasParameters.prototype.isAnalyzeById=false] * @description 是否通过节点 ID 指定路径分析的结点。 * 指定路径分析经过的结点或设施点有两种方式:输入结点 ID 号或直接输入点坐标。 * 当该字段为 true 时,表示通过结点 ID 指定途经点,即 FindServiceAreasParameters.centers = [ID1,ID2,...]; * 反之表示通过结点坐标指定途经点,即 FindServiceAreasParameters.centers = [{x1,y1},{x2,y2},...]。 */ this.isAnalyzeById = false; /** * @member {boolean} [FindServiceAreasParameters.prototype.isCenterMutuallyExclusive=false] * @description 是否中心点互斥,即按照中心点的距离进行判断是否要进行互斥处理。 * 若分析出的服务区有重叠的部分,则通过设置该参数进行互斥处理。 */ this.isCenterMutuallyExclusive = false; /** * @member {Array.>} FindServiceAreasParameters.prototype.centers * @description 服务站点数组。 * 当该类的 iSAnalyzeById = true 时,通过结点 ID 号指定服务站点;当 iSAnalyzeById = false 时,通过点坐标指定服务站点。 */ this.centers = null; /** * @member {boolean} [FindServiceAreasParameters.prototype.isFromCenter=false] * @description 是否从中心点开始分析。 * 从中心点开始分析和不从中心点开始分析,体现了服务中心和需要该服务的需求地的关系模式。 * 从中心点开始分析,是一个服务中心向服务需求地提供服务; * 而不从中心点开始分析,是一个服务需求地主动到服务中心获得服务。 */ this.isFromCenter = false; /** * APIProperty: weights * @member {Array.} FindServiceAreasParameters.prototype.weights * @description 每个服务站点提供服务的阻力半径,即超过这个阻力半径的区域不予考虑,其单位与阻力字段一致。 * 该字段为一个数组,数组长度跟服务中心个数一致,按照索引顺序与站点一一对应,每个元素表示了在对每个服务中心进行服务区分析时,所用的服务半径。 */ this.weights = null; /** * @member {TransportationAnalystParameter} FindServiceAreasParameters.prototype.parameter * @description 交通网络分析通用参数。 */ this.parameter = new TransportationAnalystParameter(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.FindServiceAreasParameters"; } /** * @function FindServiceAreasParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.isAnalyzeById = null; me.isCenterMutuallyExclusive = null; me.centers = null; me.isFromCenter = null; me.weights = null; if (me.parameter) { me.parameter.destroy(); me.parameter = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/FindServiceAreasService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindServiceAreasService * @deprecatedclass SuperMap.FindServiceAreasService * @category iServer NetworkAnalyst ServiceArea * @classdesc 服务区分析服务类。 * 服务区分析是以指定服务站点为中心, * 在一定服务范围内查找网络上服务站点能够提供服务的区域范围。 * 该类负责将客户端指定的服务区分析参数传递给服务端,并接收服务端返回的结果数据。 * 服务区分析结果通过该类支持的事件的监听函数参数获取 * @extends {NetworkAnalystServiceBase} * @example * var myFindServiceAreasService = new FindServiceAreasService(url, { * eventListeners: { * "processCompleted": findServiceAreasCompleted, * "processFailed": findServiceAreasError * } * }); * @param {string} url - 服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 互服务时所需可选参数。如: * @param {Object} options.eventListeners - 需要被注册的监听器对象 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FindServiceAreasService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FindServiceAreasService"; } /** * @function FindServiceAreasService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FindServiceAreasService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FindServiceAreasParameters} params - 服务区分析服务参数类 */ processAsync(params) { if (!(params instanceof FindServiceAreasParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'servicearea'); jsonObject = { isFromCenter: params.isFromCenter, isCenterMutuallyExclusive: params.isCenterMutuallyExclusive, parameter: Util.toJSON(params.parameter), centers: me.getJson(params.isAnalyzeById, params.centers), weights: me.getJson(true, params.weights) }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function FindServiceAreasService.prototype.getJson * @description 将对象转化为JSON字符串。 * @param {boolean} isAnalyzeById - 是否通过id分析 * @param {Array} params - 需要转换的数字 * @returns {Object} 转化后的JSON字符串。 */ getJson(isAnalyzeById, params) { var jsonString = "[", len = params ? params.length : 0; if (isAnalyzeById === false) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += '{"x":' + params[i].x + ',"y":' + params[i].y + '}'; } } else if (isAnalyzeById === true) { for (let i = 0; i < len; i++) { if (i > 0) { jsonString += ","; } jsonString += params[i]; } } jsonString += ']'; return jsonString; } /** * @function FindServiceAreasService.prototype.toGeoJSONResult * @description 将含有 geometry 的数据转换为 GeoJSON 格式。 * @param {Object} result - 服务器返回的结果对象。 */ toGeoJSONResult(result) { if (!result || !result.serviceAreaList) { return result; } var geoJSONFormat = new GeoJSON(); result.serviceAreaList.map(function (serviceArea) { if (serviceArea.serviceRegion) { serviceArea.serviceRegion = geoJSONFormat.toGeoJSON(serviceArea.serviceRegion); } if (serviceArea.edgeFeatures) { serviceArea.edgeFeatures = geoJSONFormat.toGeoJSON(serviceArea.edgeFeatures); } if (serviceArea.nodeFeatures) { serviceArea.nodeFeatures = geoJSONFormat.toGeoJSON(serviceArea.nodeFeatures); } if (serviceArea.routes) { serviceArea.routes = geoJSONFormat.toGeoJSON(serviceArea.routes); } return serviceArea; }); return result; } } ;// CONCATENATED MODULE: ./src/common/iServer/FindTSPPathsParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindTSPPathsParameters * @deprecatedclass SuperMap.FindTSPPathsParameters * @category iServer NetworkAnalyst TSPPath * @classdesc 旅行商分析参数类。 * 旅行商分析是路径分析的一种,它从起点开始(默认为用户指定的第一点)查找能够遍历所有途经点且花费最小的路径。 * 旅行商分析也可以指定到达的终点,这时查找从起点能够遍历所有途经点最后到达终点,且花费最小的路径。 * 旅行商分析和最佳路径分析都是在网络中寻找遍历所有站点的最经济的路径,区别是在遍历网络所有站点的过程中对结点访问顺序不同。 * 最佳路径分析必须按照指定顺序对站点进行访问,而旅行商分析是无序的路径分析。 * @param {Object} options - 参数。 * @param {boolean} [options.endNodeAssigned=false] - 是否指定终止点,将指定的途经点的最后一个点作为终止点。true 表示指定终止点,则旅行商必须最后一个访问终止点。 * @param {boolean} [options.isAnalyzeById=false] - 是否通过节点 ID 号来指定配送中心点和配送目的点。 * @param {Array.>} options.nodes - 配送目标集合。 * @param {TransportationAnalystParameter} [options.parameter] - 交通网络分析通用参数。 * @usage */ class FindTSPPathsParameters { constructor(options) { /** * @member {boolean} [FindTSPPathsParameters.prototype.endNodeAssigned=false] * @description 是否指定终止点,将指定的途经点的最后一个点作为终止点。 * true 表示指定终止点,则旅行商必须最后一个访问终止点。 */ this.endNodeAssigned = false; /** * @member {boolean} [FindTSPPathsParameters.prototype.isAnalyzeById=false] * @description 是否通过节点 ID 号来指定途经点。 */ this.isAnalyzeById = false; /** * @member {Array.>} FindTSPPathsParameters.prototype.nodes * @description 旅行商分析途经点数组。 * 当 FindTSPPathsParameters.isAnalyzeById = false 时,nodes 应为点的坐标数组; * 当 FindTSPPathsParameters.isAnalyzeById = true 时,nodes 应为点的 ID 数组。 */ this.nodes = null; /** * @member {TransportationAnalystParameter} [FindTSPPathsParameters.prototype.parameter] * @description 交通网络分析通用参数。通过本类可以设置障碍边、障碍点、权值字段信息的名称标识、转向权值字段等信息。 * TransportationAnalystParameter 类型,它虽然为可选参数,但是如果不设置其中的 resultSetting * 字段,则返回结果空间信息等都为空。 */ this.parameter = new TransportationAnalystParameter(); Util.extend(this, options); this.CLASS_NAME = "SuperMap.FindTSPPathsParameters"; } /** * @function FindTSPPathsParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.endNodeAssigned = null; me.isAnalyzeById = null; me.nodes = null; if (me.parameter) { me.parameter.destroy(); me.parameter = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/FindTSPPathsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FindTSPPathsService * @deprecatedclass SuperMap.FindTSPPathsService * @category iServer NetworkAnalyst TSPPath * @classdesc 旅行商分析服务类 * 旅行商分析是路径分析的一种,它从起点开始(默认为用户指定的第一点)查找能够遍历所有途经点且花费最小的路径。 * 旅行商分析也可以指定到达的终点,这时查找从起点能够遍历所有途经点最后到达终点,且花费最小的路径。 * 该类负责将客户端指定的旅行商分析参数传递给服务端,并接收服务端返回的结果数据。 * 旅行商分析结果通过该类支持的事件的监听函数参数获取 * @extends {NetworkAnalystServiceBase} * @example * (start code) * var myFindTSPPathsService = new FindTSPPathsService(url, { * eventListeners: { * "processCompleted": findTSPPathsCompleted, * "processFailed": findTSPPathsError * } * }); * (end) * @param {string} url - 网络分析服务地址。请求网络分析服务,URL应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class FindTSPPathsService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.FindTSPPathsService"; } /** * @function FindTSPPathsService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FindTSPPathsService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {FindTSPPathsParameters} params - 旅行商分析服务参数类。 */ processAsync(params) { if (!(params instanceof FindTSPPathsParameters)) { return; } var me = this, jsonObject; me.url = Util.urlPathAppend(me.url, 'tsppath'); jsonObject = { parameter: Util.toJSON(params.parameter), endNodeAssigned: params.endNodeAssigned, nodes: me.getNodesJson(params) }; me.request({ method: "GET", params: jsonObject, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function FindTSPPathsService.prototype.getNodesJson * @description 将节点对象转化为JSON字符串。 * @param {FindTSPPathsParameters} params - 旅行商分析服务参数类。 * @returns {string} 转化后的JSON字符串。 */ getNodesJson(params) { var jsonParameters = "", nodesString, i, len, nodes; if (params.isAnalyzeById === false) { for (nodesString = "[", i = 0, nodes = params.nodes, len = nodes.length; i < len; i++) { if (i > 0) { nodesString += ","; } nodesString += '{"x":' + nodes[i].x + ',"y":' + nodes[i].y + '}'; } nodesString += ']'; jsonParameters += nodesString; } else if (params.isAnalyzeById === true) { let nodeIDsString = "[", nodes = params.nodes, len = nodes.length; for (let i = 0; i < len; i++) { if (i > 0) { nodeIDsString += ","; } nodeIDsString += nodes[i]; } nodeIDsString += ']'; jsonParameters += nodeIDsString; } return jsonParameters; } /** * @function FindTSPPathsService.prototype.toGeoJSONResult * @description 将含有 geometry 的数据转换为 GeoJSON 格式。 * @param {Object} result - 服务器返回的结果对象。 */ toGeoJSONResult(result) { if (!result || !result.tspPathList) { return null; } var geoJSONFormat = new GeoJSON(); result.tspPathList.forEach(function (path) { if (path.route) { path.route = geoJSONFormat.toGeoJSON(path.route); } if (path.pathGuideItems) { path.pathGuideItems = geoJSONFormat.toGeoJSON(path.pathGuideItems); } if (path.edgeFeatures) { path.edgeFeatures = geoJSONFormat.toGeoJSON(path.edgeFeatures); } if (path.nodeFeatures) { path.nodeFeatures = geoJSONFormat.toGeoJSON(path.nodeFeatures); } }); return result; } } ;// CONCATENATED MODULE: ./src/common/iServer/GenerateSpatialDataParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GenerateSpatialDataParameters * @deprecatedclass SuperMap.GenerateSpatialDataParameters * @category iServer SpatialAnalyst GenerateSpatialData * @classdesc 动态分段操作参数类。通过该类可以为动态分段提供参数信息。 * @param {Object} options - 参数。 * @param {string} options.routeTable - 路由数据集。 * @param {string} options.routeIDField - 路由数据集的标识字段。 * @param {string} options.eventTable - 用于生成空间数据的事件表名。 * @param {DataReturnOption} options.dataReturnOption - 设置数据返回选项。 * @param {string} [options.attributeFilter] - 属性过滤条件。 * @param {string} options.eventRouteIDField - 用于生成空间数据的事件表的路由标识字段。 * @param {string} [options.measureField] - 用于生成空间数据的事件表的刻度字段,只有当事件为点事件的时候该属性才有意义。 * @param {string} [options.measureStartField] - 用于生成空间数据的事件表的起始刻度字段,只有当事件为线事件的时候该属性才有意义。 * @param {string} [options.measureEndField] - 用于生成空间数据的事件表的终止刻度字段,只有当事件为线事件的时候该属性才有意义。 * @param {string} [options.measureOffsetField] - 刻度偏移量字段。 * @param {string} [options.errorInfoField] - 错误信息字段,直接写入原事件表,用于描述事件未能生成对应的点或线时的错误信息。 * @param {Array.} [options.retainedFields] - 欲保留到结果空间数据中的字段集合(系统字段除外)。 * @usage */ class GenerateSpatialDataParameters { constructor(options) { /** * @member {string} GenerateSpatialDataParameters.prototype.routeTable * @description 路由数据集。 */ this.routeTable = null; /** * @member {string} GenerateSpatialDataParameters.prototype.routeIDField * @description 路由数据集的标识字段。 */ this.routeIDField = null; /** * @member {string} [GenerateSpatialDataParameters.prototype.attributeFilter] * @description 属性过滤条件。 * 当 {@link GenerateSpatialDataParameters.prototype.dataReturnOption.dataReturnMode} 为 {@link DataReturnMode.DATASET_AND_RECORDSET} 或 {@link DataReturnMode.RECORDSET_ONLY} 时有效。 */ this.attributeFilter = null; /** * @member {string} GenerateSpatialDataParameters.prototype.eventTable * @description 用于生成空间数据的事件表名。 */ this.eventTable = null; /** * @member {string} GenerateSpatialDataParameters.prototype.eventRouteIDField * @description 用于生成空间数据的事件表的路由标识字段。 */ this.eventRouteIDField = null; /** * @member {string} [GenerateSpatialDataParameters.prototype.measureField] * @description 用于生成空间数据的事件表的刻度字段,只有当事件为点事件的时候该属性才有意义。 */ this.measureField = null; /** * @member {string} [GenerateSpatialDataParameters.prototype.measureStartField] * @description 用于生成空间数据的事件表的起始刻度字段,只有当事件为线事件的时候该属性才有意义。 */ this.measureStartField = null; /** * @member {string} [GenerateSpatialDataParameters.prototype.measureEndField] * @description 用于生成空间数据的事件表的终止刻度字段,只有当事件为线事件的时候该属性才有意义。 */ this.measureEndField = null; /** * @member {string} [GenerateSpatialDataParameters.prototype.measureOffsetField] * @description 刻度偏移量字段。 */ this.measureOffsetField = null; /** * @member {string} [GenerateSpatialDataParameters.prototype.errorInfoField] * @description 错误信息字段,直接写入原事件表,用于描述事件未能生成对应的点或线时的错误信息。 */ this.errorInfoField = null; /** * @member {Array.} [GenerateSpatialDataParameters.prototype.retainedFields] * @description 欲保留到结果空间数据中的字段集合(系统字段除外)。 * 生成空间数据时,无论是否指定保留字段,路由 ID 字段、刻度偏移量字段、刻度值字段(点事件为刻度字段,线事件是起始和终止刻度字段)都会保留到结果空间数据中; * 如果没有指定 retainedFields 参数或者 retainedFields 参数数组长度为 0,则返回所有用户字段。 */ this.retainedFields = null; /** * @member {DataReturnOption} GenerateSpatialDataParameters.prototype.dataReturnOption * @description 设置数据返回的选项。 */ this.dataReturnOption = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GenerateSpatialDataParameters"; } /** * @function GenerateSpatialDataParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.routeTable) { me.routeTable = null; } me.routeIDField = null; me.attributeFilter = null; me.eventTable = null; me.eventRouteIDField = null; me.measureField = null; me.measureStartField = null; me.measureEndField = null; me.measureOffsetField = null; me.errorInfoField = null; if (me.dataReturnOption) { me.dataReturnOption.destroy(); me.dataReturnOption = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/GenerateSpatialDataService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GenerateSpatialDataService * @deprecatedclass SuperMap.GenerateSpatialDataService * @category iServer SpatialAnalyst GenerateSpatialData * @classdesc 动态分段分析服务类。该类负责将客户设置的动态分段分析服务参数传递给服务端,并接收服务端返回的动态分段分析结果数据。 * 获取的结果数据包括 originResult 、result 两种,其中,originResult 为服务端返回的用 JSON 对象表示的动态分段分析结果数据,result 为服务端返回的动态分段分析结果数据。 * @param {string} url - 服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst。 * @param {Object} options - 参数。
* @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 实例化该类如下例所示: * (start code) * function GenerateSpatialData(){ * * //配置数据返回选项(option) * var option = new DataReturnOption({ * expectCount: 1000, * dataset: "generateSpatialData", * deleteExistResultDataset: true, * dataReturnMode: DataReturnMode.DATASET_ONLY * }), * //配置动态分段参数(Parameters) * parameters = new GenerateSpatialDataParameters({ * routeTable: "RouteDT_road@Changchun", * routeIDField: "RouteID", * eventTable: "LinearEventTabDT@Changchun", * eventRouteIDField: "RouteID", * measureField: "", * measureStartField: "LineMeasureFrom", * measureEndField: "LineMeasureTo", * measureOffsetField: "", * errorInfoField: "", * retainedFields:[], * dataReturnOption: option * }), * //配置动态分段iService * iService = new GenerateSpatialDataService(Changchun_spatialanalyst, { * eventListeners: { * processCompleted: generateCompleted, * processFailed: generateFailded * } * }); * //执行 * iService.processAsync(parameters); * function Completed(generateSpatialDataEventArgs){//todo}; * function Error(generateSpatialDataEventArgs){//todo}; * (end) * @usage */ class GenerateSpatialDataService extends SpatialAnalystBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.GenerateSpatialDataService"; } /** * @function GenerateSpatialDataService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function GenerateSpatialDataService.prototype.processAsync * @description 负责将客户端的动态分段服务参数传递到服务端。 * @param {GenerateSpatialDataParameters} params - 动态分段操作参数类。 */ processAsync(params) { if (!(params instanceof GenerateSpatialDataParameters)) { return; } var me = this, jsonParameters; jsonParameters = me.getJsonParameters(params); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function GenerateSpatialDataService.prototype.getJsonParameters * @description 将参数转化为 JSON 字符串。 * @param {GenerateSpatialDataParameters} params - 动态分段操作参数类。 * @returns {string}转化后的JSON字符串。 */ getJsonParameters(params) { var jsonParameters = "", jsonStr = "datasets/" + params.routeTable + "/linearreferencing/generatespatialdata", me = this; me.url = Util.urlPathAppend(me.url, jsonStr); me.url = Util.urlAppend(me.url, 'returnContent=true'); jsonParameters = Util.toJSON(params); return jsonParameters; } } ;// CONCATENATED MODULE: ./src/common/iServer/GeoHashGridAggParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeoHashGridAggParameter * @deprecatedclass SuperMap.GeoHashGridAggParameter * @classdesc 格网聚合查询参数类,该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 * @category iServer Data FeatureResults * @param {Object} options - 可选参数。 * @param {number} [options.precision=5] - 精度。 * @extends {BucketAggParameter} * @usage */ class GeoHashGridAggParameter extends BucketAggParameter { constructor(options) { super(); /** * @member {number} [GeoHashGridAggParameter.prototype.precision=5] * @description 网格中数字的精度。 */ this.precision = 5; Util.extend(this, options); /** * @member {BucketAggType} [GeoHashGridAggParameter.prototype.aggType=BucketAggType.GEOHASH_GRID] * @description 格网聚合类型。 */ this.aggType = BucketAggType.GEOHASH_GRID; this.CLASS_NAME = 'SuperMap.GeoHashGridAggParameter'; } destroy() { super.destroy(); this.aggType = null; this.precision = null; } /** * @function GeoHashGridAggParameter.toJsonParameters * @description 将对象转为 JSON 格式。 * @param param 转换对象。 * @returns {Object} */ static toJsonParameters(param) { var parameters = { aggName: param.aggName, aggFieldName: param.aggFieldName, aggType: param.aggType, precision: param.precision }; return Util.toJson(parameters); } } ;// CONCATENATED MODULE: ./src/common/iServer/GeometryOverlayAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryOverlayAnalystParameters * @deprecatedclass SuperMap.GeometryOverlayAnalystParameters * @category iServer SpatialAnalyst OverlayAnalyst * @classdesc * 几何对象叠加分析参数类。对指定的某两个几何对象做叠加分析。通过该类可以指定要做叠加分析的几何对象、叠加操作类型。 * @param {Object} options - 参数。 * @param {GeoJSONObject} options.operateGeometry - 叠加分析的操作几何对象。
* 点类型可以是:{@link GeometryPoint}|{@link L.Marker}|{@link L.CircleMarker}|{@link L.Circle}|{@link L.GeoJSON}|{@link ol.geom.Point}|{@link ol.format.GeoJSON}|{@link GeoJSONObject}。
* 线类型可以是:{@link GeometryLineString}|{@link GeometryLinearRing}|{@link L.Polyline}|{@link L.GeoJSON}|{@link ol.geom.LineString}|{@link GeoJSONObject}。
* 面类型可以是:{@link GeometryPolygon}|{@link L.Polygon}|{@link L.GeoJSON}|{@link ol.geom.Polygon}|{@link GeoJSONObject}。
* @param {GeoJSONObject} options.sourceGeometry - 叠加分析的源几何对象。 * @param {Array.} [options.operateGeometries] - 批量叠加分析的操作几何对象数组。 * @param {Array.} [options.sourceGeometries] -批量叠加分析的源几何对象数组。 * @param {OverlayOperationType} [options.operation] - 叠加操作枚举值。 * @extends {OverlayAnalystParameters} * @usage */ class GeometryOverlayAnalystParameters extends OverlayAnalystParameters { constructor(options) { super(options); if (options && options.operateGeometry) { this.operateGeometry = options.operateGeometry; } if (options && options.sourceGeometry) { this.sourceGeometry = options.sourceGeometry; } if (options && options.operateGeometries) { this.operateGeometries = options.operateGeometries; } if (options && options.sourceGeometries) { this.sourceGeometries = options.sourceGeometries; } if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GeometryOverlayAnalystParameters"; } /** * @function GeometryOverlayAnalystParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.sourceGeometry) { me.sourceGeometry.destroy(); me.sourceGeometry = null; } if (me.sourceGeometries) { me.sourceGeometries.destroy(); me.sourceGeometries = null; } if (me.sourceGeometry) { me.sourceGeometry.destroy(); me.sourceGeometry = null; } if (me.operateGeometries) { me.operateGeometries.destroy(); me.operateGeometries = null; } } /** * @function GeometryOverlayAnalystParameters.toObject * @param {GeometryOverlayAnalystParameters} geometryOverlayAnalystParameters - 几何对象叠加分析参数类。 * @param {GeometryOverlayAnalystParameters} tempObj - 几何对象叠加分析参数对象。 * @description 将几何对象叠加分析参数对象转换为 JSON 对象。 * @returns {Object} JSON 对象。 */ static toObject(geometryOverlayAnalystParameters, tempObj) { for (var name in geometryOverlayAnalystParameters) { if (name === "sourceGeometry") { tempObj.sourceGeometry = ServerGeometry.fromGeometry(geometryOverlayAnalystParameters.sourceGeometry); } else if (name === "sourceGeometries") { var sourceGeometries = []; for (var i = 0; i < geometryOverlayAnalystParameters.sourceGeometries.length; i++) { sourceGeometries.push(ServerGeometry.fromGeometry(geometryOverlayAnalystParameters.sourceGeometries[i])); } tempObj.sourceGeometries = sourceGeometries; } else if (name === "operateGeometry") { tempObj.operateGeometry = ServerGeometry.fromGeometry(geometryOverlayAnalystParameters.operateGeometry); } else if (name === "operateGeometries") { var operateGeometries = []; for (var j = 0; j < geometryOverlayAnalystParameters.operateGeometries.length; j++) { operateGeometries.push(ServerGeometry.fromGeometry(geometryOverlayAnalystParameters.operateGeometries[j])); } tempObj.operateGeometries = operateGeometries; } else { tempObj[name] = geometryOverlayAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/GeometrySurfaceAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometrySurfaceAnalystParameters * @deprecatedclass SuperMap.GeometrySurfaceAnalystParameters * @category iServer SpatialAnalyst SurfaceAnalyst * @classdesc 几何对象表面分析参数类。该类对几何对象表面分析所用到的参数进行设置。 * @param {Object} options - 参数。 * @param {Array.>} options.points - 表面分析的坐标点数组。 * @param {Array.} options.zValues - 表面分析的坐标点的 Z 值数组。 * @param {number} [options.resolution] - 获取或设置指定中间结果(栅格数据集)的分辨率。 * @param {DataReturnOption} [options.resultSetting] - 结果返回设置类。 * @param {SurfaceAnalystParametersSetting} options.extractParameter - 获取或设置表面分析参数。 * @param {SurfaceAnalystMethod} [options.surfaceAnalystMethod = SurfaceAnalystMethod.ISOLINE] - 获取或设置表面分析的提取方法,提取等值线和提取等值面。 * @extends {SurfaceAnalystParameters} * @usage */ class GeometrySurfaceAnalystParameters extends SurfaceAnalystParameters { constructor(options) { super(options); /** * @member {Array.>} GeometrySurfaceAnalystParameters.prototype.points * @description 获取或设置用于表面分析的坐标点数组。 */ this.points = null; /** * @member {Array.} GeometrySurfaceAnalystParameters.prototype.zValues * @description 获取或设置用于提取操作的值。提取等值线时,将使用该数组中的值, * 对几何对象中的坐标点数组进行插值分析,得到栅格数据集(中间结果),接着从栅格数据集提取等值线。 */ this.zValues = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GeometrySurfaceAnalystParameters"; } /** * @function GeometrySurfaceAnalystParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.points) { for (var i = 0, points = me.points, len = points.length; i < len; i++) { points[i].destroy(); } me.points = null; } me.zValues = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/GeometryThiessenAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryThiessenAnalystParameters * @deprecatedclass SuperMap.GeometryThiessenAnalystParameters * @constructs GeometryThiessenAnalystParameters * @category iServer SpatialAnalyst ThiessenPolygonAnalyst * @classdesc 几何对象泰森多边形分析参数类。对指定的某个几何对象做泰森多边形分析。通过该类可以指定要做泰森多边形分析的几何对象、返回数据集名称等。 * @param {Object} options - 参数。 * @param {Array.>} options.points - 使用点数组进行分析时使用的几何对象。 * @extends {ThiessenAnalystParameters} * @usage */ class GeometryThiessenAnalystParameters extends ThiessenAnalystParameters { constructor(options) { super(options); /** * @member {Array.>} GeometryThiessenAnalystParameters.prototype.points * @description 使用点数组进行分析时使用的几何对象。 */ this.points = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GeometryThiessenAnalystParameters"; } /** * @function GeometryThiessenAnalystParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.points) { for (var i = me.points.length - 1; i >= 0; i--) { me.points[i].destroy(); } me.points = null; } } /** * @function GeometryThiessenAnalystParameters.toObject * @param {GeometryThiessenAnalystParameters} geometryThiessenAnalystParameters - 几何对象泰森多边形分析参数类。 * @param {GeometryThiessenAnalystParameters} tempObj - 几何对象泰森多边形分析参数对象。 * @description 将几何对象泰森多边形分析参数对象转换为 JSON 对象。 * @returns {Object} JSON 对象。 */ static toObject(geometryThiessenAnalystParameters, tempObj) { for (var name in geometryThiessenAnalystParameters) { if (name === "clipRegion") { tempObj.clipRegion = ServerGeometry.fromGeometry(geometryThiessenAnalystParameters.clipRegion); } else { tempObj[name] = geometryThiessenAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/GeoprocessingService.js /** * @class GeoprocessingService * @deprecatedclass SuperMap.GeoprocessingService * @category iServer ProcessingAutomationService * @classdesc 处理自动化服务接口的基类。 * @version 10.1.0 * @extends {CommonServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {Events} options.events - 处理所有事件的对象。 * @param {Object} [options.eventListeners] - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @usage */ class GeoprocessingService_GeoprocessingService extends CommonServiceBase { constructor(url, options) { options = options || {}; options.EVENT_TYPES = ['processCompleted', 'processFailed', 'processRunning']; super(url, options); this.CLASS_NAME = 'SuperMap.GeoprocessingService'; this.headers = {}; this.crossOrigin = true; } /** * @function GeoprocessingService.prototype.getTools * @description 获取处理自动化工具列表。 */ getTools() { this._get(`${this.url}/list`); } /** * @function GeoprocessingService.prototype.getTool * @description 获取处理自动化工具的ID、名称、描述、输入参数、环境参数和输出结果等相关参数。 * @param {string} identifier - 处理自动化工具ID。 */ getTool(identifier) { this._get(`${this.url}/${identifier}`); } /** * @function GeoprocessingService.prototype.execute * @description 同步执行处理自动化工具。 * @param {string} identifier - 处理自动化工具ID。 * @param {Object} parameter - 处理自动化工具的输入参数。 * @param {Object} environment - 处理自动化工具的环境参数。 */ execute(identifier, parameter, environment) { parameter = parameter ? parameter : null; environment = environment ? environment : null; const executeParamter = { parameter, environment }; this._get(`${this.url}/${identifier}/execute`, executeParamter); } /** * @function GeoprocessingService.prototype.submitJob * @description 异步执行处理自动化工具。 * @param {string} identifier - 处理自动化工具ID。 * @param {Object} parameter - 处理自动化工具的输入参数。 * @param {Object} environments - 处理自动化工具的环境参数。 */ submitJob(identifier, parameter, environments) { parameter = parameter ? parameter : null; environments = environments ? environments : null; const asyncParamter = { parameter: parameter, environments: environments }; this.request({ url: `${this.url}/${identifier}/jobs`, headers: { 'Content-type': 'application/json' }, method: 'POST', data: JSON.stringify(asyncParamter), scope: this, success: this.serviceProcessCompleted, failure: this.serviceProcessFailed }); } /** * @function GeoprocessingService.prototype.waitForJobCompletion * @description 获取处理自动化异步执行状态信息。 * @param {string} jobId - 处理自动化任务ID。 * @param {string} identifier - 处理自动化工具ID。 * @param {Object} options - 状态信息参数。 * @param {number} options.interval - 定时器时间间隔。 * @param {function} options.statusCallback - 任务状态的回调函数。 */ waitForJobCompletion(jobId, identifier, options) { const me = this; const timer = setInterval(function () { const serviceProcessCompleted = function (serverResult) { const state = serverResult.state.runState; if (options.statusCallback) { options.statusCallback(state); } switch (state) { case 'FINISHED': clearInterval(timer); me.events.triggerEvent('processCompleted', { result: serverResult }); break; case 'FAILED': clearInterval(timer); me.events.triggerEvent('processFailed', { result: serverResult }); break; case 'CANCELED': clearInterval(timer); me.events.triggerEvent('processFailed', { result: serverResult }); break; } }; me._get(`${me.url}/${identifier}/jobs/${jobId}`, null, serviceProcessCompleted); }, options.interval); } /** * @function GeoprocessingService.prototype.getJobInfo * @description 获取处理自动化任务的执行信息。 * @param {string} identifier - 处理自动化工具ID。 * @param {string} jobId - 处理自动化任务ID。 */ getJobInfo(identifier, jobId) { this._get(`${this.url}/${identifier}/jobs/${jobId}`); } /** * @function GeoprocessingService.prototype.cancelJob * @description 取消处理自动化任务的异步执行。 * @param {string} identifier - 处理自动化工具ID。 * @param {string} jobId - 处理自动化任务ID。 */ cancelJob(identifier, jobId) { this._get(`${this.url}/${identifier}/jobs/${jobId}/cancel`); } /** * @function GeoprocessingService.prototype.getJobs * @description 获取处理自动化服务任务列表。 * @param {string} identifier - 处理自动化工具ID。(传参代表identifier算子的任务列表,不传参代表所有任务的列表) */ getJobs(identifier) { let url = `${this.url}/jobs`; if (identifier) { url = `${this.url}/${identifier}/jobs`; } this._get(url); } /** * @function GeoprocessingService.prototype.getResults * @description 处理自动化工具执行的结果等,支持结果过滤。 * @param {string} identifier - 处理自动化工具ID。 * @param {string} jobId - 处理自动化任务ID。 * @param {string} filter - 输出异步结果的ID。(可选,传入filter参数时对该处理自动化工具执行的结果进行过滤获取,不填参时显示所有的执行结果) */ getResults(identifier, jobId, filter) { let url = `${this.url}/${identifier}/jobs/${jobId}/results`; if (filter) { url = `${url}/${filter}`; } this._get(url); } _get(url, paramter, serviceProcessCompleted, serviceProcessFailed) { this.request({ url: url, method: 'GET', params: paramter, headers: { 'Content-type': 'application/json' }, scope: this, success: serviceProcessCompleted ? serviceProcessCompleted : this.serviceProcessCompleted, failure: serviceProcessFailed ? serviceProcessFailed : this.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/GeoRelationAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeoRelationAnalystParameters * @deprecatedclass SuperMap.GeoRelationAnalystParameters * @category iServer SpatialAnalyst GeoRelationAnalyst * @classdesc 空间关系分析服务参数类。使用该类可以为空间关系分析服务提供所需的参数信息。 * @param {Object} options - 参数。 * @param {FilterParameter} options.sourceFilter - 空间关系分析中的源数据集查询参数。仅 name, ids, attributeFilter 和 fields 字段有效。 * @param {FilterParameter} options.referenceFilter - 空间关系分析中的参考数据集查询参数。仅 name, ids, attributeFilter 和 fields 字段有效。 * @param {SpatialRelationType} options.spatialRelationType - 指定的空间关系类型。 * @param {boolean} [options.isBorderInside] - 边界处理方式,即位于面边线上的点是否被面包含。此参数仅用于空间关系为包含或被包含的情况。 * @param {boolean} [options.returnFeature] - 是否返回 Feature 信息。 * @param {boolean} [options.returnGeoRelatedOnly=true] - 仅返回满足指定空间关系的空间对象。 * @param {number} [options.startRecord=0] - 分析结果起始记录位置。 * @param {number} [options.expectCount=500] - 空间关系分析期望返回结果记录数,如果实际不足500条结果则返回所有分析结果。 * @usage */ class GeoRelationAnalystParameters { constructor(options) { /** * @member {string} GeoRelationAnalystParameters.prototype.dataset * @description 源数据集名称。 */ this.dataset = null; /** * @member {FilterParameter} GeoRelationAnalystParameters.prototype.sourceFilter * @description 空间关系分析中的源数据集查询参数。仅 ids、attributeFilter 和 fields 字段有效。 */ this.sourceFilter = null; /** * @member {FilterParameter} GeoRelationAnalystParameters.prototype.referenceFilter * @description 空间关系分析中的参考数据集查询参数。仅 name,ids,attributeFilter 和 fields 字段有效。 */ this.referenceFilter = null; /** * @member {SpatialRelationType} GeoRelationAnalystParameters.prototype.spatialRelationType * @description 指定的空间关系类型。 */ this.spatialRelationType = null; /** * @member {boolean} [GeoRelationAnalystParameters.prototype.isBorderInside] * @description 边界处理方式,即位于面边线上的点是否被面包含。此参数仅用于空间关系为包含或被包含的情况。 */ this.isBorderInside = null; /** * @member {boolean} [GeoRelationAnalystParameters.prototype.returnFeature] * @description 是否返回 Feature 信息。 */ this.returnFeature = null; /** * @member {boolean} [GeoRelationAnalystParameters.prototype.returnGeoRelatedOnly=true] * @description 是否仅返回满足指定空间关系的空间对象。 */ this.returnGeoRelatedOnly = null; /** * @member {number} [GeoRelationAnalystParameters.prototype.returnGeoRelatedOnly=0] * @description 分析结果起始记录位置。 */ this.startRecord = 0; /** * @member {number} [GeoRelationAnalystParameters.prototype.expectCount=500] * @description 空间关系分析期望返回结果记录数,如果实际不足 500 条结果则返回所有分析结果。 */ this.expectCount = 500; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GeoRelationAnalystParameters"; } /** * @function GeoRelationAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.sourceFilter) { me.sourceFilter.destroy(); } me.sourceFilter = null; if (me.referenceFilter) { me.referenceFilter.destroy(); } me.referenceFilter = null; me.dataset = null; me.spatialRelationType = null; me.isBorderInside = null; me.returnFeature = null; me.returnGeoRelatedOnly = null; me.startRecord = null; me.expectCount = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/GeoRelationAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeoRelationAnalystService * @deprecatedclass SuperMap.GeoRelationAnalystService * @category iServer SpatialAnalyst GeoRelationAnalyst * @classdesc 空间关系分析服务类。该类负责将客户设置的空间关系分析服务参数传递给服务端,并接收服务端返回的空间关系分析结果数据。 * @param {string} url - 服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 实例化该类如下例所示: * (start code) * function datasetGeoRelationAnalystProcess() { * var referenceFilter = new FilterParameter({ * name:"Frame_R@Changchun", * attributeFilter:"SmID>0"}); * var sourceFilter = new FilterParameter({ * attributeFilter:"SmID>0"}); * //初始化服务类 * var datasetGeoRelationService = new GeoRelationAnalystService( * "http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst/"), * //构建参数类 * datasetGeoRelationParameters = new GeoRelationAnalystParameters({ * dataset: "Park@Changchun", * startRecord: 0, * expectCount: 20, * sourceFilter: sourceFilter, * referenceFilter: referenceFilter, * spatialRelationType: SpatialRelationType.INTERSECT, * isBorderInside: true, * returnFeature: true, * returnGeoRelatedOnly: true * }); * datasetGeoRelationService.events.on({ * "processCompleted": datasetGeoRelationAnalystCompleted, * "processFailed": datasetGeoRelationAnalystFailed}); * //执行 * datasetGeoRelationService.processAsync(datasetGeoRelationParameters); * } * function Completed(datasetGeoRelationAnalystCompleted){//todo}; * function Error(datasetGeoRelationAnalystFailed){//todo}; * (end) * @usage */ class GeoRelationAnalystService extends SpatialAnalystBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.GeoRelationAnalystService"; } /** * @function GeoRelationAnalystService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function GeoRelationAnalystService.prototype.processAsync * @description 负责将客户端的空间关系分析参数传递到服务端 * @param {GeoRelationAnalystParameters} parameter - 空间关系分析所需的参数信息。 */ processAsync(parameter) { if (!(parameter instanceof GeoRelationAnalystParameters)) { return; } var me = this; me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/georelation'); var jsonParameters = Util.toJSON(parameter); me.url = Util.urlAppend(me.url, 'returnContent=true'); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/DatasetService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasetService * @deprecatedclass SuperMap.DatasetService * @category iServer Data Dataset * @classdesc 数据集查询服务。 * @param {string} url - 服务的访问地址。如访问World Data服务,只需将url设为:http://localhost:8090/iserver/services/data-world/rest/data 即可。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {string}options.datasource - 数据源名称。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class DatasetService_DatasetService extends CommonServiceBase { constructor(url, options) { super(url, options); if(!options){ return; } /** * @member {string} DatasetService.prototype.datasource * @description 要查询的数据集所在的数据源名称。 */ this.datasource = null; /** * @member {string} DatasetService.prototype.dataset * @description 要查询的数据集名称。 */ this.dataset = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.DatasetService"; } /** * @function DatasetService.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.datasource = null; me.dataset = null; } /** * @function DatasetService.prototype.getDatasetsService * @description 执行服务,查询数据集服务。 */ getDatasetsService(params) { var me = this; me.url = Util.urlPathAppend(me.url,`datasources/name/${params}/datasets`); me.request({ method: "GET", data: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function DatasetService.prototype.getDatasetService * @description 执行服务,查询数据集信息服务。 */ getDatasetService(datasourceName, datasetName) { var me = this; me.url = Util.urlPathAppend(me.url,`datasources/name/${datasourceName}/datasets/name/${datasetName}`); me.request({ method: "GET", data: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function DatasetService.prototype.setDatasetService * @description 执行服务,更改数据集信息服务。 */ setDatasetService(params) { if (!params) { return; } var me = this; var jsonParamsStr = Util.toJSON(params); me.request({ method: "PUT", data: jsonParamsStr, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function DatasetService.prototype.deleteDatasetService * @description 执行服务,删除数据集信息服务。 */ deleteDatasetService() { var me = this; me.request({ method: "DELETE", data: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesParametersBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesParametersBase * @deprecatedclass SuperMap.GetFeaturesParametersBase * @category iServer Data FeatureResults * @classdesc 要素查询参数基类。 * @param {Object} options - 参数。 * @param {Array.} options.datasetNames - 数据集名称列表。 * @param {boolean} [options.returnContent=true] - 是否直接返回查询结果。 * @param {number} [options.fromIndex=0] - 查询结果的最小索引号。 * @param {number} [options.toIndex=19] - 查询结果的最大索引号。 * @param {string|number} [options.targetEpsgCode] - 动态投影的目标坐标系对应的 EPSG Code,使用此参数时,returnContent 参数需为 true。 * @param {Object} [options.targetPrj] - 动态投影的目标坐标系。使用此参数时,returnContent 参数需为 true。如:prjCoordSys={"epsgCode":3857}。当同时设置 targetEpsgCode 参数时,此参数不生效。 * @param {MetricsAggParameter|GeoHashGridAggParameter} [options.aggregations] - 聚合查询参数。该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 * @usage */ class GetFeaturesParametersBase { constructor(options) { /** * @member {Array.} GetFeaturesParametersBase.prototype.datasetName * @description 数据集集合中的数据集名称列表。 */ this.datasetNames = null; /** * @member {string} GetFeaturesParametersBase.prototype.targetEpsgCode * @description 动态投影的目标坐标系对应的 EPSG Code,使用时需设置 returnContent 参数为 true。 */ this.targetEpsgCode = null; /** * @member {Object} GetFeaturesParametersBase.prototype.targetPrj * @description 动态投影的目标坐标系。使用时需设置 returnContent 参数为 true。如:prjCoordSys={"epsgCode":3857}。当同时设置 targetEpsgCode 参数时,此参数不生效。 */ this.targetPrj = null; /** * @member {boolean} [GetFeaturesParametersBase.prototype.returnContent=true] * @description 是否立即返回新创建资源的表述还是返回新资源的 URI。 * 如果为 true,则直接返回新创建资源,即查询结果的表述。 * 如果为 false,则返回的是查询结果资源的 URI。 */ this.returnContent = true; /** * @member {number} [GetFeaturesParametersBase.prototype.fromIndex=0] * @description 查询结果的最小索引号。如果该值大于查询结果的最大索引号,则查询结果为空。 */ this.fromIndex = 0; /** * @member {number} [GetFeaturesParametersBase.prototype.toIndex=19] * @description 查询结果的最大索引号。如果该值大于查询结果的最大索引号,则以查询结果的最大索引号为终止索引号。 */ this.toIndex = 19; /** * @member {boolean} [GetFeaturesParametersBase.prototype.returnCountOnly=false] * @description 只返回查询结果的总数。 */ this.returnCountOnly = false; /** * @member {number} [GetFeaturesParametersBase.prototype.maxFeatures=1000] * @description 进行 SQL 查询时,用于设置服务端返回查询结果条目数量。 */ this.maxFeatures = null; /** * @member {number} [GetFeaturesParametersBase.prototype.hasGeometry=true] * @description 返回结果是否包含Geometry。 */ this.hasGeometry = true; /** * @member {MetricsAggParameter|GeoHashGridAggParameter} GetFeaturesParametersBase.prototype.aggregations * @description 聚合查询参数,该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 */ this.aggregations = null; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.GetFeaturesParametersBase'; } /** * * @function GetFeaturesParametersBase.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.datasetNames = null; me.returnContent = null; me.fromIndex = null; me.toIndex = null; me.hasGeometry = null; me.maxFeatures = null; me.targetEpsgCode = null; me.targetPrj = null; if (me.aggregation) { me.aggregation = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesByBoundsParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesByBoundsParameters * @deprecatedclass SuperMap.GetFeaturesByBoundsParameters * @category iServer Data FeatureResults * @classdesc 数据集范围查询参数类,该类用于设置数据集范围查询的相关参数。 * @param {Object} options - 参数。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} options.bounds - 查询的范围对象。 * @param {Array.} options.datasetNames - 数据集名称列表。 * @param {string} [options.attributeFilter] - 范围查询属性过滤条件。 * @param {Array.} [options.fields] - 设置查询结果返回字段。默认返回所有字段。 * @param {SpatialQueryMode} [options.spatialQueryMode=SpatialQueryMode.CONTAIN] - 空间查询模式常量。 * @param {boolean} [options.returnContent=true] - 是否直接返回查询结果。 * @param {number} [options.fromIndex=0] - 查询结果的最小索引号。 * @param {number} [options.toIndex=19] - 查询结果的最大索引号。 * @param {string|number} [options.targetEpsgCode] - 动态投影的目标坐标系对应的 EPSG Code,使用此参数时,returnContent 参数需为 true。 * @param {Object} [options.targetPrj] - 动态投影的目标坐标系。使用此参数时,returnContent 参数需为 true。如:prjCoordSys={"epsgCode":3857}。当同时设置 targetEpsgCode 参数时,此参数不生效。 * @param {MetricsAggParameter|GeoHashGridAggParameter} [options.aggregations] - 聚合查询参数。该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 * @extends {GetFeaturesParametersBase} * @usage */ class GetFeaturesByBoundsParameters extends GetFeaturesParametersBase { constructor(options) { super(options); /** * @member {string} GetFeaturesByBoundsParameters.prototype.getFeatureMode * @description 数据集查询模式。范围查询有 "BOUNDS","BOUNDS_ATTRIBUTEFILTER" 两种,当用户设置 attributeFilter 时会自动切换到 BOUNDS_ATTRIBUTEFILTER 访问服务。 */ this.getFeatureMode = GetFeaturesByBoundsParameters.getFeatureMode.BOUNDS; /** * @member {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} GetFeaturesByBoundsParameters.prototype.bounds * @description 用于查询的范围对象。 * */ this.bounds = null; /** * @member {Array.} GetFeaturesByBoundsParameters.prototype.fields * @description 设置查询结果返回字段。当指定了返回结果字段后,则 GetFeaturesResult 中的 features 的属性字段只包含所指定的字段。不设置即返回全部字段。 */ this.fields = null; /** * @member {string} GetFeaturesByBoundsParameters.prototype.attributeFilter * @description 范围查询属性过滤条件。 */ this.attributeFilter = null; /** * @member {SpatialQueryMode} [GetFeaturesByBoundsParameters.prototype.spatialQueryMode=SpatialQueryMode.CONTAIN] * @description 空间查询模式常量。 */ this.spatialQueryMode = SpatialQueryMode.CONTAIN; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.GetFeaturesByBoundsParameters'; } /** * @function GetFeaturesByBoundsParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.bounds) { me.bounds.destroy(); me.bounds = null; } if (me.fields) { while (me.fields.length > 0) { me.fields.pop(); } me.fields = null; } me.attributeFilter = null; me.spatialQueryMode = null; me.getFeatureMode = null; } /** * @function GetFeaturesByBoundsParameters.toJsonParameters * @description 将 {@link GetFeaturesByBoundsParameters} 对象参数转换为 JSON 字符串。 * @param {GetFeaturesByBoundsParameters} params - 范围查询参数。 * @returns {string} 转化后的 JSON 字符串。 * */ static toJsonParameters(params) { var filterParameter, bounds, parasByBounds; bounds = { leftBottom: { x: params.bounds.left, y: params.bounds.bottom }, rightTop: { x: params.bounds.right, y: params.bounds.top } }; parasByBounds = { datasetNames: params.datasetNames, getFeatureMode: GetFeaturesByBoundsParameters.getFeatureMode.BOUNDS, bounds: bounds, spatialQueryMode: params.spatialQueryMode }; if (params.fields) { filterParameter = new FilterParameter(); filterParameter.name = params.datasetNames; filterParameter.fields = params.fields; parasByBounds.queryParameter = filterParameter; } if (params.attributeFilter) { parasByBounds.attributeFilter = params.attributeFilter; parasByBounds.getFeatureMode = GetFeaturesByBoundsParameters.getFeatureMode.BOUNDS_ATTRIBUTEFILTER; } if (params.maxFeatures && !isNaN(params.maxFeatures)) { parasByBounds.maxFeatures = params.maxFeatures; } if (typeof params.hasGeometry === 'boolean') { parasByBounds.hasGeometry = params.hasGeometry; } if (params.targetEpsgCode) { parasByBounds.targetEpsgCode = params.targetEpsgCode; } if (!params.targetEpsgCode && params.targetPrj) { parasByBounds.targetPrj = params.targetPrj; } if (params.aggregations) { parasByBounds.aggregations = params.aggregations; } return Util.toJSON(parasByBounds); } } GetFeaturesByBoundsParameters.getFeatureMode = { BOUNDS: 'BOUNDS', BOUNDS_ATTRIBUTEFILTER: 'BOUNDS_ATTRIBUTEFILTER' }; ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesServiceBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesServiceBase * @deprecatedclass SuperMap.GetFeaturesServiceBase * @category iServer Data FeatureResults * @classdesc 数据服务中数据集查询服务基类。获取结果数据类型为 Object。包含 result 属性,result 的数据格式根据 format 参数决定为 GeoJSON 或者 iServerJSON。 * @extends CommonServiceBase * @param {string} url - 服务地址。请求数据服务中数据集查询服务, * URL应为:http://{服务器地址}:{服务端口号}/iserver/services/{数据服务名}/rest/data/ * 例如:"http://localhost:8090/iserver/services/data-jingjin/rest/data/" * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * var myService = new GetFeaturesServiceBase(url, { * eventListeners: { * "processCompleted": getFeatureCompleted, * "processFailed": getFeatureError * } * }); * @usage */ class GetFeaturesServiceBase extends CommonServiceBase { constructor(url, options) { super(url, options); options = options || {}; /** * @member {boolean} [GetFeaturesServiceBase.prototype.returnContent=true] * @description 是否立即返回新创建资源的表述还是返回新资源的 URI。 * 如果为 true,则直接返回新创建资源,即查询结果的表述。 * 如果为 false,则返回的是查询结果资源的 URI。 */ this.returnContent = true; /** * @member {number} [GetFeaturesServiceBase.prototype.fromIndex=0] * @description 查询结果的最小索引号。如果该值大于查询结果的最大索引号,则查询结果为空。 */ this.fromIndex = 0; /** * @member {number} [GetFeaturesServiceBase.prototype.toIndex=19] * @description 查询结果的最大索引号。 * 如果该值大于查询结果的最大索引号,则以查询结果的最大索引号为终止索引号。 */ this.toIndex = 19; /** * @member {number} [GetFeaturesServiceBase.prototype.hasGeometry=true] * @description 返回结果是否包含Geometry。 */ this.hasGeometry = true; /** * @member {number} [GetFeaturesServiceBase.prototype.maxFeatures=1000] * @description 进行 SQL 查询时,用于设置服务端返回查询结果条目数量。 */ this.maxFeatures = null; /** * @member {string} [GetFeaturesServiceBase.prototype.format=DataFormat.GEOJSON] * @description 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。 * 参数格式为 "ISERVER","GEOJSON","FGB"。 */ this.format = DataFormat.GEOJSON; Util.extend(this, options); this.url = Util.urlPathAppend(this.url, 'featureResults'); this.CLASS_NAME = "SuperMap.GetFeaturesServiceBase"; } /** * @function GetFeaturesServiceBase.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.returnContent = null; me.fromIndex = null; me.toIndex = null; me.maxFeatures = null; me.format = null; me.hasGeometry = null; } /** * @function GetFeaturesServiceBase.prototype.processAsync * @description 将客户端的查询参数传递到服务端。 * @param {Object} params - 查询参数。 */ processAsync(params) { if (!params) { return; } var me = this, jsonParameters = null, firstPara = true; me.returnContent = params.returnContent; me.fromIndex = params.fromIndex; me.toIndex = params.toIndex; me.maxFeatures = params.maxFeatures; me.hasGeometry = params.hasGeometry; if (me.returnContent) { firstPara = false; } var isValidNumber = me.fromIndex != null && me.toIndex != null && !isNaN(me.fromIndex) && !isNaN(me.toIndex); if (isValidNumber && me.fromIndex >= 0 && me.toIndex >= 0 && !firstPara) { me.url = Util.urlAppend(me.url, `fromIndex=${me.fromIndex}&toIndex=${me.toIndex}`); } if (params.returnCountOnly) { me.url = Util.urlAppend(me.url, "&returnCountOnly=" + params.returnContent) } jsonParameters = me.getJsonParameters(params); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function GetFeaturesServiceBase.prototype.getFeatureComplete * @description 查询完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ serviceProcessCompleted(result) { var me = this; result = Util.transformResult(result); if (me.format === DataFormat.GEOJSON && result.features) { var geoJSONFormat = new GeoJSON(); result.features = geoJSONFormat.toGeoJSON(result.features); } me.events.triggerEvent("processCompleted", {result: result}); } dataFormat() { return [DataFormat.GEOJSON, DataFormat.ISERVER, DataFormat.FGB]; } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesByBoundsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesByBoundsService * @deprecatedclass SuperMap.GetFeaturesByBoundsService * @category iServer Data FeatureResults * @classdesc 数据集范围查询服务类,查询与指定范围对象符合一定空间关系的矢量要素。 * @description 数据集范围查询服务类构造函数。 * @extends {GetFeaturesServiceBase} * @param {string} url - 服务地址。请求数据服务中数据集查询服务,URL 应为:http://{服务器地址}:{服务端口号}/iserver/services/{数据服务名}/rest/data/; * 例如:"http://localhost:8090/iserver/services/data-jingjin/rest/data/" * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * var myGetFeaturesByBoundsService = new SuperMa.GetFeaturesByBoundsService(url, { * eventListeners: { * "processCompleted": getFeatureCompleted, * "processFailed": getFeatureError * } * }); * function getFeatureCompleted(object){//todo}; * function getFeatureError(object){//todo} * @usage */ class GetFeaturesByBoundsService extends GetFeaturesServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.GetFeaturesByBoundsService"; } /** * @function GetFeaturesByBoundsService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function GetFeaturesByBoundsService.prototype.getJsonParameters * @description 将查询参数转化为 JSON 字符串。在本类中重写此方法,可以实现不同种类的查询(ID, SQL, Buffer, Geometry,Bounds等)。 * @param params {GetFeaturesByBoundsParameters} * @returns {string} 转化后的 JSON 字符串。 * */ getJsonParameters(params) { return GetFeaturesByBoundsParameters.toJsonParameters(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesByBufferParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesByBufferParameters * @deprecatedclass SuperMap.GetFeaturesByBufferParameters * @category iServer Data FeatureResults * @classdesc 数据集缓冲区查询参数类。 * @param {Object} options - 参数。 * @param {number} options.bufferDistance - buffer 距离,单位与所查询图层对应的数据集单位相同。 * @param {GeoJSONObject} options.geometry - 空间查询条件。 * @param {Array.} options.dataSetNames - 数据集集合中的数据集名称列表。 * @param {Array.} [options.fields] - 设置查询结果返回字段。默认返回所有字段。 * @param {string} [options.attributeFilter] - 属性查询条件。 * @param {boolean} [options.returnContent=true] - 是否直接返回查询结果。 * @param {number} [options.fromIndex=0] - 查询结果的最小索引号。 * @param {number} [options.toIndex=19] - 查询结果的最大索引号。 * @param {string|number} [options.targetEpsgCode] - 动态投影的目标坐标系对应的 EPSG Code,使用此参数时,returnContent 参数需为 true。 * @param {Object} [options.targetPrj] - 动态投影的目标坐标系。使用此参数时,returnContent 参数需为 true。如:prjCoordSys={"epsgCode":3857}。当同时设置 targetEpsgCode 参数时,此参数不生效。 * @extends {GetFeaturesParametersBase} * @usage */ class GetFeaturesByBufferParameters extends GetFeaturesParametersBase { constructor(options) { super(options); /** * @member {number} GetFeaturesByBufferParameters.prototype.bufferDistance * @description buffer 距离,单位与所查询图层对应的数据集单位相同。 */ this.bufferDistance = null; /** * @member {string} GetFeaturesByBufferParameters.prototype.attributeFilter * @description 属性查询条件。 */ this.attributeFilter = null; /** * @member {GeoJSONObject} GetFeaturesByBufferParameters.prototype.geometry * @description 空间查询条件。
* 点类型可以是:{@link GeometryPoint}|{@link L.Marker}|{@link L.CircleMarker}|{@link L.Circle}|{@link L.GeoJSON}|{@link ol.geom.Point}|{@link ol.format.GeoJSON}|{@link mapboxgl.LngLat}|{@link mapboxgl.Point}|{@link GeoJSONObject}。
* 线类型可以是:{@link GeometryLineString}|{@link GeometryLinearRing}|{@link L.Polyline}|{@link L.GeoJSON}|{@link ol.geom.LineString}|{@link ol.format.GeoJSON}|{@link GeoJSONObject}。
* 面类型可以是:{@link GeometryPolygon}|{@link L.Polygon}|{@link L.GeoJSON}|{@link ol.geom.Polygon}|{@link ol.format.GeoJSON}|{@link mapboxgl.LngLatBounds}|{@link GeoJSONObject}。 */ this.geometry = null; /** * @member {Array.} GetFeaturesByBufferParameters.prototype.fields * @description 设置查询结果返回字段。当指定了返回结果字段后,则 GetFeaturesResult 中的 features 的属性字段只包含所指定的字段。不设置即返回全部字段。 */ this.fields = null; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.GetFeaturesByBufferParameters'; } /** * @function GetFeaturesByBufferParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.bufferDistance = null; me.attributeFilter = null; if (me.fields) { while (me.fields.length > 0) { me.fields.pop(); } me.fields = null; } if (me.geometry) { me.geometry.destroy(); me.geometry = null; } } /** * @function GetFeaturesByBufferParameters.toJsonParameters * @description 将 GetFeaturesByBufferParameters 对象转换为 JSON 字符串。 * @param {GetFeaturesByBufferParameters} params - 数据集缓冲区查询参数对象。 * @returns {string} 转化后的 JSON 字符串。 */ static toJsonParameters(params) { var filterParameter, paramsByBuffer, geometry; geometry = ServerGeometry.fromGeometry(params.geometry); paramsByBuffer = { datasetNames: params.datasetNames, getFeatureMode: 'BUFFER', bufferDistance: params.bufferDistance, geometry: geometry }; if (params.fields) { filterParameter = new FilterParameter(); filterParameter.name = params.datasetNames; filterParameter.fields = params.fields; paramsByBuffer.queryParameter = filterParameter; } if (params.attributeFilter) { paramsByBuffer.attributeFilter = params.attributeFilter; paramsByBuffer.getFeatureMode = 'BUFFER_ATTRIBUTEFILTER'; } if (params.maxFeatures && !isNaN(params.maxFeatures)) { paramsByBuffer.maxFeatures = params.maxFeatures; } if (typeof params.hasGeometry === 'boolean') { paramsByBuffer.hasGeometry = params.hasGeometry; } if (params.targetEpsgCode) { paramsByBuffer.targetEpsgCode = params.targetEpsgCode; } if (!params.targetEpsgCode && params.targetPrj) { paramsByBuffer.targetPrj = params.targetPrj; } return Util.toJSON(paramsByBuffer); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesByBufferService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesByBufferService * @deprecatedclass SuperMap.GetFeaturesByBufferService * @category iServer Data FeatureResults * @classdesc 数据服务中数据集缓冲区查询服务类。 * @param {string} url - 服务地址。请求数据服务中数据集查询服务, * URL 应为:http://{服务器地址}:{服务端口号}/iserver/services/{数据服务名}/rest/data/; * 例如:"http://localhost:8090/iserver/services/data-jingjin/rest/data/" * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {GetFeaturesServiceBase} * @example * var myGetFeaturesByBufferService = new GetFeaturesByBufferService(url, { * eventListeners: { * "processCompleted": GetFeaturesCompleted, * "processFailed": GetFeaturesError * } * }); * function GetFeaturesCompleted(object){//todo}; * function GetFeaturesError(object){//todo}; * @usage */ class GetFeaturesByBufferService extends GetFeaturesServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.GetFeaturesByBufferService"; } /** * @function GetFeaturesByBufferService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function GetFeaturesByBufferService.prototype.getJsonParameters * @description 将查询参数转化为 JSON 字符串。在本类中重写此方法,可以实现不同种类的查询(IDs, SQL, Buffer, Geometry等)。 * @param {GetFeaturesByBufferParameters} params - 数据集缓冲区查询参数类。 * @returns {Object} 转化后的 JSON 字符串。 */ getJsonParameters(params) { if (!(params instanceof GetFeaturesByBufferParameters)) { return; } return GetFeaturesByBufferParameters.toJsonParameters(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesByGeometryParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesByGeometryParameters * @deprecatedclass SuperMap.GetFeaturesByGeometryParameters * @category iServer Data FeatureResults * @classdesc 数据集几何查询参数类。该类用于设置数据集几何查询的相关参数。 * @param {Object} options - 参数。 * @param {GeoJSONObject} options.geometry - 查询的几何对象。 * @param {Array.} options.datasetNames - 数据集集合中的数据集名称列表。 * @param {string} [options.attributeFilter] - 几何查询属性过滤条件。 * @param {Array.} [options.fields] - 设置查询结果返回字段。默认返回所有字段。 * @param {SpatialQueryMode} [options.spatialQueryMode=SpatialQueryMode.CONTAIN] - 空间查询模式常量。 * @param {boolean} [options.returnContent=true] - 是否直接返回查询结果。 * @param {number} [options.fromIndex=0] - 查询结果的最小索引号。 * @param {number} [options.toIndex=19] - 查询结果的最大索引号。 * @param {string|number} [options.targetEpsgCode] - 动态投影的目标坐标系对应的 EPSG Code,使用此参数时,returnContent 参数需为 true。 * @param {Object} [options.targetPrj] - 动态投影的目标坐标系。使用此参数时,returnContent 参数需为 true。如:prjCoordSys={"epsgCode":3857}。当同时设置 targetEpsgCode 参数时,此参数不生效。 * @param {MetricsAggParameter|GeoHashGridAggParameter} [options.aggregations] - 聚合查询参数。该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 * @extends {GetFeaturesParametersBase} * @usage */ class GetFeaturesByGeometryParameters extends GetFeaturesParametersBase { constructor(options) { super(options); /** * @member {string} GetFeaturesByGeometryParameters.prototype.getFeatureMode * @description 数据集查询模式。几何查询有 "SPATIAL","SPATIAL_ATTRIBUTEFILTER" 两种,当用户设置 attributeFilter 时会自动切换到 SPATIAL_ATTRIBUTEFILTER 访问服务。 */ this.getFeatureMode = 'SPATIAL'; /** * @member {GeoJSONObject} GetFeaturesByGeometryParameters.prototype.geometry * @description 用于查询的几何对象。
* 点类型可以是:{@link GeometryPoint}|{@link L.Marker}|{@link L.CircleMarker}|{@link L.Circle}|{@link L.GeoJSON}|{@link ol.geom.Point}|{@link ol.format.GeoJSON}|{@link mapboxgl.LngLat}|{@link mapboxgl.Point}|{@link GeoJSONObject}。
* 线类型可以是:{@link GeometryLineString}|{@link GeometryLinearRing}|{@link L.Polyline}|{@link L.GeoJSON}|{@link ol.geom.LineString}|{@link ol.format.GeoJSON}|{@link GeoJSONObject}。
* 面类型可以是:{@link GeometryPolygon}|{@link L.Polygon}|{@link L.GeoJSON}|{@link ol.geom.Polygon}|{@link ol.format.GeoJSON}|{@link mapboxgl.LngLatBounds}|{@link GeoJSONObject}。 */ this.geometry = null; /** * @member {Array.} GetFeaturesByGeometryParameters.prototype.fields * @description 设置查询结果返回字段。当指定了返回结果字段后,则 GetFeaturesResult 中的 features 的属性字段只包含所指定的字段。不设置即返回全部字段。 */ this.fields = null; /** * @member {string} GetFeaturesByGeometryParameters.prototype.attributeFilter * @description 几何查询属性过滤条件。 */ this.attributeFilter = null; /** * @member {SpatialQueryMode} [GetFeaturesByGeometryParameters.prototype.spatialQueryMode=SpatialQueryMode.CONTAIN] * @description 空间查询模式常量。 */ this.spatialQueryMode = SpatialQueryMode.CONTAIN; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.GetFeaturesByGeometryParameters'; } /** * @function GetFeaturesByGeometryParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; if (me.geometry) { me.geometry.destroy(); me.geometry = null; } if (me.fields) { while (me.fields.length > 0) { me.fields.pop(); } me.fields = null; } me.attributeFilter = null; me.spatialQueryMode = null; me.getFeatureMode = null; } /** * @function GetFeaturesByGeometryParameters.toJsonParameters * @description 将 GetFeaturesByGeometryParameters 对象参数转换为 JSON 字符串。 * @param {GetFeaturesByGeometryParameters} params - 查询参数对象。 * @returns {string} 转化后的 JSON 字符串。 */ static toJsonParameters(params) { var filterParameter, geometry, parasByGeometry; geometry = ServerGeometry.fromGeometry(params.geometry); parasByGeometry = { datasetNames: params.datasetNames, getFeatureMode: 'SPATIAL', geometry: geometry, spatialQueryMode: params.spatialQueryMode }; if (params.fields) { filterParameter = new FilterParameter(); filterParameter.name = params.datasetNames; filterParameter.fields = params.fields; parasByGeometry.queryParameter = filterParameter; } if (params.attributeFilter) { parasByGeometry.attributeFilter = params.attributeFilter; parasByGeometry.getFeatureMode = 'SPATIAL_ATTRIBUTEFILTER'; } if (params.maxFeatures && !isNaN(params.maxFeatures)) { parasByGeometry.maxFeatures = params.maxFeatures; } if (typeof params.hasGeometry === 'boolean') { parasByGeometry.hasGeometry = params.hasGeometry; } if (params.targetEpsgCode) { parasByGeometry.targetEpsgCode = params.targetEpsgCode; } if (!params.targetEpsgCode && params.targetPrj) { parasByGeometry.targetPrj = params.targetPrj; } if (params.aggregations) { parasByGeometry.aggregations = params.aggregations; } return Util.toJSON(parasByGeometry); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesByGeometryService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesByGeometryService * @deprecatedclass SuperMap.GetFeaturesByGeometryService * @category iServer Data FeatureResults * @classdesc 数据集几何查询服务类,查询与指定几何对象符合一定空间关系的矢量要素。 * @param {string} url - 服务地址。请求数据服务中数据集查询服务。 * URL 应为:http://{服务器地址}:{服务端口号}/iserver/services/{数据服务名}/rest/data; * 例如:"http://localhost:8090/iserver/services/data-jingjin/rest/data" * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {GetFeaturesServiceBase} * @example * var myService = new GetFeaturesByGeometryService(url, { * eventListeners: { * "processCompleted": getFeatureCompleted, * "processFailed": getFeatureError * } * }); * function getFeatureCompleted(object){//todo}; * function getFeatureError(object){//todo} * @usage */ class GetFeaturesByGeometryService extends GetFeaturesServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.GetFeaturesByGeometryService"; } /** * @function GetFeaturesByGeometryService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function GetFeaturesByGeometryService.prototype.getJsonParameters * @param {GetFeaturesByGeometryParameters} params - 数据集几何查询参数类。 * @description 将查询参数转化为 JSON 字符串。 * 在本类中重写此方法,可以实现不同种类的查询(ID, SQL, Buffer, Geometry等)。 * @returns {Object} 转化后的 JSON 字符串。 */ getJsonParameters(params) { return GetFeaturesByGeometryParameters.toJsonParameters(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesByIDsParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesByIDsParameters * @deprecatedclass SuperMap.GetFeaturesByIDsParameters * @category iServer Data FeatureResults * @classdesc ID 查询参数类。 * @param {Object} options - 参数。 * @param {Array.} options.IDs - 指定查询的元素 ID 信息。 * @param {Array.} [options.fields] - 设置查询结果返回字段。默认返回所有字段。 * @param {Array.} options.dataSetNames - 数据集集合中的数据集名称列表。 * @param {boolean} [options.returnContent=true] - 是否直接返回查询结果。 * @param {number} [options.fromIndex=0] - 查询结果的最小索引号。 * @param {number} [options.toIndex=19] - 查询结果的最大索引号。 * @param {string|number} [options.targetEpsgCode] - 动态投影的目标坐标系对应的 EPSG Code,使用此参数时,returnContent 参数需为 true。 * @param {Object} [options.targetPrj] - 动态投影的目标坐标系。使用此参数时,returnContent 参数需为 true。如:prjCoordSys={"epsgCode":3857}。当同时设置 targetEpsgCode 参数时,此参数不生效。 * @param {MetricsAggParameter|GeoHashGridAggParameter} [options.aggregations] - 聚合查询参数。该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 * @extends {GetFeaturesParametersBase} * @usage */ class GetFeaturesByIDsParameters extends GetFeaturesParametersBase { constructor(options) { super(options); /** * @member {string} GetFeaturesByIDsParameters.prototype.getFeatureMode * @description 数据集查询模式。 */ this.getFeatureMode = 'ID'; /** * @member {Array.} GetFeaturesByIDsParameters.prototype.IDs * @description 所要查询指定的元素 ID 信息。 */ this.IDs = null; /** * @member {Array.} GetFeaturesByIDsParameters.prototype.fields * @description 设置查询结果返回字段。当指定了返回结果字段后,则 GetFeaturesResult 中的 features 的属性字段只包含所指定的字段。不设置即返回全部字段。 */ this.fields = null; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.GetFeaturesByIDsParameters'; } /** * @function GetFeaturesByIDsParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.IDs = null; me.getFeatureMode = null; if (me.fields) { while (me.fields.length > 0) { me.fields.pop(); } me.fields = null; } } /** * @function GetFeaturesByIDsParameters.toJsonParameters * @description 将 GetFeaturesByIDsParameters 对象转换为 JSON 字符串。 * @param {GetFeaturesByIDsParameters} params - ID 查询参数对象。 * @returns {string} 转化后的 JSON 字符串。 */ static toJsonParameters(params) { var parasByIDs, filterParameter; parasByIDs = { datasetNames: params.datasetNames, getFeatureMode: 'ID', ids: params.IDs }; if (params.fields) { filterParameter = new FilterParameter(); filterParameter.name = params.datasetNames; filterParameter.fields = params.fields; parasByIDs.queryParameter = filterParameter; } if (params.targetEpsgCode) { parasByIDs.targetEpsgCode = params.targetEpsgCode; } if (typeof params.hasGeometry === 'boolean') { parasByIDs.hasGeometry = params.hasGeometry; } if (!params.targetEpsgCode && params.targetPrj) { parasByIDs.targetPrj = params.targetPrj; } if (params.aggregations) { parasByIDs.aggregations = params.aggregations; } return Util.toJSON(parasByIDs); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesByIDsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesByIDsService * @deprecatedclass SuperMap.GetFeaturesByIDsService * @category iServer Data FeatureResults * @classdesc 数据集ID查询服务类。在数据集集合中查找指定 ID 号对应的空间地物要素。 * @param {string} url - 服务地址。请求数据服务中数据集查询服务。 * URL 应为:http://{服务器地址}:{服务端口号}/iserver/services/{数据服务名}/rest/data/;
* 例如:"http://localhost:8090/iserver/services/data-jingjin/rest/data/" * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {GetFeaturesServiceBase} * @example * var myGetFeaturesByIDsService = new GetFeaturesByIDsService(url, { * eventListeners: { * "processCompleted": getFeatureCompleted, * "processFailed": getFeatureError * } * }); * function getFeatureCompleted(object){//todo}; * function getFeatureError(object){//todo} * @usage */ class GetFeaturesByIDsService extends GetFeaturesServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.GetFeaturesByIDsService"; } /** * @function GetFeaturesByIDsService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function GetFeaturesByIDsService.prototype.getJsonParameters * @description 将查询参数转化为 JSON 字符串。 * 在本类中重写此方法,可以实现不同种类的查询(ID, SQL, Buffer, Geometry等)。 * @param {GetFeaturesByIDsParameters} params - ID查询参数类。 * @returns {string} 转化后的 JSON 字符串。 */ getJsonParameters(params) { return GetFeaturesByIDsParameters.toJsonParameters(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesBySQLParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesBySQLParameters * @deprecatedclass SuperMap.GetFeaturesBySQLParameters * @category iServer Data FeatureResults * @classdesc 数据集 SQL 查询参数类。 * @param {Object} options - 参数。 * @param {FilterParameter} options.queryParameter - 查询过滤条件参数。 * @param {Array.} options.datasetNames - 数据集集合中的数据集名称列表。 * @param {boolean} [options.returnContent=true] - 是否直接返回查询结果。 * @param {number} [options.fromIndex=0] - 查询结果的最小索引号。 * @param {number} [options.toIndex=19] - 查询结果的最大索引号。 * @param {string|number} [options.targetEpsgCode] - 动态投影的目标坐标系对应的 EPSG Code,使用此参数时,returnContent 参数需为 true。 * @param {Object} [options.targetPrj] - 动态投影的目标坐标系。使用此参数时,returnContent 参数需为 true。如:prjCoordSys={"epsgCode":3857}。当同时设置 targetEpsgCode 参数时,此参数不生效。 * @param {MetricsAggParameter|GeoHashGridAggParameter} [options.aggregations] - 聚合查询参数。该参数仅支持数据来源 Elasticsearch 服务的Supermap iServer的rest数据服务。 * @extends {GetFeaturesParametersBase} * @usage */ class GetFeaturesBySQLParameters extends GetFeaturesParametersBase { constructor(options) { super(options); /** * @member {string} GetFeaturesBySQLParameters.prototype.getFeatureMode * @description 数据集查询模式。 */ this.getFeatureMode = 'SQL'; /** * @member {FilterParameter} GetFeaturesBySQLParameters.prototype.queryParameter * @description 查询过滤条件参数类。 */ this.queryParameter = null; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.GetFeaturesBySQLParameters'; } /** * @function GetFeaturesBySQLParameters.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.getFeatureMode = null; if (me.queryParameter) { me.queryParameter.destroy(); me.queryParameter = null; } } /** * @function GetFeaturesBySQLParameters.prototype.toJsonParameters * @description 将 GetFeaturesBySQLParameters 对象转换为 JSON 字符串。 * @param {GetFeaturesBySQLParameters} params - 数据集 SQL 查询参数对象。 * @returns {string} 转化后的 JSON 字符串。 */ static toJsonParameters(params) { var paramsBySql = { datasetNames: params.datasetNames, getFeatureMode: 'SQL', queryParameter: params.queryParameter }; if (params.maxFeatures && !isNaN(params.maxFeatures)) { paramsBySql.maxFeatures = params.maxFeatures; } if (typeof params.hasGeometry === 'boolean') { paramsBySql.hasGeometry = params.hasGeometry; } if (params.aggregations) { paramsBySql.aggregations = params.aggregations; } if (params.targetEpsgCode) { paramsBySql.targetEpsgCode = params.targetEpsgCode; } if (!params.targetEpsgCode && params.targetPrj) { paramsBySql.targetPrj = params.targetPrj; } if (params.aggregations) { paramsBySql.aggregations = params.aggregations; } return Util.toJSON(paramsBySql); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFeaturesBySQLService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFeaturesBySQLService * @deprecatedclass SuperMap.GetFeaturesBySQLService * @constructs GetFeaturesBySQLService * @category iServer Data FeatureResults * @classdesc 数据服务中数据集 SQL 查询服务类。在一个或多个指定的图层上查询符合 SQL 条件的空间地物信息。 * @param {string} url - 服务地址。请求数据服务中数据集查询服务, * URL 应为:http://{服务器地址}:{服务端口号}/iserver/services/{数据服务名}/rest/data/;
* 例如:"http://localhost:8090/iserver/services/data-jingjin/rest/data/" * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {GetFeaturesServiceBase} * @example * var myGetFeaturesBySQLService = new GetFeaturesBySQLService(url, { * eventListeners: { * "processCompleted": GetFeaturesCompleted, * "processFailed": GetFeaturesError * } * }); * function getFeaturesCompleted(object){//todo}; * function getFeaturesError(object){//todo}; * @usage */ class GetFeaturesBySQLService extends GetFeaturesServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.GetFeaturesBySQLService"; } /** * @function GetFeaturesBySQLService.prototype.destroy * @override */ destroy() { super.destroy(); } /* * @function GetFeaturesBySQLService.prototype.getJsonParameters * @description 将查询参数转化为 JSON 字符串。 * 在本类中重写此方法,可以实现不同种类的查询(ID, SQL, Buffer, Geometry等)。 * @param {GetFeaturesBySQLParameters} params - 数据集SQL查询参数类。 * @returns {string} 转化后的 JSON 字符串。 */ getJsonParameters(params) { return GetFeaturesBySQLParameters.toJsonParameters(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetFieldsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetFieldsService * @deprecatedclass SuperMap.GetFieldsService * @category iServer Data Field * @classdesc 字段查询服务,支持查询指定数据集的中所有属性字段(field)的集合。 * @param {string} url - 服务地址。如访问World Map服务,只需将url设为:http://localhost:8090/iserver/services/data-world/rest/data 即可。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {string}options.datasource - 数据源名称。 * @param {string}options.dataset - 数据集名称。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {CommonServiceBase} * @example * var myService = new GetFieldsService(url, {eventListeners: { * "processCompleted": getFieldsCompleted, * "processFailed": getFieldsError * }, * datasource: "World", * dataset: "Countries" * }; * @usage */ class GetFieldsService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {string} GetFieldsService.prototype.datasource * @description 要查询的数据集所在的数据源名称。 */ this.datasource = null; /** * @member {string} GetFieldsService.prototype.dataset * @description 要查询的数据集名称。 */ this.dataset = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GetFieldsService"; } /** * @function GetFieldsService.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.datasource = null; me.dataset = null; } /** * @function GetFieldsService.prototype.processAsync * @description 执行服务,查询指定数据集的字段信息。 */ processAsync() { var me = this; me.url = Util.urlPathAppend(me.url,`datasources/${me.datasource}/datasets/${me.dataset}/fields`); me.request({ method: "GET", data: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/GetGridCellInfosParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetGridCellInfosParameters * @deprecatedclass SuperMap.GetGridCellInfosParameters * @category iServer Data Grid * @classdesc 数据服务栅格查询参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名称。 * @param {string} options.dataSourceName - 数据源名称。 * @param {number} options.X - 地理位置 X 轴。 * @param {number} options.Y - 地理位置 Y 轴。 * @usage */ class GetGridCellInfosParameters { constructor(options) { /** * @member {string} GetGridCellInfosParameters.prototype.datasetName * @description 数据集名称。 */ this.datasetName = null; /** * @member {string} GetGridCellInfosParameters.prototype.dataSourceName * @description 数据源名称。 */ this.dataSourceName = null; /** * @member {number} GetGridCellInfosParameters.prototype.X * @description 要查询的地理位置 X 轴。 */ this.X = null; /** * @member {number} GetGridCellInfosParameters.prototype.Y * @description 要查询的地理位置 Y 轴。 */ this.Y = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.GetGridCellInfosParameters"; } /** * @function GetGridCellInfosParameters.prototype.destroy * @description 释放资源,将引用的资源属性置空。 */ destroy() { var me = this; me.datasetName = null; me.dataSourceName = null; me.X = null; me.Y = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/GetGridCellInfosService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetGridCellInfosService * @deprecatedclass SuperMap.GetGridCellInfosService * @category iServer Data Grid * @classdesc 数据栅格查询服务,支持查询指定地理位置的栅格信息。 * @param {string} url - 服务地址。例如: http://localhost:8090/iserver/services/data-jingjin/rest/data * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。
* @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {CommonServiceBase} * @example * var myService = new GetGridCellInfosService(url, {eventListeners: { * "processCompleted": queryCompleted, * "processFailed": queryError * } * }); * @usage */ class GetGridCellInfosService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {string} GetGridCellInfosService.prototype.datasetName * @description 数据集名称。 */ this.datasetName = null; /** * @member {string} GetGridCellInfosService.prototype.dataSourceName * @description 数据源名称。 */ this.dataSourceName = null; /** * @member {string} GetGridCellInfosService.prototype.datasetType * @description 数据集类型。 */ this.datasetType = null; /** * @member {number} GetGridCellInfosService.prototype.X * @description 要查询的地理位置X轴 */ this.X = null; /** * @member {number} GetGridCellInfosService.prototype.Y * @description 要查询的地理位置Y轴 */ this.Y = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GetGridCellInfosService"; } /** * @function GetGridCellInfosService.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.X = null; me.Y = null; me.datasetName = null; me.dataSourceName = null; me.datasetType = null; } /** * @function GetGridCellInfosService.prototype.processAsync * @description 执行服务,查询数据集信息。 * @param {GetGridCellInfosParameters} params - 查询参数。 */ processAsync(params) { if (!(params instanceof GetGridCellInfosParameters)) { return; } Util.extend(this, params); var me = this; me.url = Util.urlPathAppend(me.url,`datasources/${me.dataSourceName}/datasets/${me.datasetName}`); me.queryRequest(me.getDatasetInfoCompleted, me.getDatasetInfoFailed); } /** * @function GetGridCellInfosService.prototype.queryRequest * @description 执行服务,查询。 * @callback {function} successFun - 成功后执行的函数。 * @callback {function} failedFunc - 失败后执行的函数。 */ queryRequest(successFun, failedFunc) { var me = this; me.request({ method: "GET", data: null, scope: me, success: successFun, failure: failedFunc }); } /** * @function GetGridCellInfosService.prototype.getDatasetInfoCompleted * @description 数据集查询完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ getDatasetInfoCompleted(result) { var me = this; result = Util.transformResult(result); me.datasetType = result.datasetInfo.type; me.queryGridInfos(); } /** * @function GetGridCellInfosService.prototype.queryGridInfos * @description 执行服务,查询数据集栅格信息信息。 */ queryGridInfos() { var me = this; me.url = Util.urlPathAppend(me.url, me.datasetType == 'GRID' ? 'gridValue' : 'imageValue'); if (me.X != null && me.Y != null) { me.url = Util.urlAppend(me.url, `x=${me.X}&y=${me.Y}`); } me.queryRequest(me.serviceProcessCompleted, me.serviceProcessFailed); } /** * @function GetGridCellInfosService.prototype.getDatasetInfoFailed * @description 数据集查询失败,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ getDatasetInfoFailed(result) { var me = this; me.serviceProcessFailed(result); } } ;// CONCATENATED MODULE: ./src/common/iServer/Theme.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class CommonTheme * @aliasclass Theme * @deprecatedclass SuperMap.Theme * @category iServer Map Theme * @classdesc 专题图基类。 * @param {string} type - 专题图类型。 * @param {Object} options - 可选参数。 * @param {ThemeMemoryData} [options.memoryData] - 专题图内存数据。 * @usage */ class Theme { constructor(type, options) { if (!type) { return this; } /** * @member {ThemeMemoryData} CommonTheme.prototype.memoryData * @description 专题图内存数据。
* 用内存数据制作专题图的方式与表达式制作专题图的方式互斥,前者优先级较高。 * 第一个参数代表专题值,即数据集中用来做专题图的字段或表达式的值;第二个参数代表外部值。在制作专题图时,会用外部值代替专题值来制作相应的专题图。 */ this.memoryData = null; /** * @member {string} CommonTheme.prototype.type * @description 专题图类型。 */ this.type = type; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.Theme"; } /** * @function CommonTheme.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.memoryData) { me.memoryData.destroy(); me.memoryData = null; } me.type = null; } /** * @function CommonTheme.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { //return 子类实现 return; } } ;// CONCATENATED MODULE: ./src/common/iServer/ServerTextStyle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ServerTextStyle * @deprecatedclass SuperMap.ServerTextStyle * @category iServer Map Theme * @classdesc 服务端文本风格类。该类用于定义文本风格的相关属性。 * @param {Object} options - 可选参数。 * @param {TextAlignment} [options.align=TextAlignment.BASELINECENTER] - 文本的对齐方式。 * @param {ServerColor} [options.backColor] - 文本的背景色。默认 backColor = new ServerColor(255, 255, 255)。 * @param {ServerColor} [options.foreColor] - 文本的前景色。默认 foreColor = new ServerColor(0, 0, 0)。 * @param {boolean} [options.backOpaque=false] - 文本背景是否不透明。 * @param {boolean} [options.sizeFixed=true] - 文本大小是否固定。 * @param {number} [options.fontHeight=6] - 文本字体的高度。 * @param {number} [options.fontWidth=0] - 文本字体的宽度。 * @param {number} [options.fontWeight=400] - 文本字体的磅数。 * @param {string} [options.fontName='Times New Roman'] - 文本字体的名称。 * @param {boolean} [options.bold=false] - 文本是否为粗体字。 * @param {boolean} [options.italic=false] - 文本是否采用斜体。 * @param {number} [options.italicAngle=0] - 字体倾斜角度。 * @param {boolean} [options.shadow=false] - 文本是否有阴影。 * @param {boolean} [options.strikeout=false] - 文本字体是否加删除线。 * @param {boolean} [options.outline=false] - 是否以轮廓的方式来显示文本的背景。 * @param {number} [options.opaqueRate=0] - 注记文字的不透明度。 * @param {boolean} [options.underline=false] - 文本字体是否加下划线。 * @param {number} [options.rotation=0.0] - 文本旋转的角度。 * @usage */ class ServerTextStyle { constructor(options) { /** * @member {TextAlignment} [ServerTextStyle.prototype.align= TextAlignment.BASELINECENTER] * @description 文本的对齐方式。 */ this.align = TextAlignment.BASELINECENTER; /** * @member {ServerColor} [ServerTextStyle.prototype.backColor=(255, 255, 255)] * @description 文本的背景色。 */ this.backColor = new ServerColor(255, 255, 255); /** * @member {ServerColor} [ServerTextStyle.prototype.foreColor=(0, 0, 0)] * @description 文本的前景色。 */ this.foreColor = new ServerColor(0, 0, 0); /** * @member {boolean} [ServerTextStyle.prototype.backOpaque=false] * @description 文本背景是否不透明。true 表示文本背景不透明。 */ this.backOpaque = false; /** * @member {boolean} [ServerTextStyle.prototype.sizeFixed=true] * @description 文本大小是否固定。设置为 true,表示图片为固定像素大小,具体大小请参考 fontHeight。当设为 false 时,图片会随着地图缩放而缩放。 */ this.sizeFixed = true; /** * @member {number} [ServerTextStyle.prototype.fontHeight=6] * @description 文本字体的高度,单位与 sizeFixed 有关,当 sizeFixed 为 False 时,即非固定文本大小时使用地图坐标单位, * 如地理坐标系下的地图中单位为度;当 sizeFixed 为 True 时,单位为毫米(mm)。 */ this.fontHeight = 6; /** * @member {number} [ServerTextStyle.prototype.fontWidth=0] * @description 文本字体的宽度。字体的宽度以英文字符为标准,由于一个中文字符相当于两个英文字符。 */ this.fontWidth = 0; /** * @member {number} [ServerTextStyle.prototype.fontWeight=400] * @description 文本字体的磅数。表示粗体的具体数值。取值范围为从0-900之间的整百数。 */ this.fontWeight = 400; /** * @member {string} [ServerTextStyle.prototype.fontName="Times New Roman"] * @description 文本字体的名称。 */ this.fontName = "Times New Roman"; /** * @member {boolean} [ServerTextStyle.prototype.bold=false] * @description 文本是否为粗体字。true 表示为粗体。false 表示文本不是粗体字。 */ this.bold = false; /** * @member {boolean} [ServerTextStyle.prototype.italic=false] * @description 文本是否采用斜体。true 表示采用斜体。 */ this.italic = false; /** * @member {number} [ServerTextStyle.prototype.italicAngle=0] * @description 字体倾斜角度。正负度之间,以度为单位,精确到0.1度。当倾斜角度为0度,为系统默认的字体倾斜样式。 * 正负度是指以纵轴为起始零度线,其纵轴左侧为正,右侧为负。允许的最大角度为60,最小-60。大于60按照60处理,小于-60按照-60处理。目前只对标签专题图有效。 */ this.italicAngle = 0; /** * @member {boolean} [ServerTextStyle.prototype.shadow=false] * @description 文本是否有阴影。true 表示给文本增加阴影。false 表示文本没有阴影。 */ this.shadow = false; /** * @member {boolean} [ServerTextStyle.prototype.strikeout=false] * @description 文本字体是否加删除线。true 表示加删除线。false 表示文本字体不加删除线。 */ this.strikeout = false; /** * @member {boolean} [ServerTextStyle.prototype.outline=false] * @description 是否以轮廓的方式来显示文本的背景。true 表示以轮廓的方式来显示文本的背景。false 表示不以轮廓的方式来显示文本的背景。 */ this.outline = false; /** * @member {number} [ServerTextStyle.prototype.opaqueRate=0] * @description 注记文字的不透明度。不透明度的范围为0-100。0表示透明。 */ this.opaqueRate = 0; /** * @member {boolean} [ServerTextStyle.prototype.underline=false] * @description 文本字体是否加下划线。true 表示加下划线。 */ this.underline = false; /** * @member {number} [ServerTextStyle.prototype.rotation=0.0] * @description 文本旋转的角度。逆时针方向为正方向,单位为度,精确到0.1度。 */ this.rotation = 0.0; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ServerTextStyle"; } /** * @function ServerTextStyle.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.align = null; if (me.backColor) { me.backColor.destroy(); me.backColor = null; } if (me.foreColor) { me.foreColor.destroy(); me.foreColor = null; } me.backOpaque = null; me.sizeFixed = null; me.fontHeight = null; me.fontWidth = null; me.fontWeight = null; me.fontName = null; me.bold = null; me.italic = null; me.italicAngle = null; me.shadow = null; me.strikeout = null; me.outline = null; me.opaqueRate = null; me.underline = null; me.rotation = null; } /** * @function ServerTextStyle.fromObj * @description 从传入对象获服务端文本风格类。 * @param {Object} obj - 传入对象 * @returns {ServerTextStyle} 返回服务端文本风格对象 */ static fromObj(obj) { var res = new ServerTextStyle(obj); Util.copy(res, obj); res.backColor = ServerColor.fromJson(obj.backColor); res.foreColor = ServerColor.fromJson(obj.foreColor); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeLabelItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeLabelItem * @deprecatedclass SuperMap.ThemeLabelItem * @category iServer Map Theme * @classdesc 分段标签专题图的子项。标签专题图用专题值对点、线、面等对象做标注。 * 值得注意的是,分段标签专题图允许用户通过 rangeExpression 字段指定用于分段的数值型字段, * 同一范围段内的标签具有相同的显示风格,其中每一个范围段就是一个专题图子项, * 每一个子项都具有其名称、风格、起始值和终止值。注意:每个分段所表示的范围为 [Start, End)。例如:标签专题图的分段点有两个子项, * 他们所代表的分段区间分别为[0,5),[5,10)。那么需要分别设置 ThemeLabelItem[0].start=0, * ThemeLabelItem[0].end=5,SuperMap.ThemeLabelItem[1].start=5,SuperMap.ThemeLabelItem[1].end=10。 * @param {Object} options - 可选参数。 * @param {string} [options.caption] - 子项的名称。 * @param {number} [options.end=0] - 子项的终止值。 * @param {number} [options.start=0] - 子项的分段起始值。 * @param {boolean} [options.visible=true] - 子项是否可见。 * @param {ServerTextStyle} [options.style] - 子项文本的显示风格。 * @usage */ class ThemeLabelItem { constructor(options) { /** * @member {string} [ThemeLabelItem.prototype.caption] * @description 标签专题子项的标题。 */ this.caption = null; /** * @member {number} [ThemeLabelItem.prototype.end=0] * @description 标签专题图子项的终止值。如果该子项是分段中最后一个子项,那么该终止值就是分段的最大值; * 如果不是最后一项,该终止值必须与其下一子项的起始值相同,否则系统抛出异常。 */ this.end = 0; /** * @member {number} [ThemeLabelItem.prototype.start=0] * @description 标签专题图子项的分段起始值。如果该子项是分段中第一项,那么该起始值就是分段的最小值; * 如果该子项的序号大于等于 1 的时候,该起始值必须与前一子项的终止值相同,否则系统会抛出异常。 */ this.start = 0; /** * @member {boolean} [ThemeLabelItem.prototype.visible=true] * @description 标签专题图子项是否可见。如果标签专题图子项可见,则为 true,否则为 false。 */ this.visible = true; /** * @member {ServerTextStyle} ThemeLabelItem.prototype.style * @description 标签专题图子项文本的显示风格。各种风格的优先级从高到低为:
* uniformMixedStyle(标签文本的复合风格),ThemeLabelItem.style(分段子项的文本风格),uniformStyle(统一文本风格)。 */ this.style = new ServerTextStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeLabelItem"; } /** * @function ThemeLabelItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.caption = null; me.end = null; me.start = null; if (me.style) { me.style.destroy(); me.style = null; } me.visible = null; } /** * @function ThemeLabelItem.fromObj * @description 从传入对象获取分段标签专题图的子项类。 * @param {Object} obj - 传入对象。 * @returns {ThemeLabelItem} ThemeLabelItem 对象。 */ static fromObj(obj) { if (!obj) { return; } var t = new ThemeLabelItem(); Util.copy(t, obj); return t; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeUniqueItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeUniqueItem * @deprecatedclass SuperMap.ThemeUniqueItem * @category iServer Map Theme * @classdesc 单值专题图子项类。单值专题图是将专题值相同的要素归为一类,为每一类设定一种渲染风格,其中每一类就是一个专题图子项。比如,利用单值专题图制作行政区划图,Name 字段代表省/直辖市名,该字段用来做专题变量,如果该字段的字段值总共有 5 种不同值,则该行政区划图有 5 个专题图子项。 * @param {Object} options - 参数。 * @param {string} options.unique - 子项的单值字段。 * @param {string} [options.caption] - 子项的标题。 * @param {ServerStyle} [options.style] - 子项的风格。 * @param {boolean} [options.visible=true] - 子项是否可见。 * @usage */ class ThemeUniqueItem { constructor(options) { /** * @member {string} [ThemeUniqueItem.prototype.caption] * @description 单值专题图子项的标题。 */ this.caption = null; /** * @member {ServerStyle} [ThemeUniqueItem.prototype.style] * @description 单值专题图子项的显示风格。 */ this.style = new ServerStyle(); /** * @member {string} ThemeUniqueItem.prototype.unique * @description 单值专题图子项的值,可以为数字、字符串等。 */ this.unique = null; /** * @member {boolean} [ThemeUniqueItem.prototype.visible=true] * @description 单值专题图子项的可见性。 */ this.visible = true; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeUniqueItem"; } /** * @function ThemeUniqueItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.caption = null; me.unique = null; if (me.style) { me.style.destroy(); me.style = null; } me.visible = null; } /** * @function ThemeUniqueItem.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj = Util.copyAttributes(obj, this); if (obj.style) { if (obj.style.toServerJSONObject) { obj.style = obj.style.toServerJSONObject(); } } return obj; } /** * @function ThemeUniqueItem.fromObj * @description 从传入对象获取单值专题图子项类。 * @param {Object} obj - 传入对象。 * @returns {ThemeUniqueItem} ThemeUniqueItem 对象。 */ static fromObj(obj) { var res = new ThemeUniqueItem(); Util.copy(res, obj); res.style = ServerStyle.fromJson(obj.style); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeOffset.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeOffset * @deprecatedclass SuperMap.ThemeOffset * @category iServer Map Theme * @classdesc 专题图中文本或符号相对于要素内点的偏移量设置类。 * 通过该类可以设置专题图中标记文本或符号的偏移量以及偏移量是否随地图缩放而改变。 * @param {Object} options - 可选参数。 * @param {boolean} [options.offsetFixed=false] - 当前专题图是否固定标记文本或符号的偏移量。 * @param {string} [options.offsetX='0.0'] - 专题图中文本或符号相对于要素内点的水平偏移量。 * @param {string} [options.offsetY='0.0'] - 专题图中文本或符号相对于要素内点的垂直偏移量。 * @usage */ class ThemeOffset { constructor(options) { /** * @member {boolean} [ThemeOffset.prototype.offsetFixed=false] * @description 当前专题图是否固定标记文本或符号的偏移量。所谓固定偏移量,指文本或符号的偏移量不随地图的缩放而变化。 */ this.offsetFixed = false; /** * @member {string} [ThemeOffset.prototype.offsetX=0.0] * @description 专题图中文本或符号相对于要素内点的水平偏移量。偏移量的单位为地图单位。 * 该偏移量的值为一个常量值或者字段表达式所表示的值,即如果字段表达式为 SmID,其中 SmID = 2,那么水平偏移量为2。 */ this.offsetX = "0.0"; /** * @member {string} [ThemeOffset.prototype.offsetY=0.0] * @description 专题图中文本或符号相对于要素内点的垂直偏移量。偏移量的单位为地图单位。 * 该偏移量的值为一个常量值或者字段表达式所表示的值,即如果字段表达式为 SmID,其中 SmID = 2,那么垂直偏移量为2。 */ this.offsetY = "0.0"; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeOffset"; } /** * @function ThemeOffset.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.offsetFixed = null; me.offsetX = null; me.offsetY = null; } /** * @function ThemeOffset.fromObj * @description 从传入对象获取专题图中文本或符号相对于要素内点的偏移量设置类。 * @param {Object} obj - 传入对象。 * @returns {ThemeOffset} ThemeOffset 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeOffset(); Util.copy(res, obj); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/LabelMixedTextStyle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LabelMixedTextStyle * @deprecatedclass SuperMap.LabelMixedTextStyle * @category iServer Map Theme * @classdesc 标签文本复合风格类。 * 该类主要用于对标签专题图中标签的文本内容进行风格设置。通过该类用户可以使标签的文字显示不同的风格,比如文本 “喜马拉雅山”,通过本类可以将前三个字用红色显示,后两个字用蓝色显示。对同一文本设置不同的风格实质上是对文本的字符进行分段,同一分段内的字符具有相同的显示风格。对字符分段有两种方式,一种是利用分隔符对文本进行分段;另一种是根据分段索引值进行分段:
* 1.利用分隔符对文本进行分段: 比如文本 “5&109” 被分隔符 “&” 分为 “5” 和 “109” 两部分, * 在显示时,“5” 和分隔符 “&” 使用同一个风格,字符串 “109” 使用相同的风格。
* 2.利用分段索引值进行分段: 文本中字符的索引值是以0开始的整数,比如文本 “珠穆朗玛峰”, * 第一个字符(“珠”)的索引值为 0,第二个字符(“穆”)的索引值为 1,以此类推;当设置分段索引值为 1,3,4,9 时, * 字符分段范围相应的就是 (-∞,1),[1,3),[3,4),[4,9),[9,+∞),可以看出索引号为 0 的字符(即“珠” )在第一个分段内, * 索引号为 1,2 的字符(即“穆”、“朗”)位于第二个分段内,索引号为 3 的字符(“玛”)在第三个分段内,索引号为 4 的字符(“峰”)在第四个分段内,其余分段中没有字符。 * @param {Object} options - 可选参数。 * @param {ServerTextStyle} [options.defaultStyle] - 默认的文本复合风格。 * @param {string} [options.separator] - 文本的分隔符。 * @param {boolean} [options.separatorEnabled=false] - 文本的分隔符是否有效。 * @param {Array.} [options.splitIndexes] - 分段索引值,分段索引值用来对文本中的字符进行分段。 * @param {Array.} [options.styles] - 文本样式集合。 * @usage */ class LabelMixedTextStyle { constructor(options) { /** * @member {ServerTextStyle} LabelMixedTextStyle.prototype.defaultStyle * @description 默认的文本复合风格,即 ServerTextStyle 各字段的默认值。 */ this.defaultStyle = null; /** * @member {string} LabelMixedTextStyle.prototype.separator * @description 文本的分隔符,分隔符的风格与前一个字符的风格一样。文本的分隔符是一个将文本分割开的符号, * 比如文本 “5_109” 被 “ _ ” 分隔为 “5” 和 “109” 两部分,假设有风格数组:style1、style2。 * 在显示时,“5” 和分隔符 “ _ ” 使用 Style1 风格渲染,字符串 “109” 使用 Style2 的风格。 */ this.separator = null; /** * @member {boolean} [LabelMixedTextStyle.prototype.separatorEnabled=false] * @description 文本的分隔符是否有效。分隔符有效时利用分隔符对文本进行分段;无效时根据文本中字符的位置进行分段。 * 分段后,同一分段内的字符具有相同的显示风格。 */ this.separatorEnabled = false; /** * @member {Array.} LabelMixedTextStyle.prototype.splitIndexes * @description 分段索引值,分段索引值用来对文本中的字符进行分段。 * 文本中字符的索引值是以 0 开始的整数,比如文本“珠穆朗玛峰”,第一个字符(“珠”)的索引值为0,第二个字符(“穆”)的索引值为 1, * 以此类推;当设置分段索引值数组为 [1,3,4,9] 时,字符分段范围相应的就是 (-∞,1),[1,3),[3,4),[4,9),[9,+∞), * 可以看出索引号为 0 的字符(即 “珠”)在第一个分段内,索引号为 1,2 的字符(即 “穆”、“朗”)位于第二个分段内, * 索引号为 3 的字符(“玛”)在第三个分段内,索引号为 4 的字符(“峰”)在第四个分段内,其余分段中没有字符。 */ this.splitIndexes = null; /** * @member {Array.} LabelMixedTextStyle.prototype.styles * @description 文本样式集合。文本样式集合中的样式根据索引与不同分段一一对应, * 如果有分段没有风格对应则使用 defaultStyle。 */ this.styles = new ServerTextStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.LabelMixedTextStyle" } /** * @function LabelMixedTextStyle.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.defaultStyle) { me.defaultStyle.destroy(); me.defaultStyle = null; } me.separator = null; me.separatorEnabled = null; if (me.splitIndexes) { me.splitIndexes = null; } if (me.styles) { for (var i = 0, styles = me.styles, len = styles.length; i < len; i++) { styles[i].destroy(); } me.styles = null; } } /** * @function LabelMixedTextStyle.fromObj * @description 从传入对象获取标签文本复合风格类。 * @param {Object} obj - 传入对象。 * @returns {LabelMixedTextStyle} 返回新的 LabelMixedTextStyle 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new LabelMixedTextStyle(); var stys = obj.styles; Util.copy(res, obj); res.defaultStyle = new ServerTextStyle(obj.defaultStyle); if (stys) { res.styles = []; for (var i = 0, len = stys.length; i < len; i++) { res.styles.push(new ServerTextStyle(stys[i])); } } return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeLabelText.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeLabelText * @deprecatedclass SuperMap.ThemeLabelText * @category iServer Map Theme * @classdesc 标签中文本风格类。 * 通过该类可以设置标签中的文本字体大小和显示风格。 * @param {Object} options - 参数。 * @param {number} [options.maxTextHeight=0] - 标签中文本的最大高度。 * @param {number} [options.maxTextWidth=0] - 标签中文本的最大宽度。 * @param {number} [options.minTextHeight=0] - 标签中文本的最小高度。 * @param {number} [options.minTextWidth=0] - 标签中文本的最小宽度。 * @param {ServerTextStyle} [options.uniformStyle] - 统一文本风格。 * @param {LabelMixedTextStyle} [options.uniformMixedStyle] - 标签专题图统一的文本复合风格。 * @usage */ class ThemeLabelText { constructor(options) { /** * @member {number} [ThemeLabelText.prototype.maxTextHeight=0] * @description 标签中文本的最大高度。当标签文本不固定大小时,即 ServerTextStyle.sizeFixed = false 有效, * 当放大后的文本高度超过最大高度之后就不再放大。高度单位为毫米。 */ this.maxTextHeight = 0; /** * @member {number} [ThemeLabelText.prototype.maxTextWidth=0] * @description 标签中文本的最大宽度。当标签文本不固定大小时,即 ServerTextStyle.sizeFixed = false 有效, * 当放大后的文本宽度超过最大高度之后就不再放大。宽度单位为毫米。 */ this.maxTextWidth = 0; /** * @member {number} [ThemeLabelText.prototype.minTextHeight=0] * @description 标签中文本的最小高度。当标签文本不固定大小时,即 ServerTextStyle.sizeFixed = false 有效, * 当缩小后的文本高度小于最小高度之后就不再缩小。高度单位为毫米。 */ this.minTextHeight = 0; /** * @member {number} [ThemeLabelText.prototype.minTextWidth=0] * @description 标签中文本的最小宽度。当标签文本不固定大小时,即 ServerTextStyle.sizeFixed = false 有效, * 当缩小后的文本宽度小于最小宽度之后就不再缩小。宽度单位为毫米。 */ this.minTextWidth = 0; /** * @member {ServerTextStyle} [ThemeLabelText.prototype.uniformStyle] * @description 统一文本风格。当标签专题图子项的个数大于等于1时, * uniformStyle 不起作用,各标签的风格使用子项中设置的风格。各种风格的优先级从高到低为:uniformMixedStyle(标签文本的复合风格), * ThemeLabelItem.style(分段子项的文本风格),uniformStyle(统一文本风格)。 */ this.uniformStyle = new ServerTextStyle(); /** *@member {LabelMixedTextStyle} [ThemeLabelText.prototype.uniformMixedStyle] *@description 标签专题图统一的文本复合风格。通过该类可以使同一个标签中的文字使用多种风格显示。各种风格的优先级从高到低为:uniformMixedStyle(标签文本的复合风格), * ThemeLabelItem.style(分段子项的文本风格),uniformStyle(统一文本风格)。 */ this.uniformMixedStyle = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeLabelText"; } /** * @function ThemeLabelText.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.maxTextHeight = null; me.maxTextWidth = null; me.minTextHeight = null; me.minTextWidth = null; if (me.uniformStyle) { me.uniformStyle.destroy(); me.uniformStyle = null; } if (me.uniformMixedStyle) { me.uniformMixedStyle.destroy(); me.uniformMixedStyle = null; } } /** * @function ThemeLabelText.fromObj * @description 从传入对象获取标签中文本风格类。 * @param {Object} obj - 传入对象。 * @returns {ThemeLabelText} ThemeLabelText 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeLabelText(); Util.copy(res, obj); res.uniformStyle = ServerTextStyle.fromObj(obj.uniformStyle); res.uniformMixedStyle = LabelMixedTextStyle.fromObj(obj.uniformMixedStyle); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeLabelAlongLine.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeLabelAlongLine * @deprecatedclass SuperMap.ThemeLabelAlongLine * @category iServer Map Theme * @classdesc 标签沿线标注样式类。 * @param {Object} options - 可选参数。 * @param {boolean} [options.isAlongLine=true] - 是否沿线显示文本。 * @param {AlongLineDirection} [options.alongLineDirection=AlongLineDirection.LB_TO_RT] - 标签沿线标注方向。 * @param {boolean} [options.angleFixed=false] - 当沿线显示文本时,是否将文本角度固定。 * @param {boolean} [options.repeatedLabelAvoided=false] - 沿线循环标注时是否避免标签重复标注。 * @param {boolean} [options.repeatIntervalFixed=false] - 循环标注间隔是否固定。 * @param {number} [options.labelRepeatInterval=0] - 沿线且循环标注时循环标注的间隔。 * @usage */ class ThemeLabelAlongLine { constructor(options) { /** * @member {boolean} [ThemeLabelAlongLine.prototype.isAlongLine=true] * @description 是否沿线显示文本。true 表示沿线显示文本,false 表示正常显示文本。 */ this.isAlongLine = true; /** * @member {AlongLineDirection} [ThemeLabelAlongLine.prototype.alongLineDirection=AlongLineDirection.LB_TO_RT] * @description 标签沿线标注方向。 */ this.alongLineDirection = AlongLineDirection.LB_TO_RT; /** * @member {boolean} [ThemeLabelAlongLine.prototype.angleFixed=false] * @description 当沿线显示文本时,是否将文本角度固定。true 表示按固定文本角度显示文本,false 表示按照沿线角度显示文本。 * 如果固定角度,则所有标签均按所设置的文本风格中字体的旋转角度来显示,不考虑沿线标注的方向; * 如果不固定角度,在显示标签时会同时考虑字体的旋转角度和沿线标注的方向。 */ this.angleFixed = false; /** * @member {boolean} ThemeLabelAlongLine.prototype.repeatedLabelAvoided * @description 沿线循环标注时是否避免标签重复标注。 */ this.repeatedLabelAvoided = false; /** * @member {boolean} [ThemeLabelAlongLine.prototype.repeatIntervalFixed=false] * @description 循环标注间隔是否固定。true 表示使用固定循环标注间隔,即使用逻辑坐标来显示循环标注间隔; * false 表示循环标注间隔随地图的缩放而变化,即使用地理坐标来显示循环标注间隔。 */ this.repeatIntervalFixed = false; /** * @member {number} [ThemeLabelAlongLine.prototype.labelRepeatInterval=0] * @description 沿线且循环标注时循环标注的间隔。长度的单位与地图的地理单位一致。只有设定 RepeatedLabelAvoided 为 true * 的时候,labelRepeatInterval 属性才有效。 */ this.labelRepeatInterval = 0; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeLabelAlongLine"; } /** * @function ThemeLabelAlongLine.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.isAlongLine = null; me.alongLineDirection = null; me.angleFixed = null; me.repeatedLabelAvoided = null; me.repeatIntervalFixed = null; me.labelRepeatInterval = null; } /** * @function ThemeLabelAlongLine.fromObj * @description 从传入对象获取标签沿线标注样式类。 * @param {Object} obj - 传入对象。 * @returns {ThemeLabelAlongLine} ThemeLabelAlongLine 对象。 */ static fromObj(obj) { if (!obj) { return; } var t = new ThemeLabelAlongLine(); Util.copy(t, obj); return t; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeLabelBackground.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeLabelBackground * @deprecatedclass SuperMap.ThemeLabelBackground * @category iServer Map Theme * @classdesc 标签背景风格类。通过该类可以设置标签的背景形状和风格。 * @param {Object} options - 可选参数。 * @param {LabelBackShape} [options.labelBackShape=LabelBackShape.NONE] - 标签专题图中标签背景的形状枚举类。 * @param {ServerStyle} [options.backStyle] - 标签专题图中标签背景风格。 * @usage */ class ThemeLabelBackground { constructor(options) { /** * @member {LabelBackShape} [ThemeLabelBackground.prototype.labelBackShape=LabelBackShape.NONE] * @description 标签专题图中标签背景风格。当背景形状 * labelBackShape 属性设为 NONE(即无背景形状)时,backStyle 属性无效。 */ this.labelBackShape = LabelBackShape.NONE; /** * @member {ServerStyle} [ThemeLabelBackground.prototype.backStyle] * @description 标签专题图中标签背景的形状枚举类。背景类型可以是矩形、圆角矩形、菱形、椭圆形、三角形和符号等,即不使用任何的形状作为标签的背景。 */ this.backStyle = new ServerStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeLabelBackground"; } /** * @function ThemeLabelBackground.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.labelBackShape = null; if (me.backStyle) { me.backStyle.destroy(); me.backStyle = null; } } /** * @function ThemeLabelBackground.fromObj * @description 从传入对象获取标签背景风格类。 * @param {Object} obj - 传入对象。 * @returns {ThemeLabelBackground} ThemeLabelBackground 对象。 */ static fromObj(obj) { if (!obj) { return; } var t = new ThemeLabelBackground(); t.labelBackShape = obj.labelBackShape; t.backStyle = ServerStyle.fromJson(obj.backStyle); return t; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeLabel.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeLabel * @deprecatedclass SuperMap.ThemeLabel * @category iServer Map Theme * @classdesc 标签专题图类。 * @extends CommonTheme * @param {Object} options - 参数。 * @param {Array.} options.items - 子项数组。 * @param {string} options.labelExpression - 标注字段表达式。 * @param {Array.} options.matrixCells - 矩阵标签元素数组。 * @param {ThemeLabelAlongLine} [options.alongLine] - 标签沿线标注方向样式类。 * @param {ThemeLabelBackground} [options.background] - 标签的背景风格类。 * @param {LabelOverLengthMode} [options.labelOverLengthMode=LabelOverLengthMode.NONE] - 超长标签的处理模式枚举类。 * @param {number} [options.maxLabelLength=256] - 标签在每一行显示的最大长度。 * @param {number} [options.numericPrecision=0] - 通过该字段设置其显示的精度。 * @param {ThemeOffset} [options.offset] - 指定标签专题图中标记文本相对于要素内点的偏移量对象。 * @param {boolean} [options.overlapAvoided=true] - 是否允许以文本避让方式显示文本。 * @param {string} [options.rangeExpression] - 制作分段标签专题的分段字段或字段表达式。 * @param {boolean} [options.smallGeometryLabeled=false] - 是否显示长度大于被标注对象本身长度的标签。 * @param {ThemeLabelText} options.text - 标签中文本风格。 * @param {number} [options.textSpace=0] - 沿线标注,相邻两个文字之间的间距,单位当前设置的字高。 * @param {ThemeMemoryData} [options.memoryData] - 专题图内存数据。 * @usage */ class ThemeLabel extends Theme { constructor(options) { super("LABEL", options); /** * @member {ThemeLabelAlongLine} [ThemeLabel.prototype.alongLine] * @description 标签沿线标注方向样式类。 * 在该类中可以设置标签是否沿线标注以及沿线标注的多种方式。沿线标注属性只适用于线数据集专题图。 */ this.alongLine = new ThemeLabelAlongLine(); /** * @member {ThemeLabelBackground} [ThemeLabel.prototype.background] * @description 标签专题图中标签的背景风格类。通过该字段可以设置标签的背景形状和风格。 */ this.background = new ThemeLabelBackground(); /** * @member {Array.} [ThemeLabel.prototype.items] * @description 分段标签专题图的子项数组。分段标签专题图使用 rangeExpression * 指定数字型的字段作为分段数据,items 中的每个子对象的 [start,end) 分段值必须来源于属性 rangeExpression 的字段值。每个子项拥有自己的风格。 */ this.items = null; /** * @member {Array.} ThemeLabel.prototype.uniqueItems * @description 单值标签专题图子项数组。单值标签专题图使用 uniqueExpression单值标签专题图子项集合。 */ this.uniqueItems = null; /** * @member {string} ThemeLabel.prototype.labelExpression * @description 标注字段表达式。系统将 labelExpression 对应的字段或字段表达式的值以标签的形式显示在图层中。 */ this.labelExpression = null; /** * @member {LabelOverLengthMode} [ThemeLabel.prototype.labelOverLengthMode=LabelOverLengthMode.NONE] - 标签专题图中超长标签的处理模式枚举类。 * @description 对于标签的长度超过设置的标签最大长度 maxLabelLength 时称为超长标签。 */ this.labelOverLengthMode = LabelOverLengthMode.NONE; /** * @member {Array.} ThemeLabel.prototype.matrixCells * @description 矩阵标签元素数组,用于制作矩阵标签专题图。 * 数组中可以放置符号类型的矩阵标签元素和图片类型的矩阵标签元素。 */ this.matrixCells = null; /** * @member {number} [ThemeLabel.prototype.maxLabelLength=256] * @description 标签在每一行显示的最大长度,一个中文为两个字符。 * 如果超过最大长度,可以采用两种方式来处理,一种是换行的模式进行显示,另一种是以省略号方式显示。单位为字符。 */ this.maxLabelLength = 256; /** * @member {number} [ThemeLabel.prototype.numericPrecision=0] * @description 如果显示的标签内容为数字,通过该字段设置其显示的精度。例如标签对应的数字是8071.64529347, * 如果该属性为0时,显示8071;为1时,显示8071.6;为3时,则是8071.645。 */ this.numericPrecision = 0; /** * @member {ThemeOffset} [ThemeLabel.prototype.offset] * @description 用于设置标签专题图中标记文本相对于要素内点的偏移量对象。 */ this.offset = new ThemeOffset(); /** * @member {boolean} [ThemeLabel.prototype.overlapAvoided=true] * @description 是否允许以文本避让方式显示文本。true 表示自动避免文本叠盖。只针对该标签专题图层中的文本数据。 * 在标签重叠度很大的情况下,即使使用自动避让功能,可能也无法完全避免标签重叠现象。 */ this.overlapAvoided = true; /** * @member {string} ThemeLabel.prototype.rangeExpression * @description 制作分段标签专题的分段字段或字段表达式。该表达式对应的字段(或者字段表达式)的值应该为数值型。 * 该字段与 items 分段子项联合使用,每个子项的起始值 [start,end)来源于 rangeExpression 字段值。 * 最后 labelExpression 指定的标签字段(标签专题图要显示的具体内容)会根据分段子项的风格进行分段显示。 */ this.rangeExpression = null; /** * @member {string} ThemeLabel.prototype.uniqueExpression * @description 用于制作单值专题图的字段或字段表达式。 * 该字段值的数据类型可以为数值型或字符型。如果设置字段表达式,只能是相同数据类型字段间的运算。必须与labelExpression一起使用。 */ this.uniqueExpression = null; /** * @member {boolean} [ThemeLabel.prototype.smallGeometryLabeled=false] * @description 是否显示长度大于被标注对象本身长度的标签。在标签的长度大于线或者面对象本身的长度时, * 如果该值为 true,则标签文字会叠加在一起显示,为了清楚完整的显示该标签, * 可以采用换行模式来显示标签,但必须保证每行的长度小于对象本身的长度。 */ this.smallGeometryLabeled = false; /** * @member {ThemeLabelText} ThemeLabel.prototype.text * @description 标签中文本风格。 */ this.text = new ThemeLabelText(); /** * @member {number} [ThemeLabel.prototype.textSpace=0] * @description 沿线标注,相邻两个文字之间的间距,单位当前设置的字高。 */ this.textSpace = 0; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeLabel"; } /** * @function ThemeLabel.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.alongLine = null; if (me.background) { me.background.destroy(); me.background = null; } if (me.items) { for (var i = 0, items = me.items, len = items.length; i < len; i++) { items[i].destroy(); } me.items = null; } if (me.uniqueItems) { for (var j = 0, uniqueItems = me.uniqueItems, uniqueLen = uniqueItems.length; j < uniqueLen; j++) { uniqueItems[j].destory(); } me.uniqueItems = null; } me.labelExpression = null; me.labelOverLengthMode = null; me.matrixCells = null; me.maxLabelLength = null; me.numericPrecision = null; me.overlapAvoided = null; me.rangeExpression = null; me.uniqueExpression = null; if (me.offset) { me.offset.destroy(); me.offset = null; } me.overlapAvoided = null; me.smallGeometryLabeled = null; if (me.text) { me.text.destroy(); me.text = null; } me.textSpace = null; } /** * @function ThemeLabel.prototype.toJSON * @description 将themeLabel对象转化为 JSON 字符串。 * @returns {string} 返回转换后的 JSON 字符串。 */ toJSON() { return Util.toJSON(this.toServerJSONObject()); } /** * @function ThemeLabel.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj.type = this.type; obj.memoryData = this.memoryData; if (this.alongLine) { obj.alongLine = this.alongLine.isAlongLine; obj.alongLineDirection = this.alongLine.alongLineDirection; obj.angleFixed = this.alongLine.angleFixed; obj.isLabelRepeated = this.alongLine.isLabelRepeated; obj.labelRepeatInterval = this.alongLine.labelRepeatInterval; obj.repeatedLabelAvoided = this.alongLine.repeatedLabelAvoided; obj.repeatIntervalFixed = this.alongLine.repeatIntervalFixed; } if (this.offset) { obj.offsetFixed = this.offset.offsetFixed; obj.offsetX = this.offset.offsetX; obj.offsetY = this.offset.offsetY; } if (this.text) { obj.maxTextHeight = this.text.maxTextHeight; obj.maxTextWidth = this.text.maxTextWidth; obj.minTextHeight = this.text.minTextHeight; obj.minTextWidth = this.text.minTextWidth; obj.uniformStyle = this.text.uniformStyle; obj.uniformMixedStyle = this.text.uniformMixedStyle; } if (this.background) { obj.labelBackShape = this.background.labelBackShape; obj.backStyle = this.background.backStyle; } obj.labelOverLengthMode = this.labelOverLengthMode; obj.maxLabelLength = this.maxLabelLength; obj.smallGeometryLabeled = this.smallGeometryLabeled; obj.rangeExpression = this.rangeExpression; obj.uniqueExpression = this.uniqueExpression; obj.numericPrecision = this.numericPrecision; obj.items = this.items; obj.uniqueItems = this.uniqueItems; obj.labelExpression = this.labelExpression; obj.overlapAvoided = this.overlapAvoided; obj.matrixCells = this.matrixCells; obj.textSpace = this.textSpace; return obj; } /** * @function ThemeLabel.fromObj * @description 从传入对象获取标签专题图类。 * @param {Object} obj - 传入对象。 * @returns {ThemeLabel} ThemeLabel 对象。 */ static fromObj(obj) { if (!obj) { return; } var lab = new ThemeLabel(); var itemsL = obj.items, itemsU = obj.uniqueItems, cells = obj.matrixCells; obj.matrixCells = null; Util.copy(lab, obj); lab.alongLine = ThemeLabelAlongLine.fromObj(obj); lab.background = ThemeLabelBackground.fromObj(obj); if (itemsL) { lab.items = []; for (var i = 0, len = itemsL.length; i < len; i++) { lab.items.push(ThemeLabelItem.fromObj(itemsL[i])); } } if (itemsU) { lab.uniqueItems = []; for (let j = 0, uniqueLen = itemsU.length; j < uniqueLen; j++) { lab.uniqueItems.push(ThemeUniqueItem.fromObj(itemsU[j])); } } if (cells) { lab.matrixCells = []; for (let i = 0, len = cells.length; i < len; i++) { //TODO //lab.matrixCells.push(LabelMatrixCell.fromObj(cells[i])); } } lab.offset = ThemeOffset.fromObj(obj); lab.text = ThemeLabelText.fromObj(obj); return lab; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeUnique.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeUnique * @deprecatedclass SuperMap.ThemeUnique * @category iServer Map Theme * @classdesc 单值专题图。单值专题图是利用不同的颜色或符号(线型、填充)表示图层中某一属性信息的不同属性值,属性值相同的要素具有相同的渲染风格。单值专题图多用于具有分类属性的地图上, * 比如土壤类型分布图、土地利用图、行政区划图等。单值专题图着重表示现象质的差别,一般不表示数量的特征。尤其是有交叉或重叠现象时,此类不推荐使用,例如:民族分布区等。 * @extends {CommonTheme} * @param {Object} options - 参数。 * @param {Array.} options.items - 子项类数组。 * @param {string} options.uniqueExpression - 指定单值专题图的字段或字段表达式。 * @param {ServerStyle} [options.defaultStyle] - 未参与单值专题图制作的对象的显示风格。 * @param {ColorGradientType} [options.colorGradientType=ColorGradientType.YELLOW_RED] - 渐变颜色枚举类。 * @param {ThemeMemoryData} [options.memoryData] - 专题图内存数据。 * @usage */ class ThemeUnique extends Theme { constructor(options) { super("UNIQUE", options); /** * @member {ServerStyle} ThemeUnique.prototype.defaultStyle * @description 未参与单值专题图制作的对象的显示风格。 * 通过单值专题图子项数组 (items)可以指定某些要素参与单值专题图制作,对于那些没有被包含的要素,即不参加单值专题表达的要素,使用该风格显示。 */ this.defaultStyle = new ServerStyle(); /** * @member {Array.} ThemeUnique.prototype.items * @description 单值专题图子项类数组。 * 单值专题图是将专题值相同的要素归为一类,为每一类设定一种渲染风格,其中每一类就是一个专题图子项。比如,利用单值专题图制作行政区划图, * Name 字段代表省/直辖市名,该字段用来做专题变量,如果该字段的字段值总共有5种不同值,则该行政区划图有 5 个专题图子项。 */ this.items = null; /** * @member {string} ThemeUnique.prototype.uniqueExpression * @description 用于制作单值专题图的字段或字段表达式。 * 该字段值的数据类型可以为数值型或字符型。如果设置字段表达式,只能是相同数据类型字段间的运算。 */ this.uniqueExpression = null; /** * @member {ColorGradientType} [ThemeUnique.prototype.colorGradientType=ColorGradientType.YELLOW_RED] * @description 渐变颜色枚举类。 * 渐变色是由起始色根据一定算法逐渐过渡到终止色的一种混合型颜色。 * 该类作为单值专题图参数类、分段专题图参数类的属性,负责设置单值专题图、分段专题图的配色方案,在默认情况下专题图所有子项会根据这个配色方案完成填充。 * 但如果为某几个子项的风格进行单独设置后(设置了 ThemeUniqueItem 或 ThemeRangeItem 类中Style属性), * 该配色方案对于这几个子项将不起作用。 */ this.colorGradientType = ColorGradientType.YELLOW_RED; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeUnique"; } /** * @function ThemeUnique.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.uniqueExpression = null; me.colorGradientType = null; if (me.items) { if (me.items.length > 0) { for (var item in me.items) { me.items[item].destroy(); me.items[item] = null; } } me.items = null; } if (me.defaultStyle) { me.defaultStyle.destroy(); me.defaultStyle = null; } } /** * @function ThemeUnique.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj = Util.copyAttributes(obj, this); if (obj.defaultStyle) { if (obj.defaultStyle.toServerJSONObject) { obj.defaultStyle = obj.defaultStyle.toServerJSONObject(); } } if (obj.items) { var items = [], len = obj.items.length; for (var i = 0; i < len; i++) { items.push(obj.items[i].toServerJSONObject()); } obj.items = items; } return obj; } /** * @function ThemeUnique.fromObj * @description 从传入对象获取单值专题图类。 * @param {Object} obj - 传入对象。 * @returns {ThemeUnique} ThemeUnique 对象。 */ static fromObj(obj) { var res = new ThemeUnique(); var uItems = obj.items; var len = uItems ? uItems.length : 0; Util.extend(res, obj); res.items = []; res.defaultStyle = ServerStyle.fromJson(obj.defaultStyle); for (var i = 0; i < len; i++) { res.items.push(ThemeUniqueItem.fromObj(uItems[i])); } return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGraphAxes.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGraphAxes * @deprecatedclass SuperMap.ThemeGraphAxes * @category iServer Map Theme * @classdesc 统计专题图坐标轴样式类。 * @param {Object} options - 参数。 * @param {ServerColor} [options.axesColor=(0, 0, 0)] - 坐标轴颜色。 * @param {boolean} [options.axesDisplayed=false] - 是否显示坐标轴。 * @param {boolean} [options.axesGridDisplayed=false] - 是否在统计图坐标轴上显示网格。 * @param {boolean} [options.axesTextDisplayed=false] - 是否显示坐标轴的文本标注。 * @param {ServerTextStyle} [options.axesTextStyle] - 统计符号的最大最小尺寸。 * @usage */ class ThemeGraphAxes { constructor(options) { /** * @member {ServerColor} [ThemeGraphAxes.prototype.axesColor=(0, 0, 0)] * @description 坐标轴颜色。当 axesDisplayed = true 时有效。 */ this.axesColor = new ServerColor(0, 0, 0); /** * @member {boolean} [ThemeGraphAxes.prototype.axesDisplayed=false] * @description 是否显示坐标轴。
* 由于饼状图和环状图无坐标轴,故该属性以及所有与坐标轴设置相关的属性都不适用于它们。并且只有当该值为 true 时,其它设置坐标轴的属性才起作用。 */ this.axesDisplayed = false; /** * @member {boolean} [ThemeGraphAxes.prototype.axesGridDisplayed=false] * @description 是否在统计图坐标轴上显示网格。 */ this.axesGridDisplayed = false; /** * @member {boolean} [ThemeGraphAxes.prototype.axesTextDisplayed=false] * @description 是否显示坐标轴的文本标注。 */ this.axesTextDisplayed = false; /** * @member {ServerTextStyle} ThemeGraphAxes.prototype.axesTextStyle * @description 坐标轴文本风格。当 axesTextDisplayed = true 时有效。 */ this.axesTextStyle = new ServerTextStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGraphAxes"; } /** * @function ThemeGraphAxes.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.axesColor) { me.axesColor.destroy(); me.axesColor = null; } me.axesDisplayed = null; me.axesGridDisplayed = null; me.axesTextDisplayed = null; if (me.axesTextStyle) { me.axesTextStyle.destroy(); me.axesTextStyle = null; } } /** * @function ThemeGraphAxes.fromObj * @description 从传入对象获取统计专题图坐标轴样式类。 * @param {Object} obj - 传入对象。 * @returns {ThemeGraphAxes} ThemeGraphAxes 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeGraphAxes(); Util.copy(res, obj); res.axesColor = ServerColor.fromJson(obj.axesColor); res.axesTextStyle = ServerTextStyle.fromObj(obj.axesTextStyle); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGraphSize.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGraphSize * @deprecatedclass SuperMap.ThemeGraphSize * @category iServer Map Theme * @classdesc 统计专题图符号尺寸类。 * @param {Object} options - 参数。 * @param {number} [options.maxGraphSize=0] - 统计图中显示的最大图表尺寸基准值。 * @param {number} [options.minGraphSize=0] - 统计图中显示的最小图表尺寸基准值。 * @usage */ class ThemeGraphSize { constructor(options) { /** * @member {number} [ThemeGraphSize.prototype.maxGraphSize=0] * @description 获取或设置统计图中显示的最大图表尺寸基准值,单位为像素。 */ this.maxGraphSize = 0; /** * @member {number} [ThemeGraphSize.prototype.minGraphSize=0] * @description 获取或设置统计图中显示的最小图表尺寸基准值,单位为像素。 */ this.minGraphSize = 0; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGraphSize"; } /** * @function ThemeGraphSize.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.maxGraphSize = null; me.minGraphSize = null; } /** * @function ThemeGraphSize.fromObj * @description 从传入对象获统计专题图符号尺寸类。 * @param {Object} obj - 传入对象。 * @returns {ThemeGraphSize} ThemeGraphSize 对象。 */ static fromObj(obj) { var res = new ThemeGraphSize(); Util.copy(res, obj); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGraphText.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGraphText * @deprecatedclass SuperMap.ThemeGraphText * @category iServer Map Theme * @classdesc 统计图文字标注风格类。 * @param {Object} options - 可选参数。 * @param {boolean} [options.graphTextDisplayed=false] - 是否显示统计图上的文字标注。 * @param {ThemeGraphTextFormat} [options.graphTextFormat=ThemeGraphTextFormat.CAPTION] - 统计专题图文本显示格式。 * @param {ServerTextStyle} [options.graphTextStyle] - 统计图上的文字标注风格。 * @usage */ class ThemeGraphText { constructor(options) { /** * @member {boolean} [ThemeGraphText.prototype.graphTextDisplayed=false] * @description 是否显示统计图上的文字标注。 */ this.graphTextDisplayed = false; /** * @member {ThemeGraphTextFormat} [ThemeGraphText.prototype.graphTextFormat=ThemeGraphTextFormat.CAPTION] * @description 统计专题图文本显示格式。 * 文本显示格式包括百分数、真实数值、标题、标题+百分数、标题+真实数值。 */ this.graphTextFormat = ThemeGraphTextFormat.CAPTION; /** * @member {ServerTextStyle} ThemeGraphText.prototype.graphTextStyle * @description 统计图上的文字标注风格。 */ this.graphTextStyle = new ServerTextStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGraphText"; } /** * @function ThemeGraphText.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.graphTextDisplayed = null; me.graphTextFormat = null; if (me.graphTextStyle) { me.graphTextStyle.destroy(); me.graphTextStyle = null; } } /** * @function ThemeGraphText.fromObj * @description 从传入对象获取统计图文字标注风格类。 * @param {Object} obj - 传入对象。 * @returns {ThemeGraphText} ThemeGraphText 对象。 */ static fromObj(obj) { var res = new ThemeGraphText(); Util.copy(res, obj); res.graphTextStyle = ServerTextStyle.fromObj(obj.graphTextStyle); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGraphItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGraphItem * @deprecatedclass SuperMap.ThemeGraphItem * @category iServer Map Theme * @classdesc 统计专题图子项类。 * @param {Object} options - 参数。 * @param {string} [options.caption] - 专题图子项的名称。 * @param {string} options.graphExpression - 统计专题图的专题变量。 * @param {Array.} [options.memoryDoubleValues] - 内存数组方式制作专题图时的值数组。 * @param {ServerStyle} [options.uniformStyle] - 统计专题图子项的显示风格。 * @usage */ class ThemeGraphItem { constructor(options) { /** * @member {string} [ThemeGraphItem.prototype.caption] * @description 专题图子项的名称。 */ this.caption = null; /** * @member {string} ThemeGraphItem.prototype.graphExpression * @description 统计专题图的专题变量。专题变量可以是一个字段或字段表达式。字段必须为数值型;表达式只能为数值型的字段间的运算。 */ this.graphExpression = null; /** * @member {Array.} [ThemeGraphItem.prototype.memoryDoubleValues] * @description 内存数组方式制作专题图时的值数组。
* 内存数组方式制作专题图时,只对 SmID 值在键数组({@link ThemeGraph#memoryKeys})中的记录制作专题图。 * 值数组的数值个数必须与键数组中数值的个数一致。值数组中的值将代替原来的专题值来制作统计专题图。 * 比如:利用面积字段和周长字段(即有两个统计专题图子项 )作为专题变量制作统计专题图。 */ this.memoryDoubleValues = null; /** * @member {ServerStyle} [ThemeGraphItem.prototype.uniformStyle] * @description 统计专题图子项的显示风格。 * 每一个统计专题图子项都对应一种显示风格。 */ this.uniformStyle = new ServerStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGraphItem"; } /** * @function ThemeGraphItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.caption = null; me.graphExpression = null; me.memoryDoubleValues = null; me.uniformStyle = null; } /** * @function ThemeGraphItem.fromObj * @description 从传入对象获取统计专题图子项类。 * @param {Object} obj - 传入对象。 * @returns {ThemeGraphItem} ThemeGraphItem 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeGraphItem(); Util.copy(res, obj); res.uniformStyle = ServerStyle.fromJson(obj.uniformStyle); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGraph.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGraph * @deprecatedclass SuperMap.ThemeGraph * @category iServer Map Theme * @classdesc 统计专题图类。 * @extends {CommonTheme} * @param {Object} options - 参数。 * @param {Array.} options.items - 统计专题图子项集合。 * @param {number} [options.barWidth=0] - 柱状专题图中每一个柱的宽度。 * @param {GraduatedMode} [options.graduatedMode=GraduatedMode.CONSTANT] - 统计图中地理要素的值与图表尺寸间的映射关系。 * @param {ThemeGraphAxes} [options.graphAxes] - 统计图中坐标轴样式相关信息。 * @param {ThemeGraphSize} [options.graphSize=0] - 统计符号的最大最小尺寸。 * @param {boolean} [options.graphSizeFixed=false] - 缩放地图时统计图符号是否固定大小。 * @param {ThemeGraphText} [options.graphText] - 统计图上的文字是否可见以及文字标注风格。 * @param {GraphAxesTextDisplayMode} [options.graphAxesTextDisplayMode=GraphAxesTextDisplayMode.NONE] - 统计专题图坐标轴文本显示模式。 * @param {ThemeGraphType} [options.graphType=ThemeGraphType.AREA] - 统计专题图类型。 * @param {Array.} [options.memoryKeys] - 以内存数组方式制作专题图时的键数组。 * @param {boolean} [options.negativeDisplayed=false] - 专题图中是否显示属性为负值的数据。 * @param {ThemeOffset} [options.offset] - 统计图相对于要素内点的偏移量。 * @param {boolean} [options.overlapAvoided=true] - 统计图是否采用避让方式显示。 * @param {number} [options.roseAngle=0] - 统计图中玫瑰图或三维玫瑰图用于等分的角度。 * @param {number} [options.startAngle=0] - 饼状统计图扇形的起始角度。 * @usage */ class ThemeGraph extends Theme { constructor(options) { super("GRAPH", options); /** * @member {number} [ThemeGraph.prototype.barWidth=0] * @description 柱状专题图中每一个柱的宽度。使用地图坐标单位。 * 只有选择的统计图类型为柱状图(柱状图、三维柱状图、堆叠柱状图、三维堆叠柱状图)时,此项才可设置。 */ this.barWidth = 0; /** * @member {GraduatedMode} [ThemeGraph.prototype.graduatedMode=GraduatedMode.CONSTANT] * @description 统计图中地理要素的值与图表尺寸间的映射关系(常数、对数、平方根),即分级方式。 * 分级主要是为了减少制作统计专题图中数据大小之间的差异,使得统计图的视觉效果比较好,同时不同类别之间的比较也还是有意义的。 * 提供三种分级模式:常数、对数和平方根,对于有值为负数的字段,不可以采用对数和平方根的分级方式。不同的等级方式用于确定符号大小的数值是不相同的。 */ this.graduatedMode = GraduatedMode.CONSTANT; /** * @member {ThemeGraphAxes} ThemeGraph.prototype.graphAxes * @description 用于设置统计图中坐标轴样式相关信息,如坐标轴颜色、是否显示、坐标文本样式等。 */ this.graphAxes = new ThemeGraphAxes(); /** * @member {ThemeGraphSize} [ThemeGraph.prototype.graphSize=0] * @description 用于设置统计符号的最大最小尺寸。 */ this.graphSize = new ThemeGraphSize(); /** * @member {boolean} [ThemeGraph.prototype.graphSizeFixed=false] * @description 缩放地图时统计图符号是否固定大小。即统计图符号将随地图缩放。 */ this.graphSizeFixed = false; /** * @member {ThemeGraphText} ThemeGraph.prototype.graphText * @description 统计图上的文字是否可见以及文字标注风格。 */ this.graphText = new ThemeGraphText(); /** * @member {ThemeGraphType} [ThemeGraph.prototype.graphType=ThemeGraphType.AREA] * @description 统计专题图类型。SuperMap 提供了多种类型的统计图, * 分别为面积图、阶梯图、折线图、点状图、柱状图、三维柱状图、饼图、三维饼图、玫瑰图、三维玫瑰图、堆叠柱状图、三维堆叠柱状图、环状图。默认为面积图。 */ this.graphType = ThemeGraphType.AREA; /** * @member {GraphAxesTextDisplayMode} [ThemeGraph.prototype.graphAxesTextDisplayMode=GraphAxesTextDisplayMode.NONE] * @description 统计专题图坐标轴文本显示模式。 */ this.graphAxesTextDisplayMode = GraphAxesTextDisplayMode.NONE; /** * @member {Array.} ThemeGraph.prototype.items * @description 统计专题图子项集合。 * 统计专题图可以基于多个变量,反映多种属性,即可以将多个专题变量的值绘制在一个统计图上。每一个专题变量对应的统计图即为一个专题图子项。 * 对于每个专题图子项可以为其设置标题、风格,甚至可以将该子项再制作成范围分段专题图。 */ this.items = null; /** * @member {Array.} ThemeGraph.prototype.memoryKeys * @description 以内存数组方式制作专题图时的键数组。 * 键数组内的数值代表 SmID 值,它与 {@link ThemeGraphItem} 类中的值数组({@link ThemeGraphItem#memoryDoubleValues})要关联起来应用。 * 键数组中数值的个数必须要与值数组的数值个数一致。值数组中的值将代替原来的专题值来制作统计专题图。 * 目前所有的专题图都支持以内存数组的方式制作专题图,但统计专题图与其他专题图指定内存数组的方式不同, * 统计专题图使用 memoryKeys 指定内存数组,而其他专题图则使用 memoryData 来指定内存数组。 * @example * memoryKeys 的使用方法如下: * function addThemeGraph() { * removeTheme(); * //创建统计专题图对象,ThemeGraph 必设 items。 * //专题图参数 ThemeParameters 必设 theme(即以设置好的分段专题图对象)、dataSourceName 和 datasetName * var style1 = new ServerStyle({ * fillForeColor: new ServerColor(92,73,234), * lineWidth: 0.1 * }), * style2 = new ServerStyle({ * fillForeColor: new ServerColor(211,111,240), * lineWidth: 0.1 * }), * item1 = new ThemeGraphItem({ * memoryDoubleValues:[1.18,0.95,0.37,1.31,0.8,1.5], * caption: "1992-1995人口增长率", * graphExpression: "Pop_Rate95", * uniformStyle: style1 * }), * item2 = new ThemeGraphItem({ * //以内存数组方式制作专题图时的值数组 * memoryDoubleValues:[2.71,0,0.74,3.1,2.2,3.5], * caption: "1995-1999人口增长率", //专题图子项的名称 * graphExpression: "Pop_Rate99", //统计专题图的专题变量 * uniformStyle: style2 //统计专题图子项的显示风格 * }), * themeGraph = new ThemeGraph({ * //以内存数组方式制作专题图时的键数组,键数组内的数值代表 SmID 值 * memoryKeys:[1,2,4,8,10,12], * items: new Array(item1,item2), * barWidth: 0.03, * //统计图中地理要素的值与图表尺寸间的映射关系为平方根 * graduatedMode: GraduatedMode.SQUAREROOT, * //graphAxes用于设置统计图中坐标轴样式相关信息 * graphAxes: new ThemeGraphAxes({ * axesDisplayed: true * }), * graphSize: new ThemeGraphSize({ * maxGraphSize: 1, * minGraphSize: 0.35 * }), * //统计图上的文字是否可见以及文字标注风格 * graphText: new ThemeGraphText({ * graphTextDisplayed: true, * graphTextFormat: ThemeGraphTextFormat.VALUE, * graphTextStyle: new ServerTextStyle({ * sizeFixed: true, * fontHeight: 9, * fontWidth: 5 * }) * }), * //统计专题图类型为三维柱状图 * graphType: ThemeGraphType.BAR3D * }), * //专题图参数对象 * themeParameters = new ThemeParameters({ * themes: [themeGraph], * dataSourceNames: ["Jingjin"], * datasetNames: ["BaseMap_R"] * }), * //与服务端交互 * themeService=new ThemeService(url, { * eventListeners: { * "processCompleted": ThemeCompleted, * "processFailed": themeFailed * } * }); * themeService.processAsync(themeParameters); * } */ this.memoryKeys = null; /** * @member {boolean} [ThemeGraph.prototype.negativeDisplayed=false] * @description 专题图中是否显示属性为负值的数据。true 表示显示;false 不显示。 */ this.negativeDisplayed = false; /** * @member {ThemeOffset} ThemeGraph.prototype.offset * @description 用于设置统计图相对于要素内点的偏移量。 */ this.offset = new ThemeOffset(); /** * @member {boolean} ThemeGraph.prototype.overlapAvoided * @description 统计图是否采用避让方式显示。
* 1.对数据集制作统计专题图:当统计图采用避让方式显示时,如果 overlapAvoided 为 true,则在统计图重叠度很大的情况下, * 会出现无法完全避免统计图重叠的现象;如果 overlapAvoided 为 false,会过滤掉一些统计图,从而保证所有的统计图均不重叠。
* 2.对数据集同时制作统计专题图和标签专题图:当统计图不显示子项文本时,标签专题图的标签即使和统计图重叠,两者也都可正常显示; * 当统计图显示子项文本时,如果统计图中的子项文本和标签专题图中的标签不重叠,则两者均正常显示;如果重叠,则会过滤掉统计图的子项文本,只显示标签。 */ this.overlapAvoided = true; /** * @member {number} [ThemeGraph.prototype.roseAngle=0] * @description 统计图中玫瑰图或三维玫瑰图用于等分的角度,默认为 0 度,精确到 0.1 度。在角度为0或者大于 360 度的情况下均使用 360 度来等分制作统计图的字段数。 */ this.roseAngle = 0; /** * @member {number} [ThemeGraph.prototype.startAngle=0] * @description 饼状统计图扇形的起始角度。精确到 0.1 度,以水平方向为正向。只有选择的统计图类型为饼状图(饼图、三维饼图、玫瑰图、三维玫瑰图)时,此项才可设置。 */ this.startAngle = 0; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGraph"; } /** * @function ThemeGraph.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; me.barWidth = null; me.graduatedMode = null; if (me.graphAxes) { me.graphAxes.destroy(); me.graphAxes = null; } if (me.graphSize) { me.graphSize.destroy(); me.graphSize = null; } me.graphSizeFixed = null; if (me.graphText) { me.graphText.destroy(); me.graphText = null; } me.graphType = null; if (me.items) { for (var i = 0, items = me.items, len = items.length; i < len; i++) { items[i].destroy(); } me.items = null; } me.memoryKeys = null; me.negativeDisplayed = null; if (me.offset) { me.offset.destroy(); me.offset = null; } me.overlapAvoided = null; me.roseAngle = null; me.startAngle = null; me.graphAxesTextDisplayMode = null; } /** * @function ThemeGraph.prototype.toJSON * @description 将 ThemeGraph 对象转化为 JSON 字符串。 * @returns {string} 返回转换后的 JSON 字符串。 */ toJSON() { return Util.toJSON(this.toServerJSONObject()); } /** * @function ThemeGraph.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj.type = this.type; if (this.graphText) { obj.graphTextDisplayed = this.graphText.graphTextDisplayed; obj.graphTextFormat = this.graphText.graphTextFormat; obj.graphTextStyle = this.graphText.graphTextStyle; } if (this.graphAxes) { obj.axesColor = this.graphAxes.axesColor; obj.axesDisplayed = this.graphAxes.axesDisplayed; obj.axesGridDisplayed = this.graphAxes.axesGridDisplayed; obj.axesTextDisplayed = this.graphAxes.axesTextDisplayed; obj.axesTextStyle = this.graphAxes.axesTextStyle; } if (this.graphSize) { obj.maxGraphSize = this.graphSize.maxGraphSize; obj.minGraphSize = this.graphSize.minGraphSize; } if (this.offset) { obj.offsetFixed = this.offset.offsetFixed; obj.offsetX = this.offset.offsetX; obj.offsetY = this.offset.offsetY; } obj.barWidth = this.barWidth; obj.graduatedMode = this.graduatedMode; obj.graphSizeFixed = this.graphSizeFixed; obj.graphType = this.graphType; obj.graphAxesTextDisplayMode = this.graphAxesTextDisplayMode; obj.items = this.items; obj.memoryKeys = this.memoryKeys; obj.negativeDisplayed = this.negativeDisplayed; obj.overlapAvoided = this.overlapAvoided; obj.roseAngle = this.roseAngle; obj.startAngle = this.startAngle; return obj; } /** * @function ThemeGraph.fromObj * @description 从传入对象获取统计专题图类。 * @param {Object} obj - 传入对象。 * @returns {ThemeGraph} ThemeGraph 对象。 */ static fromObj(obj) { var res = new ThemeGraph(); var itemsG = obj.items; var len = itemsG ? itemsG.length : 0; Util.copy(res, obj); res.items = []; res.graphAxes = ThemeGraphAxes.fromObj(obj); res.graphSize = ThemeGraphSize.fromObj(obj); res.graphText = ThemeGraphText.fromObj(obj); res.offset = ThemeOffset.fromObj(obj); for (var i = 0; i < len; i++) { res.items.push(ThemeGraphItem.fromObj(itemsG[i])); } return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeDotDensity.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeDotDensity * @deprecatedclass SuperMap.ThemeDotDensity * @category iServer Map Theme * @classdesc 点密度专题图。点密度专题图用一定大小、形状相同的点表示现象分布范围、数量特征和分布密度。点的多少和所代表的意义由地图的内容确定。 * 点密度专题图利用图层的某一数值属性信息(专题值)映射为不同等级,每一级别使用不同数量或表现为密度的点符号来表示。 * 该专题值在各个分区内的分布情况,体现不同区域的相对数量差异。多用于具有数量特征的地图上, * 比如表示不同地区的粮食产量、GDP、人口等的分级,主要针对区域或面状的要素,因而,点密度专题图适用于面数据集。 * 注意:点密度专题图中点的分布是随机的,并不代表实际的分布位置。即使在相关设置完全相同的情况下, * 每次制作出的专题图,点的数量相同,但点的位置都有差异。 * @extends {CommonTheme} * @param {Object} options - 参数。 * @param {string} options.dotExpression - 创建点密度专题图的字段或字段表达式。 * @param {ServerStyle} [options.style] - 点密度专题图中点的风格。 * @param {number} [options.value] - 专题图中每一个点所代表的数值。 * @param {ThemeMemoryData} [options.memoryData] - 专题图内存数据。 * @usage */ class ThemeDotDensity extends Theme { constructor(options) { super("DOTDENSITY", options); /** * @member {string} ThemeDotDensity.prototype.dotExpression * @description 创建点密度专题图的字段或字段表达式。点的数目或密集程度的来源。 */ this.dotExpression = null; /** * @member {ServerStyle} ThemeDotDensity.prototype.style * @description 点密度专题图中点的风格。 */ this.style = new ServerStyle(); /** * @member {number} ThemeDotDensity.prototype.value * @description 专题图中每一个点所代表的数值。
* 点值的确定与地图比例尺以及点的大小有关。地图比例尺越大,相应的图面范围也越大, * 点相应就可以越多,此时点值就可以设置相对小一些。点形状越大, * 点值相应就应该设置的小一些。点值过大或过小都是不合适的。 */ this.value = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeDotDensity"; } /** * @function ThemeDotDensity.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.dotExpression = null; me.value = null; if (me.style) { me.style.destroy(); me.style = null; } } /** * @function ThemeDotDensity.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj = Util.copyAttributes(obj, this); if (obj.style) { if (obj.style.toServerJSONObject) { obj.style = obj.style.toServerJSONObject(); } } return obj; } /** * @function ThemeDotDensity.fromObj * @description 从传入对象获取点密度专题图中点的风格。 * @param {Object} obj - 传入对象。 * @returns {ThemeDotDensity} ThemeDotDensity 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeDotDensity(); Util.copy(res, obj); res.style = ServerStyle.fromJson(obj.style); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGraduatedSymbolStyle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGraduatedSymbolStyle * @deprecatedclass SuperMap.ThemeGraduatedSymbolStyle * @category iServer Map Theme * @classdesc 等级符号专题图正负零值显示风格类。 * @param {Object} options - 参数。 * @param {boolean} [options.negativeDisplayed=false] - 是否显示负值。 * @param {ServerStyle} [options.negativeStyle] - 负值的等级符号风格。 * @param {ServerStyle} [options.positiveStyle] - 正值的等级符号风格。 * @param {boolean} [options.zeroDisplayed=false] - 是否显示 0 值。 * @param {ServerStyle} [options.zeroStyle] - 0 值的等级符号风格。 * @usage */ class ThemeGraduatedSymbolStyle { constructor(options) { /** * @member {boolean} [ThemeGraduatedSymbolStyle.prototype.negativeDisplayed=false] * @description 是否显示负值。 */ this.negativeDisplayed = false; /** * @member {ServerStyle} [ThemeGraduatedSymbolStyle.prototype.negativeStyle] * @description 负值的等级符号风格。 */ this.negativeStyle = new ServerStyle(); /** * @member {ServerStyle} [ThemeGraduatedSymbolStyle.prototype.positiveStyle] * @description 正值的等级符号风格。 */ this.positiveStyle = new ServerStyle(); /** * @member {boolean} [ThemeGraduatedSymbolStyle.prototype.zeroDisplayed=false] * @description 是否显示 0 值。 */ this.zeroDisplayed = false; /** * @member {ServerStyle} ThemeGraduatedSymbolStyle.prototype.zeroStyle * @description 0 值的等级符号风格。 */ this.zeroStyle = new ServerStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGraduatedSymbolStyle"; } /** * @function ThemeGraduatedSymbolStyle.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.negativeDisplayed = null; me.negativeStyle = null; me.positiveStyle = null; me.zeroDisplayed = null; me.zeroStyle = null; } /** * @function ThemeGraduatedSymbolStyle.fromObj * @description 从传入对象获取等级符号专题图正负零值显示风格类。 * @param {Object} obj - 传入对象。 * @returns {ThemeGraduatedSymbolStyle} ThemeGraduatedSymbolStyle 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeGraduatedSymbolStyle(); Util.copy(res, obj); res.negativeStyle = ServerStyle.fromJson(obj.negativeStyle); res.positiveStyle = ServerStyle.fromJson(obj.positiveStyle); res.zeroStyle = ServerStyle.fromJson(obj.zeroStyle); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGraduatedSymbol.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGraduatedSymbol * @deprecatedclass SuperMap.ThemeGraduatedSymbol * @category iServer Map Theme * @classdesc 等级符号专题图。 * @extends {CommonTheme} * @param {Object} options - 参数。 * @param {ThemeGraduatedSymbolStyle} options.style - 等级符号专题图正负零值显示风格类。 * @param {string} options.expression - 等级符号专题图的字段或字段表达式。 * @param {number} [options.baseValue=0] - 等级符号专题图的基准值,单位同专题变量的单位。 * @param {GraduatedMode} [options.graduatedMode=GraduatedMode.CONSTANT] - 等级符号专题图分级模式。 * @param {ThemeOffset} [options.offset] - 指定等级符号专题图中标记文本相对于要素内点的偏移量对象。 * @param {ThemeMemoryData} [options.memoryData] - 专题图内存数据。 * @usage */ class ThemeGraduatedSymbol extends Theme { constructor(options) { super("GRADUATEDSYMBOL", options); /** * @member {number} [ThemeGraduatedSymbol.prototype.baseValue=0] * @description 等级符号专题图的基准值,单位同专题变量的单位。
* 依据此值系统会自动根据分级方式计算其余值对应的符号大小,每个符号的显示大小等于 * ThemeValueSection.positiveStyle(或 zeroStyle,negativeStyle).markerSize * value / basevalue, * 其中 value 是 expression 所指定字段对应的值经过分级计算之后的值。默认值为0,建议通过多次尝试设置该值才能达到较好的显示效果。 */ this.baseValue = 0; /** * @member {string} ThemeGraduatedSymbol.prototype.expression * @description 用于创建等级符号专题图的字段或字段表达式,字段或字段表达式应为数值型。 */ this.expression = null; /** * @member {GraduatedMode} [ThemeGraduatedSymbol.prototype.graduatedMode=GraduatedMode.CONSTANT] * @description 等级符号专题图分级模式。
* 分级主要是为了减少制作等级符号专题图中数据大小之间的差异。如果数据之间差距较大,则可以采用对数或者平方根的分级方式来进行, * 这样就减少了数据之间的绝对大小的差异,使得等级符号图的视觉效果比较好,同时不同类别之间的比较也是有意义的。 * 有三种分级模式:常数、对数和平方根,对于有值为负数的字段,在用对数或平方根方式分级时,默认对负数取正。 * 不同的分级模式用于确定符号大小的数值是不相同的:常数按照字段的原始数据进行;对数则是对每条记录对应的专题变量取自然对数; * 平方根则是对其取平方根,然后用最终得到的结果来确定其等级符号的大小。 */ this.graduatedMode = GraduatedMode.CONSTAN; /** * @member {ThemeOffset} [ThemeGraduatedSymbol.prototype.offset] * @description 用于设置等级符号图相对于要素内点的偏移量。 */ this.offset = new ThemeOffset(); /** * @member {ThemeGraduatedSymbolStyle} ThemeGraduatedSymbol.prototype.style * @description 用于设置等级符号图正负和零值显示风格。 */ this.style = new ThemeGraduatedSymbolStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGraduatedSymbol"; } /** * @function ThemeGraduatedSymbol.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.expression = null; me.graduatedMode = GraduatedMode.CONSTANT; if (me.offset) { me.offset.destroy(); me.offset = null; } if (me.style) { me.style.destroy(); me.style = null; } } /** * @function ThemeGraduatedSymbol.prototype.toJSON * @description 将 themeLabel 对象转化为 JSON 字符串。 * @returns {string} 返回转换后的 JSON 字符串。 */ toJSON() { return Util.toJSON(this.toServerJSONObject()); } /** * @function ThemeGraduatedSymbol.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj.type = this.type; obj.memoryData = this.memoryData; obj.baseValue = this.baseValue; obj.expression = this.expression; obj.graduatedMode = this.graduatedMode; if (this.offset) { obj.offsetFixed = this.offset.offsetFixed; obj.offsetX = this.offset.offsetX; obj.offsetY = this.offset.offsetY; } if (this.style) { obj.negativeStyle = this.style.negativeStyle; obj.negativeDisplayed = this.style.negativeDisplayed; obj.positiveStyle = this.style.positiveStyle; obj.zeroDisplayed = this.style.zeroDisplayed; obj.zeroStyle = this.style.zeroStyle; } return obj; } /** * @function ThemeGraduatedSymbol.fromObj * @description 从传入对象获取等级符号专题图。 * @param {Object} obj - 传入对象。 * @returns {ThemeGraduatedSymbol} 等级符号专题图对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeGraduatedSymbol(); Util.copy(res, obj); res.offset = ThemeOffset.fromObj(obj); res.style = ThemeGraduatedSymbolStyle.fromObj(obj); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeRangeItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeRangeItem * @deprecatedclass SuperMap.ThemeRangeItem * @category iServer Map Theme * @classdesc 范围分段专题图子项类。在分段专题图中,字段值按照某种分段模式被分成多个范围段, * 每个范围段即为一个子项,同一范围段的要素属于同一个分段专题图子项。 * 每个子项都有其分段起始值、终止值、名称和风格等。每个分段所表示的范围为[start, end)。 * @param {Object} options - 参数。 * @param {string} [options.caption] - 子项的标题。 * @param {number} [options.end=0] - 子项的终止值。 * @param {number} [options.start=0] - 子项的起始值。 * @param {ServerStyle} options.style - 子项的风格。 * @param {boolean} [options.visible=true] - 子项是否可见。 * @usage */ class ThemeRangeItem { constructor(options) { /** * @member {string} [ThemeRangeItem.prototype.caption] * @description 分段专题图子项的标题。 */ this.caption = null; /** * @member {number} [ThemeRangeItem.prototype.end=0] * @description 分段专题图子项的终止值,即该段专题值范围的最大值。
* 如果该子项是分段中最后一个子项,则该终止值应大于分段字段(ThemeRange 类的 rangeExpression 属性)的最大值,若该终止值小于分段字段最大值, * 则剩余部分由内部随机定义其颜色;如果不是最后一项,该终止值必须与其下一子项的起始值相同,否则系统抛出异常; * 如果设置了范围分段模式和分段数,则会自动计算每段的范围 [start, end),故无需设置 [start, end);当然可以设置,那么结果就会按您设置的值对分段结果进行调整。 */ this.end = 0; /** * @member {number} [ThemeRangeItem.prototype.start=0] * @description 分段专题图子项的起始值,即该段专题值范围的最小值。
* 如果该子项是分段中第一个子项,那么该起始值就是分段的最小值;如果子项的序号大于等于 1 的时候,该起始值必须与前一子项的终止值相同,否则系统会抛出异常。 * 如果设置了范围分段模式和分段数,则会自动计算每段的范围 [start, end),故无需设置 [start, end);当然可以设置,那么结果就会按您设置的值对分段结果进行调整。 */ this.start = 0; /** * @member {ServerStyle} ThemeRangeItem.prototype.style * @description 分段专题图子项的风格。 * 每一个分段专题图子项都对应一种显示风格。 */ this.style = new ServerStyle(); /** * @member {boolean} [ThemeRangeItem.prototype.visible=true] * @description 分段专题图子项是否可见。 */ this.visible = true; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeRangeItem"; } /** * @function ThemeRangeItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.caption = null; me.end = null; me.start = null; if (me.style) { me.style.destroy(); me.style = null; } me.visible = null; } /** * @function ThemeRangeItem.prototypetoServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj = Util.copyAttributes(obj, this); if (obj.style) { if (obj.style.toServerJSONObject) { obj.style = obj.style.toServerJSONObject(); } } return obj; } /** * @function ThemeRangeItem.fromObj * @description 从传入对象获取范围分段专题图子项类。 * @param {Object} obj - 传入对象。 * @returns {ThemeRangeItem} ThemeRangeItem 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeRangeItem(); Util.copy(res, obj); res.style = ServerStyle.fromJson(obj.style); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeRange.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeRange * @deprecatedclass SuperMap.ThemeRange * @category iServer Map Theme * @classdesc 范围分段专题图。 * 范围分段专题图是按照指定的分段方法(如:等距离分段法)对字段的属性值进行分段,使用不同的颜色或符号(线型、填充)表示不同范围段落的属性值在整体上的分布情况,体现区域的差异。 * 在分段专题图中,专题值按照某种分段方式被分成多个范围段,要素根据各自的专题值被分配到其中一个范围段中,在同一个范围段中的要素使用相同的颜色,填充,符号等风格进行显示。 * 分段专题图所基于的专题变量必须为数值型,分段专题图一般用来反映连续分布现象的数量或程度特征,如降水量的分布,土壤侵蚀强度的分布等。 * @extends {CommonTheme} * @param {Object} options - 参数。 * @param {Array.} options.items - 子项数组。 * @param {string} options.rangeExpression - 分段字段表达式。 * @param {number} options.rangeParameter - 分段参数。 * @param {RangeMode} [options.rangeMode=RangeMode.EQUALINTERVAL] - 分段模式。 * @param {ColorGradientType} [options.colorGradientType=ColorGradientType.YELLOW_RED] - 渐变颜色枚举类。 * @param {ThemeMemoryData} [options.memoryData] - 专题图内存数据。 * @usage */ class ThemeRange extends Theme { constructor(options) { super("RANGE", options); /** * @member {string} ThemeRange.prototype.precision * @description 精准度。 */ this.precision = '1.0E-12'; /** * @member {Array.} ThemeRange.prototype.items * @description 分段专题图子项数组。
* 在分段专题图中,字段值按照某种分段模式被分成多个范围段,每个范围段即为一个子项,同一范围段的要素属于同一个分段专题图子项。 * 每个子项都有其分段起始值、终止值、名称和风格等。每个分段所表示的范围为 [start, end)。 * 如果设置了范围分段模式和分段数,则会自动计算每段的范围 [start, end),故无需设置 [start, end);当然可以设置,那么结果就会按照您设置的值对分段结果进行调整。 */ this.items = null; /** * @member {string} ThemeRange.prototype.rangeExpression * @description 分段字段表达式。
* 由于范围分段专题图基于各种分段方法根据一定的距离进行分段,因而范围分段专题图所基于的字段值的数据类型必须为数值型。对于字段表达式,只能为数值型的字段间的运算。 */ this.rangeExpression = null; /** * @member {RangeMode} [ThemeRange.prototype.rangeMode=RangeMode.EQUALINTERVAL] * @description 分段专题图的分段模式。
* 在分段专题图中,作为专题变量的字段或表达式的值按照某种分段方式被分成多个范围段。 * 目前 SuperMap 提供的分段方式包括:等距离分段法、平方根分段法、标准差分段法、对数分段法、等计数分段法和自定义距离法, * 显然这些分段方法根据一定的距离进行分段,因而范围分段专题图所基于的专题变量必须为数值型。 */ this.rangeMode = RangeMode.EQUALINTERVAL; /** * @member {number} ThemeRange.prototype.rangeParameter * @description 分段参数。 * 当分段模式为等距离分段法,平方根分段,对数分段法,等计数分段法其中一种模式时,该参数用于设置分段个数;当分段模式为标准差分段法时, * 该参数不起作用;当分段模式为自定义距离时,该参数用于设置自定义距离。 */ this.rangeParameter = 0; /** * @member {ColorGradientType} [ThemeRange.prototype.colorGradientType=ColorGradientType.YELLOW_RED] * @description 渐变颜色枚举类。
* 渐变色是由起始色根据一定算法逐渐过渡到终止色的一种混合型颜色。 * 该类作为单值专题图参数类、分段专题图参数类的属性,负责设置单值专题图、分段专题图的配色方案,在默认情况下专题图所有子项会根据这个配色方案完成填充。但如果为某几个子项的风格进行单独设置后(设置了 {@link ThemeUniqueItem} 或 {@link ThemeRangeItem} 类中Style属性), * 该配色方案对于这几个子项将不起作用。 */ this.colorGradientType = ColorGradientType.YELLOW_RED; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeRange"; } /** * @function ThemeRange.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.items) { if (me.items.length > 0) { for (var item in me.items) { me.items[item].destroy(); me.items[item] = null; } } me.items = null; } me.rangeExpression = null; me.rangeMode = null; me.rangeParameter = null; me.colorGradientType = null; } /** * @function ThemeRange.fromObj * @description 从传入对象获取范围分段专题图类。 * @param {Object} obj - 传入对象。 * @returns {ThemeRange} ThemeRange 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeRange(); Util.copy(res, obj); var itemsR = obj.items; var len = itemsR ? itemsR.length : 0; res.items = []; for (var i = 0; i < len; i++) { res.items.push(ThemeRangeItem.fromObj(itemsR[i])); } return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/UGCLayer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UGCLayer * @deprecatedclass SuperMap.UGCLayer * @category iServer Map Layer * @classdesc SuperMap 图层类。 * @param {Object} options - 参数。 * @param {Bounds} options.bounds - 图层范围。 * @param {string} options.name - 图层的名称。 * @param {UGCLayerType} options.type - 图层类型。 * @param {string} [options.caption] - 图层的标题。 * @param {string} [options.description] - 图层的描述信息。 * @param {boolean} [options.queryable] - 图层中的对象是否可以查询。 * @param {boolean} [options.subUGCLayers] - 是否允许图层的符号大小随图缩放。 * @param {boolean} [options.visible=false] - 地图对象在同一范围内时,是否重叠显示。 * @usage */ class UGCLayer { constructor(options) { options = options || {}; /** * @member {Bounds} UGCLayer.prototype.bounds * @description 图层范围。 */ this.bounds = null; /** * @member {string} [UGCLayer.prototype.caption] * @description 图层的标题。默认情况下图层的标题与图层的名称一致。在图例、图层控制列表中显示的图层名称就是该图层的标题值。 */ this.caption = null; /** * @member {string} UGCLayer.prototype.description * @description 图层的描述信息。 */ this.description = null; /** * @member {string} UGCLayer.prototype.name * @description 图层的名称。图层的名称在图层所在的地图中唯一标识此图层。该属性区分大小写。 */ this.name = null; /** * @member {boolean} UGCLayer.prototype.queryable * @description 图层中的对象是否可以查询。 */ this.queryable = null; /** * @member {Array} UGCLayer.prototype.subLayers * @description 子图层集。 */ this.subLayers = null; /** * @member {UGCLayerType} UGCLayer.prototype.type * @description 图层类型。 */ this.type = null; /** * @member {boolean} UGCLayer.prototype.visible * @description 地图对象在同一范围内时,是否重叠显示。 */ this.visible = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.UGCLayer"; } /** * @function UGCLayer.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; Util.reset(me); } /** * @function UGCLayer.prototype.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 */ fromJson(jsonObject) { jsonObject = jsonObject ? jsonObject : {}; Util.extend(this, jsonObject); var b = this.bounds; if (b) { this.bounds = new Bounds(b.leftBottom.x, b.leftBottom.y, b.rightTop.x, b.rightTop.y); } } /** * @function UGCLayer.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var jsonObject = {}; jsonObject = Util.copyAttributes(jsonObject, this); if (jsonObject.bounds) { if (jsonObject.bounds.toServerJSONObject) { jsonObject.bounds = jsonObject.bounds.toServerJSONObject(); } } return jsonObject; } } ;// CONCATENATED MODULE: ./src/common/iServer/UGCMapLayer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UGCMapLayer * @deprecatedclass SuperMap.UGCMapLayer * @category iServer Map Layer * @classdesc SuperMap 地图图层类。 * @extends {UGCLayer} * @param {Object} options - 可选参数。 * @param {boolean} [options.completeLineSymbolDisplayed] - 是否显示完整线型。 * @param {number} [options.maxScale] - 地图最大比例尺。 * @param {number} [options.minScale] - 地图最小比例尺。 * @param {number} [options.minVisibleGeometrySize] - 几何对象的最小可见大小,以像素为单位。 * @param {number} [options.opaqueRate] - 图层的不透明度。 * @param {boolean} [options.symbolScalable] - 是否允许图层的符号大小随图缩放。 * @param {number} [options.symbolScale] - 图层的符号缩放基准比例尺。 * @param {boolean} [options.overlapDisplayed=false] - 地图对象在同一范围内时,是否重叠显示。 * @param {OverlapDisplayedOptions} [options.overlapDisplayedOptions] - 地图的压盖过滤显示选项,当overlapDisplayed 为 false 时有效。 * @usage */ class UGCMapLayer extends UGCLayer { constructor(options) { options = options || {}; super(options); /** * @member {boolean} UGCMapLayer.prototype.completeLineSymbolDisplayed * @description 是否显示完整线型。 */ this.completeLineSymbolDisplayed = null; /** * @member {number} UGCMapLayer.prototype.maxScale * @description 地图最大比例尺。 */ this.maxScale = null; /** * @member {number} UGCMapLayer.prototype.minScale * @description 地图最小比例尺。 */ this.minScale = null; /** * @member {number} UGCMapLayer.prototype.minVisibleGeometrySize * @description 几何对象的最小可见大小,以像素为单位。 */ this.minVisibleGeometrySize = null; /** * @member {number} UGCMapLayer.prototype.opaqueRate * @description 图层的不透明度。 */ this.opaqueRate = null; /** * @member {boolean} UGCMapLayer.prototype.symbolScalable * @description 是否允许图层的符号大小随图缩放。 */ this.symbolScalable = null; /** * @member {number} UGCMapLayer.prototype.symbolScale * @description 图层的符号缩放基准比例尺。 */ this.symbolScale = null; /** * @member {boolean} [UGCMapLayer.prototype.overlapDisplayed=false] * @description 地图对象在同一范围内时,是否重叠显示。 */ this.overlapDisplayed = null; /** * @member {OverlapDisplayedOptions} UGCMapLayer.prototype.overlapDisplayedOptions * @description 地图的压盖过滤显示选项,当 overlapDisplayed 为 false 时有效。 */ this.overlapDisplayedOptions = null; this.CLASS_NAME = "SuperMap.UGCMapLayer"; } /** * @function UGCMapLayer.prototype.destroy * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function UGCMapLayer.prototype.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 */ fromJson(jsonObject) { super.fromJson(jsonObject); } /** * @function UGCMapLayer.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { return super.toServerJSONObject(); } } ;// CONCATENATED MODULE: ./src/common/iServer/JoinItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class JoinItem * @deprecatedclass SuperMap.JoinItem * @category iServer Data FeatureResults * @classdesc 连接信息类。 * 该类用于矢量数据集与外部表的连接。外部表可以为另一个矢量数据集(其中纯属性数据集中没有空间几何信息)所对应的 DBMS 表,也可以是用户自建的业务表。 * 需要注意的是,矢量数据集与外部表必须属于同一数据源。表之间的联系的建立有两种方式,一种是连接(join),一种是关联(link)。 * 连接,实际上是依据相同的字段将一个外部表追加到指定的表;而关联是基于一个相同的字段定义了两个表格之间的联系,但不是实际的追加。 * 用于连接两个表的字段的名称不一定相同,但类型必须一致。当两个表格之间建立了连接,通过对主表进行操作,可以对外部表进行查询,制作专题图以及分析等。 * 当两个表格之间是一对一或多对一的关系时,可以使用 join 连接。当为多对一的关系时,允许指定多个字段之间的关联。 *(注意:JoinItem 目前支持左连接和内连接,不支持全连接和右连接,UDB 引擎不支持内连接。并且用于建立连接的两个表必须在同一个数据源下。) * @param {Object} options - 参数。 * @param {string} options.foreignTableName - 外部表的名称。 * @param {string} options.joinFilter - 矢量数据集与外部表之间的连接表达式,即设定两个表之间关联的字段。 * @param {JoinType} options.joinType - 两个表之间连接类型。 * @example 下面以 SQL 查询说明 joinItem 的使用方法: *(start code) * function queryBySQL() { * // 设置与外部表的连接信息 * var joinItem = new JoinItem({ * foreignTableName: "foreignTable", * joinFilter: "foreignTable.CONTINENT = Countries.CONTINENT", * joinType: "LEFTJOIN" * }) * var queryParam, queryBySQLParams, queryBySQLService; * // 设置查询参数,在查询参数中添加joinItem关联条件信息 * queryParam = new FilterParameter({ * name: "Countries@World", * joinItems: [joinItem] * }), * queryBySQLParams = new QueryBySQLParameters({ * queryParams: [queryParam] * }), * queryBySQLService = new QueryBySQLService(url, { * eventListeners: { "processCompleted": processCompleted, "processFailed": processFailed} * }); * queryBySQLService.processAsync(queryBySQLParams); * } * function processCompleted(queryEventArgs) {//todo} * function processFailed(e) {//todo} * (end) * @usage */ class JoinItem { constructor(options) { /** * @member {string} JoinItem.prototype.foreignTableName * @description 外部表的名称。 * 如果外部表的名称是以 “表名@数据源名” 命名方式,则该属性只需赋值表名。 * 例如:外部表 Name@changchun,Name 为表名,changchun 为数据源名称,则该属性的赋值应为:Name。 */ this.foreignTableName = null; /** * @member {string} JoinItem.prototype.joinFilter * @description 矢量数据集与外部表之间的连接表达式,即设定两个表之间关联的字段。 * 例如,将房屋面数据集(Building)的 district 字段与房屋拥有者的纯属性数据集(Owner)的 region 字段相连接, * 两个数据集对应的表名称分别为 Table_Building 和 Table_Owner, * 则连接表达式为 Table_Building.district = Table_Owner.region。 * 当有多个字段相连接时,用 AND 将多个表达式相连。 */ this.joinFilter = null; /** * @member {JoinType} JoinItem.prototype.joinType * @description 两个表之间连接类型。 * 连接类型决定了对两个表进行连接查询后返回的记录的情况。 */ this.joinType = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.JoinItem"; } /** * @function JoinItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.foreignTableName = null; me.joinFilter = null; me.joinType = null; } /** * @function JoinItem.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 */ toServerJSONObject() { var dataObj = {}; dataObj = Util.copyAttributes(dataObj, this); //joinFilter基本是个纯属性对象,这里不再做转换 return dataObj; } } ;// CONCATENATED MODULE: ./src/common/iServer/UGCSubLayer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UGCSubLayer * @deprecatedclass SuperMap.UGCSubLayer * @category iServer Map Layer * @classdesc 地图服务图层属性信息类。影像图层(Image)、专题图层(ServerTheme)、栅格图层(Grid)、矢量图层(Vector)等图层均继承该类。 * @extends {UGCMapLayer} * @param {Object} options - 参数。 * @param {DatasetInfo} options.datasetInfo - 数据集信息。 * @param {string} [options.displayFilter] - 图层显示过滤条件。 * @param {JoinItem} [options.joinItems] - 连接信息类。 * @param {string} [options.representationField] - 存储制图表达信息的字段。 * @param {LayerType} [options.ugcLayerType] - 图层类型。 * @usage */ class UGCSubLayer extends UGCMapLayer { constructor(options) { options = options || {}; super(options); /** * @member {DatasetInfo} UGCSubLayer.prototype.datasetInfo * @description 数据集信息。 */ this.datasetInfo = null; /** * @member {string} UGCSubLayer.prototype.displayFilter * @description 图层显示过滤条件。 */ this.displayFilter = null; /** * @member {JoinItem} UGCSubLayer.prototype.joinItems * @description 连接信息类。 */ this.joinItems = null; /** * @member {string} UGCSubLayer.prototype.representationField * @description 存储制图表达信息的字段。 */ this.representationField = null; /** * @member {LayerType} UGCSubLayer.prototype.ugcLayerType * @description 图层类型。 */ this.ugcLayerType = null; this.CLASS_NAME = "SuperMap.UGCSubLayer"; } /** * @function UGCSubLayer.prototype.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 */ fromJson(jsonObject) { super.fromJson(jsonObject); if (this.datasetInfo) { this.datasetInfo = new DatasetInfo(this.datasetInfo); } if (this.joinItems && this.joinItems.length) { var newJoinItems = []; for (var i = 0; i < this.joinItems.length; i++) { newJoinItems[i] = new JoinItem(this.joinItems[i]); } this.joinItems = newJoinItems; } } /** * @function UGCSubLayer.prototype.destroy * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function UGCSubLayer.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var jsonObject = super.toServerJSONObject(); if (jsonObject.joinItems) { var joinItems = []; for (var i = 0; i < jsonObject.joinItems.length; i++) { if (jsonObject.joinItems[i].toServerJSONObject) { joinItems[i] = jsonObject.joinItems[i].toServerJSONObject(); } } jsonObject.joinItems = joinItems; } if (jsonObject.datasetInfo) { if (jsonObject.datasetInfo.toServerJSONObject) { jsonObject.datasetInfo = jsonObject.datasetInfo.toServerJSONObject(); } } return jsonObject; } } ;// CONCATENATED MODULE: ./src/common/iServer/ServerTheme.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ServerTheme * @deprecatedclass SuperMap.ServerTheme * @category iServer Map Theme * @classdesc SuperMap 专题图图层类。 * @extends {UGCSubLayer} * @param {CommonTheme} theme - 专题图对象。 * @param {LonLat} themeElementPosition - 专题图元素位置。 * @usage */ class ServerTheme extends UGCSubLayer { constructor(options) { options = options || {}; super(options); /** * @member {CommonTheme} ServerTheme.prototype.theme * @description 专题图对象。 */ this.theme = null; /** * @member {LonLat} ServerTheme.prototype.themeElementPosition * @description 专题图元素位置。 */ this.themeElementPosition = null; this.CLASS_NAME = "SuperMap.ServerTheme"; } /** * @function ServerTheme.prototype.destroy * @description 释放资源,将引用资源的属性置空。 * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function ServerTheme.prototype.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 */ fromJson(jsonObject) { super.fromJson(jsonObject); var themeObj = this.theme; var themeT = themeObj && themeObj.type; switch (themeT) { case 'LABEL': this.theme = ThemeLabel.fromObj(themeObj); break; case 'UNIQUE': this.theme = ThemeUnique.fromObj(themeObj); break; case 'GRAPH': this.theme = ThemeGraph.fromObj(themeObj); break; case 'DOTDENSITY': this.theme = ThemeDotDensity.fromObj(themeObj); break; case 'GRADUATEDSYMBOL': this.theme = ThemeGraduatedSymbol.fromObj(themeObj); break; case 'RANGE': this.theme = ThemeRange.fromObj(themeObj); break; default: break; } if (this.themeElementPosition) { //待测试 this.themeElementPosition = new LonLat(this.themeElementPosition.x, this.themeElementPosition.y); } } /** * @function ServerTheme.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 */ toServerJSONObject() { //普通属性直接赋值 var jsonObject = super.toServerJSONObject(); if (jsonObject.themeElementPosition) { if (jsonObject.themeElementPosition.toServerJSONObject) { jsonObject.themeElementPosition = jsonObject.themeElementPosition.toServerJSONObject(); } } if (jsonObject.theme) { if (jsonObject.theme.toServerJSONObject) { jsonObject.theme = jsonObject.theme.toServerJSONObject(); } } return jsonObject; } } ;// CONCATENATED MODULE: ./src/common/iServer/Grid.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Grid * @deprecatedclass SuperMap.Grid * @category iServer Map Layer * @classdesc SuperMap 栅格图层类。 * @extends {UGCSubLayer} * @param {Object} options - 可选参数。 * @param {Array.} [options.colorDictionary] - 颜色对照表对象。 * @param {number} [options.brightness] - Grid 图层的亮度。 * @param {ColorGradientType} [options.colorGradientType] - 颜色渐变枚举。 * @param {ServerColor} [options.colors] - 颜色表对象。 * @param {number} [options.contrast] - Grid 图层的对比度。 * @param {GridType} [options.gridType] - 格网类型。 * @param {number} [options.horizontalSpacing] - 格网水平间隔大小。 * @param {boolean} [options.sizeFixed] - 格网是否固定大小,如果不固定大小,则格网随着地图缩放。 * @param {ServerStyle} [options.solidStyle] - 格网实线的样式。 * @param {ServerColor} [options.specialColor] - 栅格数据集无值数据的颜色。 * @param {number} [options.specialValue] - 图层的特殊值。 * @param {boolean} [options.specialValueTransparent] - 图层的特殊值(specialValue)所处区域是否透明。 * @param {number} [options.verticalSpacing] - 格网垂直间隔大小。 * @usage */ class Grid extends UGCSubLayer { constructor(options) { options = options || {}; super(options); /** * @member {Array.} Grid.prototype.colorDictionarys * @description 颜色对照表对象。 */ this.colorDictionarys = null; /** * @member {number} Grid.prototype.brightness * @description Grid 图层的亮度。 */ this.brightness = null; /** * @member {ColorGradientType} Grid.prototype.colorGradientType * @description 渐变颜色枚举值。 */ this.colorGradientType = null; /** * @member {ServerColor} Grid.prototype.colors * @description 颜色表对象。 */ this.colors = null; /** * @member {number} Grid.prototype.contrast * @description Grid 图层的对比度。 */ this.contrast = null; /** * @member {ServerStyle} Grid.prototype.dashStyle * @description 栅格数据集特殊值数据的颜色。 */ this.dashStyle = null; /** * @member {GridType} Grid.prototype.gridType * @description 格网类型。 */ this.gridType = null; /** * @member {number} Grid.prototype.horizontalSpacing * @description 格网水平间隔大小。 */ this.horizontalSpacing = null; /** * @member {boolean} Grid.prototype.sizeFixed * @description 格网是否固定大小,如果不固定大小,则格网随着地图缩放。 */ this.sizeFixed = null; /** * @member {ServerStyle} Grid.prototype.solidStyle * @description 格网实线的样式。 */ this.solidStyle = null; /** * @member {ServerColor} Grid.prototype.specialColor * @description 栅格数据集无值数据的颜色。 */ this.specialColor = null; /** * @member {number} Grid.prototype.specialValue * @description 图层的特殊值。 */ this.specialValue = null; /** * @member {boolean} Grid.prototype.specialValueTransparent * @description 图层的特殊值(specialValue)所处区域是否透明。 */ this.specialValueTransparent = null; /** * @member {number} Grid.prototype.verticalSpacing * @description 格网垂直间隔大小。 */ this.verticalSpacing = null; this.CLASS_NAME = "SuperMap.Grid"; } /** * @function Grid.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); Util.reset(this); } /** * @function Grid.prototype.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 */ fromJson(jsonObject) { super.fromJson(jsonObject); if (this.specialColor) { this.specialColor = new ServerColor(this.specialColor.red, this.specialColor.green, this.specialColor.blue); } if (this.colors) { var colors = [], color; for (var i in this.colors) { color = this.colors[i]; colors.push(new ServerColor(color.red, color.green, color.blue)); } this.colors = colors; } if (this.dashStyle) { this.dashStyle = new ServerStyle(this.dashStyle); } if (this.solidStyle) { this.solidStyle = new ServerStyle(this.solidStyle); } if (this.colorDictionary) { var colorDics = [], colorDic; for (var key in this.colorDictionary) { colorDic = this.colorDictionary[key]; colorDics.push(new ColorDictionary({elevation: key, color: colorDic})); } this.colorDictionarys = colorDics; } delete this.colorDictionary; } /** * @function Grid.prototype.toServerJSONObject * @description 转换成对应的 JSON 对象。 * @returns JSON 对象。 */ toServerJSONObject() { var jsonObject = super.toServerJSONObject(); if (jsonObject.dashStyle) { if (jsonObject.dashStyle.toServerJSONObject) { jsonObject.dashStyle = jsonObject.dashStyle.toServerJSONObject(); } } if (jsonObject.solidStyle) { if (jsonObject.solidStyle.toServerJSONObject) { jsonObject.solidStyle = jsonObject.solidStyle.toServerJSONObject(); } } return jsonObject; } } ;// CONCATENATED MODULE: ./src/common/iServer/Image.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UGCImage * @deprecatedclass SuperMap.Image * @category iServer Map Layer * @classdesc SuperMap 影像图层类 * @extends {UGCSubLayer} * @param {Object} options - 可选参数。 * @param {ColorSpaceType} [options.colorSpaceType] - 返回影像图层的色彩显示模式。 * @param {number} [options.brightness] - 影像图层的亮度。 * @param {Array.} [options.displayBandIndexes] - 返回当前影像图层显示的波段索引。 * @param {number} [options.contrast] - 影像图层的对比度。 * @param {boolean} [options.transparent] - 是否背景透明。 * @param {ServerColor} [options.transparentColor] - 返回背景透明色。 * @param {number} [options.transparentColorTolerance] - 背景透明色容限。 * @usage * @private */ class UGCImage extends UGCSubLayer { constructor(options) { options = options || {}; super(options); /** * @member {number} UGCImage.prototype.brightness * @description 影像图层的亮度。 */ this.brightness = null; /** * @member {ColorSpaceType} UGCImage.prototype.colorSpaceType * @description 返回影像图层的色彩显示模式。 */ this.colorSpaceType = null; /** * @member {number} UGCImage.prototype.contrast * @description 影像图层的对比度。 */ this.contrast = null; /** * @member {Array.} UGCImage.prototype.displayBandIndexes * @description 返回当前影像图层显示的波段索引。 */ this.displayBandIndexes = null; /** * @member {boolean} UGCImage.prototype.transparent * @description 是否背景透明。 */ this.transparent = null; /** * @member {ServerColor} UGCImage.prototype.transparentColor * @description 返回背景透明色。 */ this.transparentColor = null; /** * @member {number} UGCImage.prototype.transparentColorTolerance * @description 背景透明色容限。 */ this.transparentColorTolerance = null; this.CLASS_NAME = "SuperMap.Image"; } /** * @function UGCImage.prototype.destroy * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function UGCImage.prototype.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 */ fromJson(jsonObject) { super.fromJson(jsonObject); if (this.transparentColor) { this.transparentColor = new ServerColor(this.transparentColor.red, this.transparentColor.green, this.transparentColor.blue); } } /** * @function UGCImage.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 */ toServerJSONObject() { return super.toServerJSONObject(); } } ;// CONCATENATED MODULE: ./src/common/iServer/Vector.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Vector * @deprecatedclass SuperMap.Vector * @category iServer Map Layer * @classdesc SuperMap 矢量图层类。 * @extends {UGCSubLayer} * @param {Object} options - 可选参数。 * @param {ServerStyle} [options.style] - 矢量图层的风格。 * @usage */ class Vector_Vector extends UGCSubLayer { constructor(options) { options = options || {}; super(options); /** * @member {ServerStyle} Vector.prototype.style * @description 矢量图层的风格。 */ this.style = null; this.CLASS_NAME = "SuperMap.Vector"; } /** * @function Vector.prototype.destroy * @description 销毁对象,将其属性置空。 * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function Vector.prototype.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 */ fromJson(jsonObject) { super.fromJson(jsonObject); var sty = this.style; if (sty) { this.style = new ServerStyle(sty); } } /** * @function Vector.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象 */ toServerJSONObject() { var jsonObject = super.toServerJSONObject(); if (jsonObject.style) { if (jsonObject.style.toServerJSONObject) { jsonObject.style = jsonObject.style.toServerJSONObject(); } } return jsonObject; } } ;// CONCATENATED MODULE: ./src/common/iServer/GetLayersInfoService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GetLayersInfoService * @deprecatedclass SuperMap.GetLayersInfoService * @category iServer Map Layer * @classdesc 获取图层信息服务类构造函数。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求地图服务,URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{地图服务名}/rest/maps/{地图名}; * 如 http://localhost:8090/iserver/services/map-world/rest/maps/World 。 * 如果查询临时图层的信息,请指定完成的url,包含临时图层ID信息,如: * http://localhost:8090/iserver/services/map-world/rest/maps/World/tempLayersSet/resourceID * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @param {boolean} options.isTempLayers - 当前url对应的图层是否是临时图层。 * @usage */ class GetLayersInfoService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {boolean} GetLayersInfoService.prototype.isTempLayers * @description 当前url对应的图层是否是临时图层。 */ this.isTempLayers = false; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GetLayersInfoService"; } /** * @function GetLayersInfoService.prototype.destroy * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function GetLayersInfoService.prototype.processAsync * @description 负责将客户端的更新参数传递到服务端。 */ processAsync() { var me = this, method = "GET"; if (!me.isTempLayers) { me.url = Util.urlPathAppend(me.url, 'layers'); } me.request({ method: method, params: null, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function GetLayersInfoService.prototype.serviceProcessCompleted * @description 编辑完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ serviceProcessCompleted(result) { var me = this, existRes, layers, len; result = Util.transformResult(result); existRes = !!result && result.length > 0; layers = existRes ? result[0].subLayers.layers : null; len = layers ? layers.length : 0; me.handleLayers(len, layers); me.events.triggerEvent("processCompleted", {result: result[0]}); } /** * TODO 专题图时候可能会用到 * @function GetLayersInfoService.prototype.handleLayers * @description 处理 iServer 新增图层组数据 (subLayers.layers 中可能还会含有 subLayers.layers) * @param {number} len - subLayers.layers的长度 * @param {Array.} layers - subLayers.layers的长度数组 */ handleLayers(len, layers) { var me = this, tempLayer; if (len) { for (var i = 0; i < len; i++) { if (layers[i].subLayers && layers[i].subLayers.layers && layers[i].subLayers.layers.length > 0) { me.handleLayers(layers[i].subLayers.layers.length, layers[i].subLayers.layers); } else { var type = layers[i].ugcLayerType; switch (type) { case 'THEME': tempLayer = new ServerTheme(); tempLayer.fromJson(layers[i]); layers[i] = tempLayer; break; case 'GRID': tempLayer = new Grid(); tempLayer.fromJson(layers[i]); layers[i] = tempLayer; break; case 'IMAGE': tempLayer = new UGCImage(); tempLayer.fromJson(layers[i]); layers[i] = tempLayer; break; case 'VECTOR': tempLayer = new Vector_Vector(); tempLayer.fromJson(layers[i]); layers[i] = tempLayer; break; default: break; } } } } } } ;// CONCATENATED MODULE: ./src/common/iServer/InterpolationAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class InterpolationAnalystParameters * @deprecatedclass SuperMap.InterpolationAnalystParameters * @category iServer SpatialAnalyst InterpolationAnalyst * @classdesc 插值分析参数类。 * @param {Object} options - 参数。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} options.bounds - 插值分析的范围,用于确定结果栅格数据集的范围。 * @param {string} options.outputDatasetName - 插值分析结果数据集的名称。 * @param {string} options.outputDatasourceName - 插值分析结果数据源的名称。 * @param {string} [options.zValueFieldName] - 进行插值分析的字段名称,插值分析不支持文本类型的字段。 * @param {string} [options.dataset] - 待分析的数据集名称。当插值分析类型(InterpolationAnalystType)为 dataset 时,此为必选参数。 * @param {Array.>} [options.inputPoints] - 用于做插值分析的离散点集合。当插值分析类型(InterpolationAnalystType)为 geometry 时,此参数为必设参数。 * @param {number} [options.searchRadius=0] - 查找半径,即参与运算点的查找范围,与点数据集单位相同。 * @param {number} [options.zValueScale=1] - 进行插值分析值的缩放比率。 * @param {number} [options.resolution] - 插值结果栅格数据集的分辨率,即一个像元所代表的实地距离,与点数据集单位相同。 * @param {FilterParameter} [options.filterQueryParameter] - 属性过滤条件。 * @param {PixelFormat} [options.pixelFormat] - 指定结果栅格数据集存储的像素格式。 * @param {string} [options.InterpolationAnalystType="dataset"] - 插值分析类型("dataset" 或 "geometry")。 * @usage */ class InterpolationAnalystParameters { constructor(options) { if (!options) { return; } /** * @member {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} InterpolationAnalystParameters.prototype.bounds * @description 插值分析的范围,用于确定结果栅格数据集的范围。 * 如果缺省,则默认为原数据集的范围。鉴于此插值方法为内插方法,原数据集的范围内的插值结果才相对有参考价值, * 因此建议此参数不大于原数据集范围。 */ this.bounds = null; /** * @member {number} [InterpolationAnalystParameters.prototype.searchRadius=0] * @description 查找半径,即参与运算点的查找范围,与点数据集单位相同。 * 计算某个位置的 Z 值时,会以该位置为圆心,以查找范围的值为半径,落在这个范围内的采样点都将参与运算。 * 该值需要根据待插值点数据的分布状况和点数据集范围进行设置。 */ this.searchRadius = 0; /** * @member {string} InterpolationAnalystParameters.prototype.zValueFieldName * @description 数据集插值分析中,用于指定进行插值分析的目标字段名,插值分析不支持文本类型的字段。 * 含义为每个插值点在插值过程中的权重,可以将所有点此字段值设置为 1,即所有点在整体插值中权重相同。 * 当插值分析类型(InterpolationAnalystType)为 dataset 时,此为必选参数。 */ this.zValueFieldName = null; /** * @member {number} [InterpolationAnalystParameters.prototype.zValueScale=1] * @description 用于进行插值分析值的缩放比率。 * 参加插值分析的值将乘以该参数值后再进行插值,也就是对进行插值分析的值进行统一的扩大或缩小。 */ this.zValueScale = 1; /** * @member {number} InterpolationAnalystParameters.prototype.resolution * @description 插值结果栅格数据集的分辨率,即一个像元所代表的实地距离,与点数据集单位相同。 * 该值不能超过待分析数据集的范围边长。 * 且该值设置时,应该考虑点数据集范围大小来取值,一般为结果栅格行列值(即结果栅格数据集范围除以分辨率),在 500 以内可以较好地体现密度走势。 */ this.resolution = null; /** * @member {FilterParameter} [InterpolationAnalystParameters.prototype.filterQueryParameter] * @description 过滤条件,对分析数据集中的点进行过滤,设置为 null 表示对数据集中的所有点进行分析。 */ this.filterQueryParameter = null; /** * @member {string} InterpolationAnalystParameters.prototype.outputDatasetName * @description 插值分析结果数据集的名称。 */ this.outputDatasetName = null; /** * @member {string} InterpolationAnalystParameters.prototype.outputDatasourceName * @description 插值分析结果数据源的名称。 */ this.outputDatasourceName = null; /** * @member {PixelFormat} [InterpolationAnalystParameters.prototype.pixelFormat] * @description 指定结果栅格数据集存储的像素格式。支持存储的像素格式有 BIT16、BIT32、DOUBLE、SINGLE、UBIT1、UBIT4、UBIT8、UBIT24、UBIT32。 */ this.pixelFormat = null; /** * @member {string} [InterpolationAnalystParameters.prototype.dataset] * @description 用来做插值分析的数据源中数据集的名称,该名称用形如 "数据集名称@数据源别名" 形式来表示。 * 当插值分析类型(InterpolationAnalystType)为 dataset 时,此为必选参数。 */ this.dataset = null; /** * @member {Array.>} [InterpolationAnalystParameters.prototype.inputPoints] * @description 用于做插值分析的离散点(离散点包括Z值)集合。 * 当插值分析类型(InterpolationAnalystType)为 geometry 时,此参数为必设参数。 * 通过离散点直接进行插值分析不需要指定输入数据集inputDatasourceName,inputDatasetName以及zValueFieldName。 */ this.inputPoints = null; /** * @member {string} [InterpolationAnalystParameters.prototype.InterpolationAnalystType="dataset"] * @description 插值分析类型。插值分析包括数据集插值分析和几何插值分析两类, * "dataset" 表示对数据集进行插值分析,"geometry" 表示对离散点数组进行插值分析。 */ this.InterpolationAnalystType = "dataset"; /** * @member {ClipParameter} InterpolationAnalystParameters.prototype.clipParam * @description 对插值分析结果进行裁剪的参数。 */ this.clipParam = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.InterpolationAnalystParameters"; } /** * @function InterpolationAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.bounds = null; me.searchRadius = null; me.zValueFieldName = null; me.zValueScale = null; me.resolution = null; me.filterQueryParameter = null; me.outputDatasetName = null; me.pixelFormat = null; } /** * @function InterpolationAnalystParameters.toObject * @param {InterpolationAnalystParameters} interpolationAnalystParameters - 插值分析参数类。 * @param {InterpolationAnalystParameters} tempObj - 插值分析参数对象。 * @description 将插值分析参数对象转换成 JSON 对象。 * @returns JSON 对象。 */ static toObject(interpolationAnalystParameters, tempObj) { for (var name in interpolationAnalystParameters) { if (name === "inputPoints" && interpolationAnalystParameters.InterpolationAnalystType === "geometry") { var objs = []; for (var i = 0; i < interpolationAnalystParameters.inputPoints.length; i++) { var item = interpolationAnalystParameters.inputPoints[i]; var obj = { x: item.x, y: item.y, z: item.tag }; objs.push(obj); } tempObj[name] = objs; } else { tempObj[name] = interpolationAnalystParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/InterpolationRBFAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class InterpolationRBFAnalystParameters * @deprecatedclass SuperMap.InterpolationRBFAnalystParameters * @category iServer SpatialAnalyst InterpolationAnalyst * @classdesc 样条插值(径向基函数插值法)分析参数类。 * @extends {InterpolationAnalystParameters} * @param {Object} options - 参数。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} options.bounds - 插值分析的范围,用于确定结果栅格数据集的范围。 * @param {string} options.searchMode - 插值运算时,查找参与运算点的方式,有固定点数查找、定长查找、块查找。 * @param {string} options.outputDatasetName - 插值分析结果数据集的名称。 * @param {string} options.outputDatasourceName - 插值分析结果数据源的名称。 * @param {string} [options.zValueFieldName] - 存储用于进行插值分析的字段名称,插值分析不支持文本类型的字段。当插值分析类型(SuperMap.InterpolationAnalystType)为 dataset 时,此为必选参数。 * @param {number} [options.smooth=0.1] - 光滑系数,该值表示插值函数曲线与点的逼近程度,值域为0到1。 * @param {number} [options.tension=40] - 张力系数,用于调整结果栅格数据表面的特性。 * @param {number} [options.expectedCount=12] - 【固定点数查找】方式下,设置参与插值运算的点数。 * @param {number} [options.searchRadius=0] - 【定长查找】方式下,设置参与运算点的查找范围。 * @param {number} [options.maxPointCountForInterpolation=200] - 【块查找】方式下,设置最多参与插值的点数。 * @param {number} [options.maxPointCountInNode=50] - 【块查找】方式下,设置单个块内最多参与运算点数。 * @param {number} [options.zValueScale=1] - 用于进行插值分析值的缩放比率。 * @param {number} [options.resolution] - 插值结果栅格数据集的分辨率,即一个像元所代表的实地距离,与点数据集单位相同。 * @param {FilterParameter} [options.filterQueryParameter] - 属性过滤条件。 * @param {string} [options.pixelFormat] - 指定结果栅格数据集存储的像素格式。 * @param {string} [options.dataset] - 要用来做插值分析的数据源中数据集的名称。该名称用形如”数据集名称@数据源别名”形式来表示。当插值分析类型(InterpolationAnalystType)为 dataset 时。此为必选参数。 * @param {Array.>} [options.inputPoints] - 用于做插值分析的离散点集合。当插值分析类型(InterpolationAnalystType)为 geometry 时。此为必选参数。 * @example * var myInterpolationRBFAnalystParameters = new InterpolationRBFAnalystParameters({ * dataset:"SamplesP@Interpolation", * smooth: 0.1, * tension: 40, * searchMode: "QUADTREE", * maxPointCountForInterpolation: 20, * maxPointCountInNode: 5, * pixelFormat: "BIT16", * zValueFieldName: "AVG_TMP", * resolution: 3000, * filterQueryParameter: { * attributeFilter: "" * }, * outputDatasetName: "myRBF" * }); * @usage */ class InterpolationRBFAnalystParameters extends InterpolationAnalystParameters { constructor(options) { super(options); /** * @member {number} [InterpolationRBFAnalystParameters.prototype.smooth=0.1] * @description 光滑系数,值域为 0 到 1,常用取值如 0、0.001、0.01、0.1、和 0.5。 * 该值表示插值函数曲线与点的逼近程度,此数值越大,函数曲线与点的偏差越大,反之越小。 */ this.smooth = 0.1; /** * @member {number} [InterpolationRBFAnalystParameters.prototype.tension=40] * @description 张力系数,常用取值如 0、1、5 和 10。 * 用于调整结果栅格数据表面的特性,张力越大,插值时每个点对计算结果影响越小,反之越大。 */ this.tension = 40; /** * @member {SearchMode} InterpolationRBFAnalystParameters.prototype.searchMode * @description 插值运算时,查找参与运算点的方式,有固定点数查找、定长查找、块查找。必设参数。 * 具体如下: * {KDTREE_FIXED_COUNT} 使用 KDTREE 的固定点数方式查找参与内插分析的点。 * {KDTREE_FIXED_RADIUS} 使用 KDTREE 的定长方式查找参与内插分析的点。 * {QUADTREE} 使用 QUADTREE 方式查找参与内插分析的点(块查找)。 */ this.searchMode = null; /** * @member {number} [InterpolationRBFAnalystParameters.prototype.expectedCount=12] * @description 【固定点数查找】方式下,设置待查找的点数,即参与插值运算的点数。 */ this.expectedCount = 12; /** * @member {number} [InterpolationRBFAnalystParameters.prototype.maxPointCountForInterpolation=200] * @description 【块查找】方式下,最多参与插值的点数。 */ this.maxPointCountForInterpolation = 200; /** * @member {number} [InterpolationRBFAnalystParameters.prototype.maxPointCountInNode=50] * @description 【块查找】方式下,单个块内最多参与运算点数。 */ this.maxPointCountInNode = 50; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.InterpolationRBFAnalystParameters"; } /** * @function InterpolationRBFAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.smooth = null; me.tension = null; me.searchMode = null; me.expectedCount = null; me.maxPointCountForInterpolation = null; me.maxPointCountInNode = null; } /** * @function InterpolationRBFAnalystParameters.toObject * @param {InterpolationRBFAnalystParameters} datasetInterpolationRBFAnalystParameters - 样条插值(径向基函数插值法)分析参数类。 * @param {InterpolationRBFAnalystParameters} tempObj - 样条插值(径向基函数插值法)分析参数对象。 * @description 将样条插值(径向基函数插值法)分析参数对象转换为 JSON 对象。 * @returns JSON 对象。 */ static toObject(datasetInterpolationRBFAnalystParameters, tempObj) { for (var name in datasetInterpolationRBFAnalystParameters) { tempObj[name] = datasetInterpolationRBFAnalystParameters[name]; } } } ;// CONCATENATED MODULE: ./src/common/iServer/InterpolationDensityAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class InterpolationDensityAnalystParameters * @deprecatedclass SuperMap.InterpolationDensityAnalystParameters * @category iServer SpatialAnalyst InterpolationAnalyst * @classdesc 点密度插值分析参数类。 * @param {Object} options - 参数。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} options.bounds - 插值分析的范围,用于确定结果栅格数据集的范围。 * @param {string} options.outputDatasourceName - 插值分析结果数据源的名称。 * @param {string} options.outputDatasetName - 插值分析结果数据集的名称。 * @param {number} [options.searchRadius=0] - 查找半径,即参与运算点的查找范围,与点数据集单位相同。 * @param {string} [options.zValueFieldName] - 进行插值分析的字段名称,插值分析不支持文本类型的字段。当插值分析类型(InterpolationAnalystParameters.prototype.InterpolationAnalystType)为 dataset 时。此为必选参数。 * @param {number} [options.zValueScale=1] - 进行插值分析值的缩放比率。 * @param {number} [options.resolution] - 插值结果栅格数据集的分辨率,即一个像元所代表的实地距离,与点数据集单位相同。 * @param {FilterParameter} [options.filterQueryParameter] - 属性过滤条件。 * @param {string} [options.pixelFormat] - 指定结果栅格数据集存储的像素格式。 * @param {string} [options.dataset] - 用来做插值分析的数据源中数据集的名称,该名称用形如 "数据集名称@数据源别名" 形式来表示。当插值分析类型(InterpolationAnalystParameters.prototype.InterpolationAnalystType)为 dataset 时,此为必选参数。 * @param {Array.>} [options.inputPoints] - 用于做插值分析的离散点集合。当插值分析类型(InterpolationAnalystParameters.prototype.InterpolationAnalystType)为 geometry 时,此为必选参数。 * @extends {InterpolationAnalystParameters} * @example * var myInterpolationDensityAnalystParameters = new InterpolationDensityAnalystParameters({ * dataset: "SamplesP@Interpolation", * searchRadius: "100000", * pixelFormat: "BIT16", * zValueFieldName: "AVG_TMP", * resolution: 3000, * filterQueryParameter: { * attributeFilter: "" * }, * outputDatasetName: "myDensity" * }); * @usage */ class InterpolationDensityAnalystParameters extends InterpolationAnalystParameters { constructor(options) { super(options); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.InterpolationDensityAnalystParameters"; } /** * @function InterpolationDensityAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/iServer/InterpolationIDWAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class InterpolationIDWAnalystParameters * @deprecatedclass SuperMap.InterpolationIDWAnalystParameters * @category iServer SpatialAnalyst InterpolationAnalyst * @classdesc 反距离加权插值(IDW)分析参数类。 * @param {Object} options - 参数。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} options.bounds - 插值分析的范围,用于确定结果栅格数据集的范围。 * @param {string} options.searchMode - 插值运算时,查找参与运算点的方式,支持固定点数查找、定长查找。 * @param {string} options.outputDatasetName - 插值分析结果数据集的名称。 * @param {string} options.outputDatasourceName - 插值分析结果数据源的名称。 * @param {string} [options.zValueFieldName] - 进行插值分析的字段名称,插值分析不支持文本类型的字段。当插值分析类型(SuperMap.InterpolationAnalystType)为 dataset 时,此为必选参数。 * @param {number} [options.expectedCount=12] - 【固定点数查找】方式下,设置待查找的点数,即参与插值运算的点数。 * @param {number} [options.searchRadius=0] - 【定长查找】方式下,设置查找半径,即参与运算点的查找范围,与点数据集单位相同。 * @param {number} [options.power=2] - 距离权重计算的幂次。 * @param {number} [options.zValueScale=1] - 用于进行插值分析值的缩放比率。 * @param {number} [options.resolution] - 插值结果栅格数据集的分辨率,即一个像元所代表的实地距离,与点数据集单位相同。 * @param {FilterParameter} [options.filterQueryParameter] - 属性过滤条件。 * @param {string} [options.pixelFormat] - 指定结果栅格数据集存储的像素格式。 * @param {string} [options.dataset] - 要用来做插值分析的数据源中数据集的名称。该名称用形如”数据集名称@数据源别名”形式来表示。当插值分析类型(SuperMap.InterpolationAnalystType)为 dataset 时,此为必选参数。 * @param {Array.>} [options.inputPoints] - 用于做插值分析的离散点集合。当插值分析类型(SuperMap.InterpolationAnalystType)为 geometry 时,此为必选参数。 * @extends {InterpolationAnalystParameters} * @example 例如: * var myInterpolationIDWAnalystParameters = new InterpolationIDWAnalystParameters({ * dataset:"SamplesP@Interpolation", * power: 2, * searchMode: "KDTREE_FIXED_COUNT", * expectedCount: 12, * pixelFormat: "BIT16", * zValueFieldName: "AVG_TMP", * resolution: 3000, * filterQueryParameter: { * attributeFilter: "" * }, * outputDatasetName: "myIDW" * }); * @usage */ class InterpolationIDWAnalystParameters extends InterpolationAnalystParameters { constructor(options) { super(options); /** * @member {number} [InterpolationIDWAnalystParameters.prototype.power=2] * @description 距离权重计算的幂次。 * 该值决定了权值下降的速度,幂次越大,随距离的增大权值下降越快,距离预测点越远的点的权值也越小。 * 理论上,参数值必须大于0,但是0.5到3之间时运算结果更合理,因此推荐值为0.5~3。 */ this.power = 2; /** * @member {SearchMode} InterpolationIDWAnalystParameters.prototype.searchMode * @description 插值运算时,查找参与运算点的方式,支持固定点数查找、定长查找。 * 具体如下: * {KDTREE_FIXED_COUNT} 使用 KDTREE 的固定点数方式查找参与内插分析的点。 * {KDTREE_FIXED_RADIUS} 使用 KDTREE 的定长方式查找参与内插分析的点。 */ this.searchMode = null; /** * @member {number} [InterpolationIDWAnalystParameters.prototype.expectedCount=12] * @description 【固定点数查找】方式下,设置待查找的点数,即参与插值运算的点数。 */ this.expectedCount = 12; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.InterpolationIDWAnalystParameters"; } /** * @function InterpolationIDWAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.power = null; me.searchMode = null; me.expectedCount = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/InterpolationKrigingAnalystParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class InterpolationKrigingAnalystParameters * @deprecatedclass SuperMap.InterpolationKrigingAnalystParameters * @category iServer SpatialAnalyst InterpolationAnalyst * @classdesc 克吕金插值分析参数类。通过该类可以设置克吕金插值分析所需的参数。 * 克吕金(Kriging)法为地统计学上一种空间数据内插处理方法,主要的目的是利用各数据点间变异数(variance)的大小来推求某一未知点与各已知点的权重关系, * 再由各数据点的值和其与未知点的权重关系推求未知点的值。Kriging 法最大的特色不仅是提供一个最小估计误差的预测值,并且可明确地指出误差值的大小。 * 一般而言,许多地质参数,如地形面,本身即具有连续性,故在一段距离内的任两点必有空间上的关系。反之,在一不规则面上的两点若相距甚远, * 则在统计意义上可视为互为独立 (stastically indepedent)。这种随距离而改变的空间上连续性,可用半变异图 (semivariogram) 来表现。 * 因此,若想由已知的散乱点来推求某一未知点的值,则可利用半变异图推求各已知点与未知点的空间关系,即以下四个参数:
* 1.块金值(nugget):当采样点间距为0时,理论上半变异函数值为0,但时间上两采样点非常接近时半变异函数值并不为0,即产生了块金效应, * 对应的半变异函数值为块金值。块金值可能由于测量误差或者空间变异产生。
* 2.基台值(sill):随着采样点间距的不断增大,半变异函数的值趋向一个稳定的常数,该常数成为基台值。到达基台值后,半变异函数的值不再随采样点间距而改变, * 即大于此间距的采样点不再具有空间相关性。
* 3.偏基台值:基台值与块金值的差值。
* 4.自相关阈值(range):也称变程,是半变异函数值达到基台值时,采样点的间距。超过自相关阈值的采样点不再具有空间相关性,将不对预测结果产生影响。
* 然后,由此空间参数推求半变异数,由各数据点间的半变异数可推求未知点与已知点间的权重关系,进而推求出未知点的值。 * 克吕金法的优点是以空间统计学作为其坚实的理论基础,物理含义明确;不但能估计测定参数的空间变异分布,而且还可以估算参数的方差分布。克吕金法的缺点是计算步骤较烦琐, * 计算量大,且变异函数有时需要根据经验人为选定。 * * 由上述可知,半变异函数是克吕金插值的关键,因此选择合适的半变异函数模型非常重要,SuperMap 提供了以下三种半变异函数模型:
* 1.指数型(EXPONENTIAL):适用于空间相关关系随样本间距的增加呈指数递减的情况,其空间自相关关系在样本间距的无穷远处完全消失。
* 2.球型(SPHERICAL):适用于空间自相关关系随样本间距的增加而逐渐减少,直到超出一定的距离时空间自相关关系消失的情况。
* 3.高斯型(GAUSSIAN):适用于半变异函数值渐进地逼近基台值的情况。
* * 半变异函数中,有一个关键参数即插值的字段值的期望(平均值),由于对于此参数的不同处理方法而衍生出了不同的 Kriging 方法。SuperMap的插值功能基于以下三种常用 Kriging 算法:
* 1.简单克吕金(Simple Kriging):该方法假定用于插值的字段值的期望(平均值)为已知的某一常数。
* 2.普通克吕金(Kriging):该方法假定用于插值的字段值的期望(平均值)未知且恒定。它利用一定的数学函数,通过对给定的空间点进行拟合来估算单元格的值, * 生成格网数据集。它不仅可以生成一个表面,还可以给出预测结果的精度或者确定性的度量。因此,此方法计算精度较高,常用于地学领域。
* 3.泛克吕金(Universal Kriging):该方法假定用于插值的字段值的期望(平均值)是未知的变量。在样点数据中存在某种主导趋势且该趋势可以通过某一个确定 * 的函数或者多项式进行拟合的情况下,适用泛克吕金插值法。
* @param {Object} options - 参数。 * @param {string} options.type - 克吕金插值的类型。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} options.bounds - 插值分析的范围,用于确定结果栅格数据集的范围。 * @param {string} options.searchMode - 插值运算时,查找参与运算点的方式,有固定点数查找、定长查找、块查找。 * @param {string} options.outputDatasetName - 插值分析结果数据集的名称。 * @param {string} options.outputDatasourceName - 插值分析结果数据源的名称。 * @param {string} [options.zValueFieldName] - 存储用于进行插值分析的字段名称,插值分析不支持文本类型的字段。当插值分析类型(InterpolationAnalystParameters.prototype.InterpolationAnalystType)为 dataset 时,此为必选参数。 * @param {number} [options.mean] - 【简单克吕金】类型下,插值字段的平均值。 * @param {number} [options.angle=0] - 克吕金算法中旋转角度值。 * @param {number} [options.nugget=0] - 克吕金算法中块金效应值。 * @param {number} [options.range=0] - 克吕金算法中自相关阈值,单位与原数据集单位相同。 * @param {number} [options.sill=0] - 克吕金算法中基台值。 * @param {string} [options.variogramMode="SPHERICAL"] - 克吕金插值时的半变函数类型。 * @param {string} [options.exponent='exp1'] - 【泛克吕金】类型下,用于插值的样点数据中趋势面方程的阶数,可选值为 exp1、exp2。 * @param {number} [options.expectedCount=12] - 【固定点数查找】方式下,设置待查找的点数;【定长查找】方式下,设置查找的最小点数。 * @param {number} [options.searchRadius=0] - 【定长查找】方式下,设置参与运算点的查找范围。 * @param {number} [options.maxPointCountForInterpolation=200] - 【块查找】方式下,设置最多参与插值的点数。 * @param {number} [options.maxPointCountInNode=50] - 【块查找】方式下,设置单个块内最多参与运算点数。 * @param {number} [options.zValueScale=1] - 用于进行插值分析值的缩放比率。 * @param {number} [options.resolution] - 插值结果栅格数据集的分辨率,即一个像元所代表的实地距离,与点数据集单位相同。 * @param {FilterParameter} [options.filterQueryParameter] - 属性过滤条件。 * @param {string} [options.pixelFormat] - 指定结果栅格数据集存储的像素格式。 * @param {string} [options.dataset] - 要用来做插值分析的数据源中数据集的名称。该名称用形如 ”数据集名称@数据源别名” 形式来表示。当插值分析类型(InterpolationAnalystParameters.prototype.InterpolationAnalystType)为 dataset 时。 * @param {Array.>} [options.inputPoints] - 用于做插值分析的离散点集合。当插值分析类型(InterpolationAnalystParameters.prototype.InterpolationAnalystType)为 geometry 时。 * @extends {InterpolationAnalystParameters} * @example 例如: * var myInterpolationKrigingAnalystParameters = new InterpolationKrigingAnalystParameters({ * dataset:"SamplesP@Interpolation", * type: "KRIGING", * angle: 0, * mean: 5, * nugget: 30, * range: 50, * sill: 300, * variogramMode: "EXPONENTIAL", * searchMode: "QUADTREE", * maxPointCountForInterpolation: 20, * maxPointCountInNode: 5, * pixelFormat: "BIT16", * zValueFieldName: "AVG_TMP", * resolution: 30000, * filterQueryParameter: { * attributeFilter: "" * }, * outputDatasetName: "myKriging" * }); * @usage */ class InterpolationKrigingAnalystParameters extends InterpolationAnalystParameters { constructor(options) { super(options); /** * @member {InterpolationAlgorithmType} InterpolationKrigingAnalystParameters.prototype.type * @description 克吕金插值的类型。 * 具体如下:
* {KRIGING} 普通克吕金插值法。 * {SimpleKriging} 简单克吕金插值法。 * {UniversalKriging} 泛克吕金插值法。 */ this.type = null; /** * @member {number} InterpolationKrigingAnalystParameters.prototype.mean * @description 【简单克吕金】方式下,插值字段的平均值。 * 即采样点插值字段值总和除以采样点数目。 */ this.mean = null; /** * @member {number} [InterpolationKrigingAnalystParameters.prototype.angle=0] * @description 克吕金算法中旋转角度值。 * 此角度值指示了每个查找邻域相对于水平方向逆时针旋转的角度。 */ this.angle = 0; /** * @member {number} [InterpolationKrigingAnalystParameters.prototype.nugget=0] * @description 克吕金算法中块金效应值。 */ this.nugget = 0; /** * @member {number} [InterpolationKrigingAnalystParameters.prototype.range=0] * @description 克吕金算法中自相关阈值,单位与原数据集单位相同。 */ this.range = 0; /** * @member {number} [InterpolationKrigingAnalystParameters.prototype.sill=0] * @description 克吕金算法中基台值。 */ this.sill = 0; /** * @member {VariogramMode} [InterpolationKrigingAnalystParameters.prototype.variogramMode=VariogramMode.SPHERICAL] * @description 克吕金插值时的半变函数类型。 * 用户所选择的半变函数类型会影响未知点的预测,特别是曲线在原点处的不同形状有重要意义。 * 曲线在原点处越陡,则较近领域对该预测值的影响就越大,因此输出表面就会越不光滑。 */ this.variogramMode = VariogramMode.SPHERICAL; /** * @member {Exponent} [InterpolationKrigingAnalystParameters.prototype.exponent=Exponent.EXP1] * @description 【泛克吕金】类型下,用于插值的样点数据中趋势面方程的阶数。 */ this.exponent = Exponent.EXP1; /** * @member {SearchMode} InterpolationKrigingAnalystParameters.prototype.searchMode * @description 插值运算时,查找参与运算点的方式,有固定点数查找、定长查找、块查找。此为必选参数。 * 简单克吕金和泛克吕金不支持块查找。 * 具体如下:
* {KDTREE_FIXED_COUNT} 使用 KDTREE 的固定点数方式查找参与内插分析的点。
* {KDTREE_FIXED_RADIUS} 使用 KDTREE 的定长方式查找参与内插分析的点。
* {QUADTREE} 使用 QUADTREE 方式查找参与内插分析的点(块查找)。 */ this.searchMode = null; /** * @member {number} [InterpolationKrigingAnalystParameters.prototype.expectedCount=12] * @description 【固定点数查找】方式下,设置待查找的点数,即参与插值运算的点数,默认值为12。 * 【定长查找】方式下,设置查找的最小点数,默认值为12。 */ this.expectedCount = 12; /** * @member {number} [InterpolationKrigingAnalystParameters.prototype.maxPointCountForInterpolation=200] * @description 【块查找】方式下,最多参与插值的点数。 * 仅用于普通克吕金插值,简单克吕金和泛克吕金不支持块查找。 */ this.maxPointCountForInterpolation = 200; /** * @member {number} [InterpolationKrigingAnalystParameters.prototype.maxPointCountInNode=50] * @description 【块查找】方式下,设置单个块内最多参与运算点数。 * 仅用于普通克吕金插值,简单克吕金和泛克吕金不支持块查找。 */ this.maxPointCountInNode = 50; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.InterpolationKrigingAnalystParameters"; } /** * @function InterpolationKrigingAnalystParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.type = null; me.mean = null; me.angle = null; me.nugget = null; me.range = null; me.sill = null; me.variogramMode = null; me.exponent = null; me.searchMode = null; me.expectedCount = null; me.maxPointCountForInterpolation = null; me.maxPointCountInNode = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/InterpolationAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class InterpolationAnalystService * @deprecatedclass SuperMap.InterpolationAnalystService * @category iServer SpatialAnalyst InterpolationAnalyst * @classdesc 插值分析服务类。 * 插值分析可以将有限的采样点数据,通过插值算法对采样点周围的数值情况进行预测,可以掌握研究区域内数据的总体分布状况,从而使采样的离散点不仅仅反映其所在位置的数值情况, * 还可以反映区域的数值分布。目前SuperMap iServer的插值功能提供从点数据集插值得到栅格数据集的功能,支持以下常用的内插方法, * 包括:反距离加权插值、克吕金(Kriging)插值法、样条(径向基函数,Radial Basis Function)插值、点密度插值。 * @param {string} url - 服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 例如: * (start code) * var myTInterpolationAnalystService = new InterpolationAnalystService(url); * myTInterpolationAnalystService.events.on({ * "processCompleted": processCompleted, * "processFailed": processFailed * } * ); * (end) * @usage */ class InterpolationAnalystService extends SpatialAnalystBase { constructor(url, options) { super(url, options); /** * @member {string} InterpolationAnalystService.prototype.mode * @description 插值分析类型。 */ this.mode = null; if (options) { Util.extend(this, options); } } /** * @function InterpolationAnalystService.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); this.mode = null; this.CLASS_NAME = "SuperMap.InterpolationAnalystService"; } /** * @function InterpolationAnalystService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {InterpolationDensityAnalystParameters|InterpolationIDWAnalystParameters|InterpolationRBFAnalystParameters|InterpolationKrigingAnalystParameters} parameter - 插值分析参数类。 */ processAsync(parameter) { var parameterObject = {}; var me = this; if (parameter instanceof InterpolationDensityAnalystParameters) { me.mode = 'Density'; if (parameter.InterpolationAnalystType === 'geometry') { me.url = Util.urlPathAppend(me.url, 'geometry/interpolation/density'); } else { me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/interpolation/density'); } } else if (parameter instanceof InterpolationIDWAnalystParameters) { me.mode = 'IDW'; if (parameter.InterpolationAnalystType === 'geometry') { me.url = Util.urlPathAppend(me.url, 'geometry/interpolation/idw'); } else { me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/interpolation/idw'); } } else if (parameter instanceof InterpolationRBFAnalystParameters) { me.mode = 'RBF'; if (parameter.InterpolationAnalystType === 'geometry') { me.url = Util.urlPathAppend(me.url, 'geometry/interpolation/rbf'); } else { me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/interpolation/rbf'); } } else if (parameter instanceof InterpolationKrigingAnalystParameters) { me.mode = 'Kriging'; if (parameter.InterpolationAnalystType === 'geometry') { me.url = Util.urlPathAppend(me.url, 'geometry/interpolation/kriging'); } else { me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/interpolation/kriging'); } } InterpolationAnalystParameters.toObject(parameter, parameterObject); var jsonParameters = Util.toJSON(parameterObject); me.url = Util.urlAppend(me.url, 'returnContent=true'); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/KernelDensityJobParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class KernelDensityJobParameter * @deprecatedclass SuperMap.KernelDensityJobParameter * @category iServer ProcessingService DensityAnalyst * @classdesc 核密度分析服务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {string} options.fields - 权重索引。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} [options.query] - 分析范围(默认为全图范围)。 * @param {number} [options.resolution=80] - 分辨率。 * @param {number} [options.method=0] - 分析方法。 * @param {number} [options.meshType=0] - 分析类型。 * @param {number} [options.radius=300] - 分析的影响半径。 * @param {OutputSetting} [options.output] - 输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class KernelDensityJobParameter { constructor(options) { if (!options) { return; } /** * @member {string} KernelDensityJobParameter.prototype.datasetName * @description 数据集名。 */ this.datasetName = ""; /** * @member {SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject} [KernelDensityJobParameter.prototype.query] * @description 分析范围。 */ this.query = ""; /** * @member {number} [KernelDensityJobParameter.prototype.resolution=80] * @description 网格大小。 */ this.resolution = 80; /** * @member {number} [KernelDensityJobParameter.prototype.method=0] * @description 分析方法。 */ this.method = 0; /** * @member {number} [KernelDensityJobParameter.prototype.meshType=0] * @description 分析类型。 */ this.meshType = 0; /** * @member {string} KernelDensityJobParameter.prototype.fields * @description 权重索引。 */ this.fields = ""; /** * @member {number} [KernelDensityJobParameter.prototype.radius=300] * @description 分析的影响半径。 */ this.radius = 300; /** * @member {AnalystSizeUnit} [KernelDensityJobParameter.prototype.meshSizeUnit=AnalystSizeUnit.METER] * @description 网格大小单位。 */ this.meshSizeUnit = AnalystSizeUnit.METER; /** * @member {AnalystSizeUnit} [KernelDensityJobParameter.prototype.radiusUnit=AnalystSizeUnit.METER] * @description 搜索半径单位。 */ this.radiusUnit = AnalystSizeUnit.METER; /** * @member {AnalystAreaUnit} [KernelDensityJobParameter.prototype.areaUnit=AnalystAreaUnit.SQUAREMILE] * @description 面积单位。 */ this.areaUnit = AnalystAreaUnit.SQUAREMILE; /** * @member {OutputSetting} KernelDensityJobParameter.prototype.output * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [KernelDensityJobParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.KernelDensityJobParameter"; } /** * @function KernelDensityJobParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.datasetName = null; this.query = null; this.resolution = null; this.method = null; this.radius = null; this.meshType = null; this.fields = null; this.meshSizeUnit = null; this.radiusUnit = null; this.areaUnit = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters) { this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function KernelDensityJobParameter.toObject * @param {KernelDensityJobParameter} kernelDensityJobParameter - 核密度分析服务参数类。 * @param {KernelDensityJobParameter} tempObj - 核密度分析服务参数对象。 * @description 将核密度分析服务参数对象转换为 JSON 对象。 * @returns JSON 对象。 */ static toObject(kernelDensityJobParameter, tempObj) { for (var name in kernelDensityJobParameter) { if (name === "datasetName") { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = kernelDensityJobParameter[name]; continue; } if (name === "output") { tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = kernelDensityJobParameter[name]; continue; } tempObj['analyst'] = tempObj['analyst'] || {}; if (name === 'query' && kernelDensityJobParameter[name]) { tempObj['analyst'][name] = kernelDensityJobParameter[name].toBBOX(); } else { tempObj['analyst'][name] = kernelDensityJobParameter[name]; } if (name === 'mappingParameters') { tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = kernelDensityJobParameter[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/KernelDensityJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class KernelDensityJobsService * @deprecatedclass SuperMap.KernelDensityJobsService * @category iServer ProcessingService DensityAnalyst * @classdesc 核密度分析服务类 * @extends {ProcessingServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class KernelDensityJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/density'); this.CLASS_NAME = "SuperMap.KernelDensityJobsService"; } /** * @function KernelDensityJobsService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function KernelDensityJobsService.prototype.getKernelDensityJobs * @description 获取核密度分析任务 */ getKernelDensityJobs() { super.getJobs(this.url); } /** * @function KernelDensityJobsService.prototype.getKernelDensityJobs * @description 获取指定id的核密度分析服务 * @param {string} id - 指定要获取数据的id */ getKernelDensityJob(id) { super.getJobs(Util.urlPathAppend(this.url, id)); } /** * @function KernelDensityJobsService.prototype.addKernelDensityJob * @description 新建核密度分析服务 * @param {KernelDensityJobParameter} params - 核密度分析服务参数类。 * @param {number} seconds - 开始创建后,获取创建成功结果的时间间隔。 */ addKernelDensityJob(params, seconds) { super.addJob(this.url, params, KernelDensityJobParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/LabelMatrixCell.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LabelMatrixCell * @deprecatedclass SuperMap.LabelMatrixCell * @category iServer Map Theme * @classdesc 矩阵标签元素抽象类。该类可以包含 n*n 个矩阵标签元素,矩阵标签元素的类型可以是图片,符号,标签专题图等。 * 符号类型的矩阵标签元素类、图片类型的矩阵标签元素类和专题图类型的矩阵标签元素类均继承自该类。 * @usage */ class LabelMatrixCell { constructor() { this.CLASS_NAME = "LabelMatrixCell"; } } ;// CONCATENATED MODULE: ./src/common/iServer/LabelImageCell.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LabelImageCell * @deprecatedclass SuperMap.LabelImageCell * @category iServer Map Theme * @classdesc 图片类型的矩阵标签元素类。该类继承自 {@link LabelMatrixCell}类,主要对矩阵标签中的专题图类型的矩阵标签元素进行设置。 * 矩阵标签专题图是标签专题图(ThemeLabel)的一种,其中矩阵标签中的填充元素又可分为图片类型({@link LabelImageCell})、 * 符号类型({@link LabelSymbolCell})、专题图类型({@link LabelThemeCell})三种,该类是这三种类型的矩阵标签元素其中的一种, * 用于定义符号类型的矩阵标签,如符号 ID 字段名称(符号 ID 与 SuperMap 桌面产品中点、线、面符号的 ID 对应)、大小等。 * 用户在实现矩阵标签专题图时只需将定义好的矩阵标签元素赋值予 {@link ThemeLabel#matrixCells} 属性即可。matrixCells 是一个二维数组, * 每一维可以是任意类型的矩阵标签元素组成的数组(也可是单个标签元素组成的数组,即数组中只有一个元素)。 * @extends {LabelMatrixCell} * @param {Object} options - 可选参数。 * @param {number} [options.height=0] - 设置图片的高度,单位为毫米。 * @param {string} [options.pathField] - 设置矩阵标签元素所使用图片的路径。 * @param {number} [options.rotation=0.0] - 图片的旋转角度。逆时针方向为正方向,单位为度,精确到0.1度。 * @param {number} [options.width=0] - 设置图片的宽度,单位为毫米。 * @param {boolean} [options.sizeFixed=false] - 是否固定图片的大小。 * @usage */ class LabelImageCell extends LabelMatrixCell { constructor(options) { super(options); /** * @member {number} LabelImageCell.prototype.height * @description 设置图片的高度,单位为毫米。 */ this.height = 0; /** * @member {string} LabelImageCell.prototype.pathField * @description 设置矩阵标签元素所使用的图片路径对应的字段名。 */ this.pathField = null; /** * @member {number} [LabelImageCell.prototype.rotation=0.0] * @description 图片的旋转角度。逆时针方向为正方向,单位为度,精确到0.1度。 */ this.rotation = 0.0; /** * @member {number} LabelImageCell.prototype.width * @description 设置图片的宽度,单位为毫米。 */ this.width = 0; /** * @member {boolean} [LabelImageCell.prototype.sizeFixed=false] * @description 是否固定图片的大小。 */ this.sizeFixed = false; /** * @member {string} LabelImageCell.prototype.type * @description 制作矩阵专题图时是必须的。 */ this.type = "IMAGE"; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.LabelImageCell"; } /** * @function LabelImageCell.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.height = null; me.pathField = null; me.rotation = null; me.width = null; me.sizeFixed = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/LabelSymbolCell.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LabelSymbolCell * @deprecatedclass SuperMap.LabelSymbolCell * @category iServer Map Theme * @classdesc 符号类型的矩阵标签元素类。 * 该类继承自 {@link LabelMatrixCell}类,主要对矩阵标签中的专题图类型的矩阵标签元素进行设置。 * 矩阵标签专题图是标签专题图({@link ThemeLabel})的一种,其中矩阵标签中的填充元素又可分为图片类型({@link LabelImageCell})、 * 符号类型({@link LabelSymbolCell})、专题图类型({@link LabelThemeCell})三种,该类是这三种类型的矩阵标签元素其中的一种, * 用于定义符号类型的矩阵标签,如符号 ID 字段名称(符号 ID 与 SuperMap 桌面产品中点、线、面符号的 ID 对应)、大小等。 * 用户在实现矩阵标签专题图时只需将定义好的矩阵标签元素赋值予 {@link ThemeLabel#matrixCells} 属性即可。matrixCells 属性是一个二维数组, * 每一维可以是任意类型的矩阵标签元素组成的数组(也可是单个标签元素组成的数组,即数组中只有一个元素)。 * @extends {LabelMatrixCell} * @param {Object} options - 参数。 * @param {ServerStyle} options.style - 获取或设置符号样式。 * @param {string} options.symbolIDField - 符号 ID 或符号 ID 所对应的字段名称。 * @usage */ class LabelSymbolCell extends LabelMatrixCell { constructor(options) { super(options); /** * @member {ServerStyle} LabelSymbolCell.prototype.style * @description 获取或设置符号样式—— {@link ServerStyle} 对象,包括符号大小({@link ServerStyle#markerSize}) * 和符号旋转({@link ServerStyle#markerAngle})角度,其中用于设置符号 ID 的属性({@link ServerStyle#markerSymbolID})在此处不起作用。 */ this.style = new ServerStyle(); /** * @member {string} LabelSymbolCell.prototype.symbolIDField * @description 获取或设置符号 ID 或符号 ID 所对应的字段名称。 */ this.symbolIDField = null; /** * @member {string} LabelSymbolCell.prototype.type * @description 制作矩阵专题图时是必须的。 */ this.type = "SYMBOL"; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.LabelSymbolCell"; } /** * @function LabelSymbolCell.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.style) { me.style.destroy(); me.style = null; } me.symbolIDField = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/LabelThemeCell.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LabelThemeCell * @deprecatedclass SuperMap.LabelThemeCell * @category iServer Map Theme * @classdesc 专题图类型的矩阵标签元素类。 * 该类继承自 {@link LabelMatrixCell} 类,主要对矩阵标签中的专题图类型的矩阵标签元素进行设置。 * 矩阵标签专题图是标签专题图({@link ThemeLabel})的一种,其中矩阵标签中的填充元素又可分为图片类型({@link LabelImageCell})、 * 符号类型({@link LabelSymbolCell})、专题图类型({@link LabelThemeCell})三种,该类是这三种类型的矩阵标签元素其中的一种, * 用于定义符号类型的矩阵标签,如符号 ID 字段名称(符号 ID 与 SuperMap 桌面产品中点、线、面符号的 ID 对应)、大小等。 * 用户在实现矩阵标签专题图时只需将定义好的矩阵标签元素赋值予 {@link ThemeLabel#matrixCells} 属性即可。matrixCells 属性是一个二维数组, * 每一维可以是任意类型的矩阵标签元素组成的数组(也可是单个标签元素组成的数组,即数组中只有一个元素)。 * @extends {LabelMatrixCell} * @param {Object} options -参数。 * @param {ThemeLabel} options.themeLabel - 作为矩阵标签元素的标签专题图类。 * @usage */ class LabelThemeCell extends LabelMatrixCell { constructor(options) { super(options); /** * @member {ThemeLabel} LabelThemeCell.prototype.themeLabel * @description 使用专题图对象作为矩阵标签的一个元素。 */ this.themeLabel = new ThemeLabel(); /** * @member {string} LabelThemeCell.prototype.type * @description 制作矩阵专题图时是必须的。 */ this.type = "THEME"; if (options) { Util.extend(this, options); } this.CLASS_NAME = " SuperMap.LabelThemeCell"; } /** * @function LabelThemeCell.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.themeLabel) { me.themeLabel.destroy(); me.themeLabel = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/LayerStatus.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LayerStatus * @deprecatedclass SuperMap.LayerStatus * @category iServer Map TempLayersSet * @classdesc 子图层显示参数类。该类存储了各个子图层的名字和是否可见的状态。 * @param {Object} options - 参数。 * @param {string} options.layerName - 图层名称。 * @param {boolean} [options.isVisible=true] - 图层是否可见,true 表示可见。 * @param {string} [options.displayFilter] - 图层显示 SQL 过滤条件。 * @usage */ class LayerStatus { constructor(options) { /** * @member {string} LayerStatus.prototype.layerName * @description 获取或设置图层名称。 */ this.layerName = null; /** * @member {boolean} LayerStatus.prototype.isVisible * @description 获取或设置图层是否可见,true 表示可见。 */ this.isVisible = null; /** * @member {string} [LayerStatus.prototype.displayFilter] * @description 图层显示 SQL 过滤条件,如 layerStatus.displayFilter = "smid < 10",表示仅显示 smid 值小于 10 的对象。 */ this.displayFilter = null; /** * @member {Object} [LayerStatus.prototype.fieldValuesDisplayFilter] * @property {Array.} values - 要过滤的值。 * @property {string} fieldName - 要过滤的字段名称只支持数字类型的字段。 * @property {string} fieldValuesDisplayMode - 目前有两个 DISPLAY/DISABLE。当为 DISPLAY 时,表示只显示以上设置的相应属性值的要素,否则表示不显示以上设置的相应属性值的要素。 */ this.fieldValuesDisplayFilter = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.LayerStatus"; } /** * @function LayerStatus.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.layerName = null; me.isVisible = null; me.displayFilter = null; } /** * @function LayerStatus.prototype.toJSON * @description 生成对应的 JSON。 * @returns {Object} 对应的 JSON。 */ toJSON() { var json = '{'; json += '"type":"UGC",'; var v = []; if (this.layerName) { v.push('"name":"' + this.layerName + '"'); v.push('"visible":' + this.isVisible); } if (this.displayFilter) { v.push('"displayFilter":"' + this.displayFilter + '"'); } if (this.minScale || this.minScale == 0) { v.push('"minScale":' + this.minScale); } if (this.maxScale || this.maxScale == 0) { v.push('"maxScale":' + this.maxScale); } if (this.fieldValuesDisplayFilter) { v.push('"fieldValuesDisplayFilter":' + Util.toJSON(this.fieldValuesDisplayFilter)); } json += v; json += '}'; return json; } } ;// CONCATENATED MODULE: ./src/common/iServer/LinkItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LinkItem * @deprecatedclass SuperMap.LinkItem * @constructs LinkItem * @category iServer Data FeatureResults * @classdesc 关联信息类。该类用于矢量数据集与外部表的关联。外部表是另一个数据集(其中纯属性数据集中没有空间几何信息)中的 DBMS 表, * 矢量数据集与外部表可以属于不同的数据源,但数据源类型目前只支持 SQL Server 和 Oracle 类型。使用 LinkItem 时, * 空间数据和属性数据必须满足关联条件,即主空间数据集与外部属性表之间存在关联字段。{@link LinkItem} * 只支持左连接,UDB、PostgreSQL 和 DB2 数据源不支持 {@link LinkItem};另外,用于建立关联关系的两个表可以不在同一个数据源下。注意:
* 1.使用 {@link LinkItem} 的约束条件为:空间数据和属性数据必须有关联条件,即主空间数据集与外部属性表之间存在关联字段;
* 2.使用外关联表制作专题图时,所关联的字段必须设置表名,例如,如果所关联的字段为 BaseMap_R 数据集的 SmID,就要写成 BaseMap_R.SMID。 * @param {Object} options - 参数。 * @param {DatasourceConnectionInfo} options.datasourceConnectionInfo - 关联的外部数据源信息。 * @param {Array.} options.foreignKeys - 主空间数据集的外键。 * @param {string} options.foreignTable - 关联的外部属性表的名称。 * @param {Array.} options.linkFields - 欲保留的外部属性表的字段。 * @param {string} options.linkFilter - 与外部属性表的连接条件。 * @param {string} options.name - 此关联信息对象的名称。 * @param {Array.} options.primaryKeys - 关联的外部属性表的主键。 * @example 下面以 SQL 查询说明 linkitem 的使用方法: * function queryBySQL() { * // 设置关联的外部数据库信息,alias表示数据库别名 * var dc = new DatasourceConnectionInfo({ * dataBase: "RelQuery", * server: "{ip}:{port}", * user: "sa", * password: "map", * driver: "SQL Server", * connect: true, * OpenLinkTable: false, * alias: "RelQuery", * engineType: EngineType.SQLPLUS, * readOnly: false, * exclusive: false * }); * // 设置关联信息 * var linkItem = new LinkItem({ * datasourceConnectionInfo: dc, * foreignKeys: ["name"], * foreignTable: "Pop_2011", * linkFields: ["SmID as Pid","pop"], * name: "link", * primatryKeys: ["name"], * }); * // 设置查询参数,在查询参数中添加linkItem关联条件信息 * var queryParam, queryBySQLParams, queryBySQLService; * queryParam = new FilterParameter({ * name: "Province@RelQuery", * fields: ["SmID","name"], * attributeFilter: "SmID<7", * linkItems: [linkItem] * }), * queryBySQLParams = new QueryBySQLParameters({ * queryParams: [queryParam] * }), * queryBySQLService = new QueryBySQLService(url, { * eventListeners: { * "processCompleted": processCompleted, * "processFailed": processFailed * } * }); * queryBySQLService.processAsync(queryBySQLParams); * } * function processCompleted(queryEventArgs) {//todo} * function processFailed(e) {//todo} * @usage */ class LinkItem { constructor(options) { /** * @member {DatasourceConnectionInfo} LinkItem.prototype.datasourceConnectionInfo * @description 关联的外部数据源信息。 */ this.datasourceConnectionInfo = null; /** * @member {Array.} LinkItem.prototype.foreignKeys * @description 主空间数据集的外键。 */ this.foreignKeys = null; /** * @member {string} LinkItem.prototype.foreignTable * @description 关联的外部属性表的名称,目前仅支持 Supermap 管理的表,即另一个矢量数据集所对应的 DBMS 表。 */ this.foreignTable = null; /** * @member {Array.} LinkItem.prototype.linkFields * @description 欲保留的外部属性表的字段。如果不设置字段或者设置的字段在外部属性表中不存在的话则不返回任何外部属性表的属性信息。如果欲保留的外部表字段与主表字段存在同名,则还需要指定一个不存在字段名作为外部表的字段别名。 */ this.linkFields = null; /** * @member {string} LinkItem.prototype.linkFilter * @description 与外部属性表的连接条件。 */ this.linkFilter = null; /** * @member {string} LinkItem.prototype.name * @description 此关联信息对象的名称。 */ this.name = null; /** * @member {Array.} LinkItem.prototype.primaryKeys * @description 需要关联的外部属性表的主键。 */ this.primaryKeys = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.LinkItem"; } /** * @function LinkItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; if (me.datasourceConnectionInfo instanceof DatasourceConnectionInfo) { me.datasourceConnectionInfo.destroy(); me.datasourceConnectionInfo = null; } me.foreignKeys = null; me.foreignTable = null; me.linkFields = null; me.linkFilter = null; me.name = null; me.primaryKeys = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/MapService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MapService * @deprecatedclass SuperMap.MapService * @category iServer Map * @classdesc 地图信息服务类。 * @extends {CommonServiceBase} * @example * var myMapService = new MapService(url, { * eventListeners:{ * "processCompleted": MapServiceCompleted, * "processFailed": MapServiceFailed * } * }); * * @param {string} url - 服务地址。如:http://localhost:8090/iserver/services/map-world/rest/maps/World+Map 。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class MapService_MapService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {string} MapService.prototype.projection * @description 根据投影参数获取地图状态信息。如"EPSG:4326" */ this.projection = null; this.CLASS_NAME = "SuperMap.MapService"; if (options) { Util.extend(this, options); } var me = this; if (me.projection) { var arr = me.projection.split(":"); if (arr instanceof Array) { if (arr.length === 2) { me.url = Util.urlAppend(me.url,`prjCoordSys=${encodeURIComponent(`{\"epsgCode\":"${arr[1]}"}`)}`) } if (arr.length === 1) { me.url = Util.urlAppend(me.url,`prjCoordSys=${encodeURIComponent(`{\"epsgCode\":"${arr[0]}"}`)}`) } } } } /** * @function destroy * @description 释放资源,将引用的资源属性置空。 */ destroy() { super.destroy(); var me = this; if (me.events) { me.events.un(me.eventListeners); me.events.listeners = null; me.events.destroy(); me.events = null; me.eventListeners = null; } } /** * @function MapService.prototype.processAsync * @description 负责将客户端的设置的参数传递到服务端,与服务端完成异步通讯。 */ processAsync() { var me = this; me.request({ method: "GET", scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /* * Method: getMapStatusCompleted * 获取地图状态完成,执行此方法。 * * Parameters: * {Object} result - 服务器返回的结果对象。 */ serviceProcessCompleted(result) { var me = this; result = Util.transformResult(result); var codeStatus = (result.code >= 200 && result.code < 300) || result.code == 0 || result.code === 304; var isCodeValid = result.code && codeStatus; if (!result.code || isCodeValid) { me.events && me.events.triggerEvent("processCompleted", {result: result}); } else { ////在没有token是返回的是200,但是其实是没有权限,所以这里也应该是触发失败事件 me.events.triggerEvent("processFailed", {error: result}); } } } ;// CONCATENATED MODULE: ./src/common/iServer/MathExpressionAnalysisParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MathExpressionAnalysisParameters * @deprecatedclass SuperMap.MathExpressionAnalysisParameters * @category iServer SpatialAnalyst GridMathAnalyst * @classdesc 栅格代数运算参数类。 * @param {Object} options - 参数。 * @param {string} options.dataset - 指定栅格代数运算数据源中数据集的名称。该名称用形如"数据集名称@数据源别名"形式来表示,例如:BaseMap_P@Jingjin。 * @param {string} options.resultGridName - 指定结果数据集名称。 * @param {string} options.expression - 指定的栅格运算表达式。如:[DatasourceAlias1.Raster1]*2-10。 * @param {string} options.targetDatasource - 指定存储结果数据集的数据源。 * @param {GeometryPolygon|L.Polygon|ol.geom.Polygon|GeoJSONObject} [options.extractRegion] - 栅格代数运算的范围,指定数据集中参与栅格代数运算的区域。 * 如果缺省,则计算全部区域,如果参与运算的数据集范围不一致,将使用所有数据集的范围的交集作为计算区域 。 * @param {boolean} [options.isZip=false] - 是否对结果数据集进行压缩处理。 * @param {boolean} [options.ignoreNoValue=false] - 是否忽略无值栅格数据。true 表示忽略无值数据,即无值栅格不参与运算。 * @param {boolean} [options.deleteExistResultDataset=false] - 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 * @usage */ class MathExpressionAnalysisParameters { constructor(options) { if (!options) { return; } /** * @member {string} MathExpressionAnalysisParameters.prototype.dataset * @description 要用来做栅格代数运算数据源中数据集的名称。 * 该名称用形如"数据集名称@数据源别名"形式来表示,例如:JingjinTerrain@Jingjin。 * */ this.dataset = null; /** * @member {GeometryPolygon|L.Polygon|ol.geom.Polygon|GeoJSONObject} [MathExpressionAnalysisParameters.prototype.extractRegion] * @description 栅格代数运算的范围,指定数据集中参与栅格代数运算的区域。 * 如果缺省,则计算全部区域,如果参与运算的数据集范围不一致,将使用所有数据集的范围的交集作为计算区域 。 */ this.extractRegion = null; /** * @member {string} MathExpressionAnalysisParameters.prototype.expression * @description 指定的栅格运算表达式。如:"[DatasourceAlias1.Raster1]*2-10"。 */ this.expression = null; /** * @member {boolean} [MathExpressionAnalysisParameters.prototype.isZip=false] * @description 是否对结果数据集进行压缩处理。 */ this.isZip = false; /** * @member {boolean} [MathExpressionAnalysisParameters.prototype.ignoreNoValue=false] * @description 是否忽略无值栅格数据。 */ this.ignoreNoValue = false; /** * @member {string} MathExpressionAnalysisParameters.prototype.targetDatasource * @description 指定存储结果数据集的数据源。 */ this.targetDatasource = null; /** * @member {string} MathExpressionAnalysisParameters.prototype.resultGridName * @description 指定结果数据集名称。 */ this.resultGridName = null; /** * @member {boolean} [MathExpressionAnalysisParameters.prototype.deleteExistResultDataset=false] * @description 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 */ this.deleteExistResultDataset = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.MathExpressionAnalysisParameters" } /** * @function MathExpressionAnalysisParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.dataset = null; me.bounds = null; me.expression = null; me.isZip = true; me.ignoreNoValue = true; me.targetDatasource = null; me.resultGridName = null; me.deleteExistResultDataset = null; } /** * @function MathExpressionAnalysisParameters.toObject * @param {Object} mathExpressionAnalysisParameters - 栅格代数运算参数。 * @param {Object} tempObj - 目标对象。 * @description 生成栅格代数运算对象。 */ static toObject(mathExpressionAnalysisParameters, tempObj) { for (var name in mathExpressionAnalysisParameters) { if (name !== "dataset") { tempObj[name] = mathExpressionAnalysisParameters[name]; } if (name === "extractRegion") { if (mathExpressionAnalysisParameters[name]) { var bs = mathExpressionAnalysisParameters[name].components[0].components; var region = {}, points = [], type = "REGION"; var len = bs.length; for (var i = 0; i < len - 1; i++) { var poi = {}; poi["x"] = bs[i].x; poi["y"] = bs[i].y; points.push(poi); } region["points"] = points; region["type"] = type; tempObj[name] = region; } } } } } ;// CONCATENATED MODULE: ./src/common/iServer/MathExpressionAnalysisService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MathExpressionAnalysisService * @deprecatedclass SuperMap.MathExpressionAnalysisService * @category iServer SpatialAnalyst GridMathAnalyst * @classdesc 栅格代数运算服务类。 * @param {string} url - 服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 例如: * (start code) * var myMathExpressionAnalysisService = new MathExpressionAnalysisService(url); * myMathExpressionAnalysisService.on({ * "processCompleted": processCompleted, * "processFailed": processFailed * } * ); * (end) * @usage */ class MathExpressionAnalysisService extends SpatialAnalystBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.MathExpressionAnalysisService"; } /** * @override */ destroy() { super.destroy(); } /** * @function MathExpressionAnalysisService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {MathExpressionAnalysisParameters} parameter - 栅格代数运算参数类。 */ processAsync(parameter) { var me = this; var parameterObject = {}; if (parameter instanceof MathExpressionAnalysisParameters) { me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/mathanalyst'); } MathExpressionAnalysisParameters.toObject(parameter, parameterObject); var jsonParameters = Util.toJSON(parameterObject); me.url = Util.urlAppend(me.url, 'returnContent=true'); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/MeasureParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MeasureParameters * @deprecatedclass SuperMap.MeasureParameters * @category iServer Map Measure * @classdesc 量算参数类。 * @param {GeoJSONObject} geometry - 要量算的几何对象。 * @param {Object} options - 可选参数。 * @param {Unit} [options.unit=Unit.METER] - 量算单位。 * @param {string} [options.prjCoordSys] - 用来指定该量算操作所使用的投影。 * @param {string} [options.distanceMode="Geodesic"] - 用来指定量算的方式为按球面长度 'Geodesic' 或者平面长度 'Planar' 来计算。 * @usage */ class MeasureParameters { constructor(geometry, options) { if (!geometry) { return; } /** * @member {GeoJSONObject} MeasureParameters.prototype.geometry * @description 要量算的几何对象。
* 点类型可以是:{@link GeometryPoint}|{@link L.Marker}|{@link L.CircleMarker}|{@link L.Circle}|{@link L.GeoJSON}|{@link ol.geom.Point}|{@link ol.format.GeoJSON}|{@link GeoJSONObject}。
* 线类型可以是:{@link GeometryLineString}|{@link GeometryLinearRing}|{@link L.Polyline}|{@link L.GeoJSON}|{@link ol.geom.LineString}|{@link ol.format.GeoJSON}|{@link GeoJSONObject}。
* 面类型可以是:{@link GeometryPolygon}|{@link L.Polygon}|{@link L.GeoJSON}|{@link ol.geom.Polygon}|{@link ol.format.GeoJSON}|{@link GeoJSONObject}。 */ this.geometry = geometry; /** * @member {Unit} [MeasureParameters.prototype.unit=Unit.METER] * @description 量算单位。即量算结果以米为单位。 */ this.unit = Unit.METER; /** * @member {string} [MeasureParameters.prototype.prjCoordSys] * @description 用来指定该量算操作所使用的投影。 */ this.prjCoordSys = null; /** * @member {string} [MeasureParameters.prototype.distanceMode="Geodesic"] * @description 用来指定量算的方式为按球面长度 'Geodesic' 或者平面长度 'Planar' 来计算。 * @example * var param = new MeasureParameters(getmetry,{distanceMode:'Planar'}); */ this.distanceMode = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.MeasureParameters"; } /** * @function MeasureParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.geometry = null; me.unit = null; me.prjCoordSys = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/MeasureService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MeasureService * @deprecatedclass SuperMap.MeasureService * @category iServer Map Measure * @classdesc 量算服务类。 * 该类负责将量算参数传递到服务端,并获取服务端返回的量算结果。 * @extends {CommonServiceBase} * @example * var myMeasuerService = new MeasureService(url, { * measureMode: MeasureMode.DISTANCE, * eventListeners:{ * "processCompleted": measureCompleted * } * }); * @param {string} url - 服务地址。如:http://localhost:8090/iserver/services/map-world/rest/maps/World+Map 。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @param {MeasureMode} options.measureMode - 量算模式,包括距离量算模式和面积量算模式。 * @usage */ class MeasureService_MeasureService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {MeasureMode} [MeasureService.prototype.measureMode=MeasureMode.DISTANCE] * @description 量算模式,包括距离量算模式和面积量算模式。 */ this.measureMode = MeasureMode.DISTANCE; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.MeasureService"; } /** * @override */ destroy() { super.destroy(); var me = this; me.measureMode = null; } /** * @function MeasureService.prototype.processAsync * @description 负责将客户端的量算参数传递到服务端。 * @param {MeasureParameters} params - 量算参数。 */ processAsync(params) { if (!(params instanceof MeasureParameters)) { return; } var me = this, geometry = params.geometry, pointsCount = 0, point2ds = null; if (!geometry) { return; } me.url = Util.urlPathAppend(me.url, me.measureMode === MeasureMode.AREA ? 'area' : 'distance'); var serverGeometry = ServerGeometry.fromGeometry(geometry); if (!serverGeometry) { return; } pointsCount = serverGeometry.parts[0]; point2ds = serverGeometry.points.splice(0, pointsCount); var prjCoordSysTemp, prjCodeTemp, paramsTemp; if (params.prjCoordSys) { if (typeof (params.prjCoordSys) === "object") { prjCodeTemp = params.prjCoordSys.projCode; prjCoordSysTemp = '{"epsgCode"' + prjCodeTemp.substring(prjCodeTemp.indexOf(":"), prjCodeTemp.length) + "}"; } else if (typeof (params.prjCoordSys) === "string") { prjCoordSysTemp = '{"epsgCode"' + params.prjCoordSys.substring(params.prjCoordSys.indexOf(":"), params.prjCoordSys.length) + "}"; } paramsTemp = { "point2Ds": Util.toJSON(point2ds), "unit": params.unit, "prjCoordSys": prjCoordSysTemp, "distanceMode": params.distanceMode || 'Geodesic' }; } else { paramsTemp = {"point2Ds": Util.toJSON(point2ds), "unit": params.unit, "distanceMode": params.distanceMode || 'Geodesic'}; } me.request({ method: "GET", params: paramsTemp, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/OverlapDisplayedOptions.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OverlapDisplayedOptions * @deprecatedclass SuperMap.OverlapDisplayedOptions * @category iServer Map Layer * @classdesc 地图压盖过滤显示选项。在文本或专题图元素显示较密集的区域,文本之间或专题元素之间会发生相互压盖的现象, * 该类可以分别控制各种类型的对象的压盖显示情况,进而很好地处理地图中各种类型对象的压盖显示问题。 * @param {Object} options - 可选参数。 * @param {boolean} [options.allowPointOverlap=true] - 点和点压盖时是否显示压盖的点对象。 * @param {boolean} [options.allowPointWithTextDisplay=true] - 标签和相应普通图层上的点是否一起过滤显示,如果过滤显示, * 只以图层集合中对应数据集的索引最小的图层的点风格来绘制点。 * @param {boolean} [options.allowTextOverlap=false] - 文本压盖时是否显示压盖的文本对象。 * @param {boolean} [options.allowTextAndPointOverlap=true] - 文本和点压盖时是否显示压盖的文本或点对象(此属性不处理文本之间的压盖和点之间的压盖)。 * @param {boolean} [options.allowThemeGraduatedSymbolOverlap=false] - 等级符号元素压盖时是否显示压盖的等级符号元素。 * @param {boolean} [options.allowThemeGraphOverlap=false] - 统计专题图元素压盖时是否显示压盖的统计专题图元素。 * @param {number} [options.horizontalOverlappedSpaceSize=0] - 两个对象之间的横向压盖间距,单位为 0.1 毫米,跟 verticalOverlappedSpaceSize 结合使用, * 当两个对象的横向间距小于该值,且纵向间距小于 verticalOverlappedSpaceSize 时认为压盖。 * @param {number} [options.verticalOverlappedSpaceSize=0] - 两个对象之间的纵向压盖间距,单位为 0.1 毫米,跟 horizontalOverlappedSpaceSize 结合使用, * 当两个对象的纵向间距小于该值,且横向间距小于 horizontalOverlappedSpaceSize 时认为压盖。 * @usage */ class OverlapDisplayedOptions { constructor(options) { options = options || {}; /** * @member {boolean} [OverlapDisplayedOptions.prototype.allowPointOverlap=true] * @description 点和点压盖时是否显示压盖的点对象。 */ this.allowPointOverlap = true; /** * @member {boolean} [OverlapDisplayedOptions.prototype.allowPointWithTextDisplay=true] * @description 标签和相应普通图层上的点是否一起过滤显示,如果过滤显示, * 只以图层集合中对应数据集的索引最小的图层的点风格来绘制点。 */ this.allowPointWithTextDisplay = true; /** * @member {boolean} [OverlapDisplayedOptions.prototype.allowTextOverlap=false] * @description 文本压盖时是否显示压盖的文本对象。 */ this.allowTextOverlap = false; /** * @member {boolean} [OverlapDisplayedOptions.prototype.allowTextAndPointOverlap=true] * @description 文本和点压盖时是否显示压盖的文本或点对象(此属性不处理文本之间的压盖和点之间的压盖)。 */ this.allowTextAndPointOverlap = true; /** * @member {boolean} [OverlapDisplayedOptions.prototype.allowThemeGraduatedSymbolOverlap=false] * @description 等级符号元素压盖时是否显示压盖的等级符号元素。 */ this.allowThemeGraduatedSymbolOverlap = false; /** * @member {boolean} [OverlapDisplayedOptions.prototype.allowThemeGraphOverlap=false] * @description 统计专题图元素压盖时是否显示压盖的统计专题图元素。 */ this.allowThemeGraphOverlap = false; /** * @member {number} [OverlapDisplayedOptions.prototype.horizontalOverlappedSpaceSize=0] * @description 两个对象之间的横向压盖间距,单位为0.1毫米,跟 verticalOverlappedSpaceSize 结合使用, * 当两个对象的横向间距小于该值,且纵向间距小于 verticalOverlappedSpaceSize 时认为压盖。 */ this.horizontalOverlappedSpaceSize = 0; /** * @member {number} [OverlapDisplayedOptions.prototype.verticalOverlappedSpaceSize=0] * @description 两个对象之间的纵向压盖间距,单位为0.1毫米,跟 horizontalOverlappedSpaceSize 结合使用, * 当两个对象的纵向间距小于该值,且横向间距小于 horizontalOverlappedSpaceSize 时认为压盖。 */ this.verticalOverlappedSpaceSize = 0; Util.extend(this, options); this.ugcLayer = new UGCLayer(options); this.CLASS_NAME = "SuperMap.OverlapDisplayedOptions"; } /** * @function OverlapDisplayedOptions.prototype.destroy * @description 释放资源,将资源的属性置空。 */ destroy() { Util.reset(this); } /** * @function OverlapDisplayedOptions.prototype.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 */ fromJson(jsonObject) { this.ugcLayer.fromJson.apply(this, [jsonObject]); } /** * @function OverlapDisplayedOptions.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var jsonObject = this.ugcLayer.toServerJSONObject.apply(this, arguments); return jsonObject; } /** * @function OverlapDisplayedOptions.prototype.toString * @description 转换成对应的 tileLayer 请求瓦片时 overlapDisplayedOptions 参数。 * @returns {string} 对应的 tileLayer 请求瓦片时 overlapDisplayedOptions 参数。 */ toString() { var jsonObject = this.ugcLayer.toServerJSONObject.apply(this, arguments); var str = "{"; for (var attr in jsonObject) { if (jsonObject.hasOwnProperty(attr)) { str += "'" + attr + "':" + jsonObject[attr] + ","; } } str = str.substr(0, str.length - 1); str += "}"; return str; } } ;// CONCATENATED MODULE: ./src/common/iServer/OverlayAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OverlayAnalystService * @deprecatedclass SuperMap.OverlayAnalystService * @category iServer SpatialAnalyst OverlayAnalyst * @classdesc 叠加分析服务类。 * 该类负责将客户设置的叠加分析参数传递给服务端,并接收服务端返回的叠加分析结果数据。 * 叠加分析结果通过该类支持的事件的监听函数参数获取 * @param {string} url - 服务地址。如http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {Object} [options.headers] - 请求头。 * @extends {CommonServiceBase} * @example 例如: * (start code) * var myOverlayAnalystService = new OverlayAnalystService(url, { * eventListeners: { * "processCompleted": OverlayCompleted, * "processFailed": OverlayFailed * } * }); * (end) * @usage */ class OverlayAnalystService extends SpatialAnalystBase { constructor(url, options) { super(url, options); /** * @member {string} OverlayAnalystService.prototype.mode * @description 叠加分析类型 */ this.mode = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.OverlayAnalystService"; } /** * @override */ destroy() { super.destroy(); this.mode = null; } /** * @function OverlayAnalystService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {OverlayAnalystParameters} parameter - 叠加分析参数类。 */ processAsync(parameter) { var parameterObject = {}; var me = this; if (parameter instanceof DatasetOverlayAnalystParameters) { me.mode = "datasets"; me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.sourceDataset + '/overlay'); DatasetOverlayAnalystParameters.toObject(parameter, parameterObject); } else if (parameter instanceof GeometryOverlayAnalystParameters) { me.mode = "geometry"; //支持传入多个几何要素进行叠加分析 if(parameter.operateGeometries && parameter.sourceGeometries){ me.url = Util.urlPathAppend(me.url, 'geometry/overlay/batch'); me.url = Util.urlAppend(me.url, 'ignoreAnalystParam=true'); }else { me.url = Util.urlPathAppend(me.url, 'geometry/overlay'); } GeometryOverlayAnalystParameters.toObject(parameter, parameterObject); } this.returnContent = true; var jsonParameters = Util.toJSON(parameterObject); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } dataFormat() { return [DataFormat.GEOJSON, DataFormat.ISERVER, DataFormat.FGB]; } } ;// CONCATENATED MODULE: ./src/common/iServer/OverlayGeoJobParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OverlayGeoJobParameter * @deprecatedclass SuperMap.OverlayGeoJobParameter * @category iServer ProcessingService OverlayAnalyst * @classdesc 叠加分析任务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {string} options.datasetOverlay - 叠加对象所在的数据集名称。 * @param {string} options.srcFields - 输入数据需要保留的字段。 * @param {string} [options.overlayFields] - 叠加数据需要保留的字段。对分析模式为 clip、update、erase 时,此参数无效。 * @param {string} [options.mode] - 叠加分析模式。 * @param {OutputSetting} [options.output] - 输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class OverlayGeoJobParameter { constructor(options) { if (!options) { return; } /** * @member {string} OverlayGeoJobParameter.prototype.datasetName * @description 数据集名。 */ this.datasetName = ""; /** * @member {string} OverlayGeoJobParameter.prototype.datasetOverlay * @description 叠加对象所在的数据集名称。 */ this.datasetOverlay = ""; /** * @member {string} [OverlayGeoJobParameter.prototype.mode] * @description 叠加分析模式。 */ this.mode = ""; /** * @member {string} OverlayGeoJobParameter.prototype.srcFields * @description 输入数据需要保留的字段。 */ this.srcFields = ""; /** * @member {string} OverlayGeoJobParameter.prototype.overlayFields * @description 叠加数据需要保留的字段,对分析模式为 clip、update、erase 时,此参数无效。 */ this.overlayFields = ""; /** * @member {OutputSetting} [OverlayGeoJobParameter.prototype.output] * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [OverlayGeoJobParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.OverlayGeoJobParameter"; } /** * @function OverlayGeoJobParameter.prototype.destroy * @description 释放资源,将资源的属性置空。 */ destroy() { this.datasetName = null; this.datasetOverlay = null; this.mode = null; this.srcFields = null; this.overlayFields = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters) { this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function OverlayGeoJobParameter.toObject * @param {Object} OverlayGeoJobParameter - 点聚合分析任务参数。 * @param {Object} tempObj - 目标对象。 * @description 生成点聚合分析任务对象。 */ static toObject(OverlayGeoJobParameter, tempObj) { for (var name in OverlayGeoJobParameter) { if (name == "datasetName") { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = OverlayGeoJobParameter[name]; continue; } if (name === "output") { tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = OverlayGeoJobParameter[name]; continue; } tempObj['analyst'] = tempObj['analyst'] || {}; tempObj['analyst'][name] = OverlayGeoJobParameter[name]; if(name === 'mappingParameters'){ tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = OverlayGeoJobParameter[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/OverlayGeoJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OverlayGeoJobsService * @deprecatedclass SuperMap.OverlayGeoJobsService * @category iServer ProcessingService OverlayAnalyst * @classdesc 叠加分析任务类。 * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {Events} options.events - 处理所有事件的对象。 * @param {Object} [options.eventListeners] - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {number} options.index - 服务访问地址在数组中的位置。 * @param {number} options.length - 服务访问地址数组长度。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class OverlayGeoJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/overlay'); this.CLASS_NAME = 'SuperMap.OverlayGeoJobsService'; } /** * @override */ destroy() { super.destroy(); } /** * @function OverlayGeoJobsService.prototype.getOverlayGeoJobs * @description 获取叠加分析任务 */ getOverlayGeoJobs() { super.getJobs(this.url); } /** * @function OverlayGeoJobsService.prototype.getOverlayGeoJob * @description 获取指定id的叠加分析任务 * @param {string} id - 指定要获取数据的id */ getOverlayGeoJob(id) { super.getJobs(Util.urlPathAppend(this.url, id)); } /** * @function OverlayGeoJobsService.prototype.addOverlayGeoJob * @description 新建点叠加析服务 * @param {OverlayGeoJobParameter} params - 创建一个叠加分析的请求参数。 * @param {number} seconds - 开始创建后,获取创建成功结果的时间间隔。 */ addOverlayGeoJob(params, seconds) { super.addJob(this.url, params, OverlayGeoJobParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryByBoundsParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryByBoundsParameters * @deprecatedclass SuperMap.QueryByBoundsParameters * @category iServer Map QueryResults * @classdesc Bounds 查询参数类。该类用于设置 Bounds 查询的相关参数。 * @extends {QueryParameters} * @param {Object} options - 参数。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} options.bounds - 指定的查询范围。 * @param {Array.} options.queryParams - 查询过滤条件参数数组。 * @param {string} [options.customParams] - 自定义参数,供扩展使用。 * @param {Object} [options.prjCoordSys] -自定义参数,供 SuperMap Online 提供的动态投影查询扩展使用。如 {"epsgCode":3857}。 * @param {number} [options.expectCount=100000] - 期望返回结果记录个数。 * @param {GeometryType} [options.networkType=GeometryType.LINE] - 网络数据集对应的查询类型。 * @param {QueryOption} [options.queryOption=QueryOption.ATTRIBUTEANDGEOMETRY] - 查询结果类型枚举类。 * @param {number} [options.startRecord=0] - 查询起始记录号。 * @param {number} [options.holdTime=10] - 资源在服务端保存的时间,单位为分钟。 * @param {boolean} [options.returnCustomResult=false] - 仅供三维使用。 * @param {boolean} [options.returnContent=true] - 是否立即返回新创建资源的表述还是返回新资源的 URI。 * @param {boolean} [options.returnFeatureWithFieldCaption = false] - 返回的查询结果要素字段标识是否为字段别名。为 false 时,返回的是字段名;为 true 时,返回的是字段别名。 * @usage */ class QueryByBoundsParameters extends QueryParameters { constructor(options) { options = options || {}; super(options); /** * @member {boolean} [QueryByBoundsParameters.prototype.returnContent=true] * @description 是否立即返回新创建资源的表述还是返回新资源的 URI。 * 如果为 true,则直接返回新创建资源,即查询结果的表述。 * 为 false,则返回的是查询结果资源的 URI。 */ this.returnContent = true; /** * @member {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} QueryByBoundsParameters.prototype.bounds * @description 指定的查询范围。 */ this.bounds = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.QueryByBoundsParameters"; } /** * @function QueryByBoundsParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.returnContent = null; if (me.bounds) { me.bounds = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryService * @deprecatedclass SuperMap.QueryService * @category iServer Map QueryResults * @classdesc 查询服务基类。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求地图查询服务的 URL 应为:http://{服务器地址}:{服务端口号}/iserver/services/{地图服务名}/rest/maps/{地图名}; * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * var myService = new QueryService(url, { * eventListeners: { * "processCompleted": queryCompleted, * "processFailed": queryError * } * }; * @usage */ class QueryService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {boolean} QueryService.prototype.returnContent * @description 是否立即返回新创建资源的表述还是返回新资源的URI。 */ this.returnContent = false; /** * @member {string} QueryService.prototype.format * @description 查询结果返回格式,目前支持iServerJSON、GeoJSON、FGB三种格式。参数格式为"ISERVER","GEOJSON","FGB"。 */ this.format = DataFormat.GEOJSON; this.returnFeatureWithFieldCaption = false; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.QueryService"; if (!this.url) { return; } if (options && options.format) { this.format = options.format.toUpperCase(); } this.url = Util.urlPathAppend(this.url,'queryResults'); } /** * @function QueryService.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.returnContent = null; me.format = null; } /** * @function QueryService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {QueryParameters} params - 查询参数。 */ processAsync(params) { if (!(params instanceof QueryParameters)) { return; } var me = this, returnCustomResult = null, jsonParameters = null; me.returnContent = params.returnContent; jsonParameters = me.getJsonParameters(params); if (!me.returnContent) { //仅供三维使用 获取高亮图片的bounds returnCustomResult = params.returnCustomResult; if (returnCustomResult) { me.url = Util.urlAppend(me.url, 'returnCustomResult=' + returnCustomResult); } } me.returnFeatureWithFieldCaption = params.returnFeatureWithFieldCaption; me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function QueryService.prototype.serviceProcessCompleted * @description 查询完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象。 */ serviceProcessCompleted(result) { var me = this; result = Util.transformResult(result); var geoJSONFormat = new GeoJSON(); if (result && result.recordsets) { for (var i = 0, recordsets = result.recordsets, len = recordsets.length; i < len; i++) { if (recordsets[i].features) { if (me.returnFeatureWithFieldCaption === true) { recordsets[i].features.map((feature) => { feature.fieldNames = recordsets[i].fieldCaptions; return feature; }) } if (me.format === DataFormat.GEOJSON) { recordsets[i].features = geoJSONFormat.toGeoJSON(recordsets[i].features); } } } } me.events.triggerEvent("processCompleted", { result: result }); } dataFormat() { return [DataFormat.GEOJSON, DataFormat.ISERVER, DataFormat.FGB]; } /** * @function QueryService.prototype.getQueryParameters * @description 将 JSON 对象表示的查询参数转化为 QueryParameters 对象。 * @param {Object} params - JSON 字符串表示的查询参数。 * @returns {QueryParameters} 返回转化后的 QueryParameters 对象。 */ getQueryParameters(params) { return new QueryParameters({ customParams: params.customParams, expectCount: params.expectCount, networkType: params.networkType, queryOption: params.queryOption, queryParams: params.queryParams, startRecord: params.startRecord, prjCoordSys: params.prjCoordSys, holdTime: params.holdTime }); } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryByBoundsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryByBoundsService * @deprecatedclass SuperMap.QueryByBoundsService * @category iServer Map QueryResults * @classdesc Bounds 查询服务类。 * @augments {QueryService} * @example * (start end) * var myQueryByBoundsService = new QueryByBoundsService(url, { * eventListeners: { * "processCompleted": queryCompleted, * "processFailed": queryError * } * }); * function queryCompleted(object){//todo}; * function queryError(object){//todo}; * (end) * @param {string} url - 服务地址。如访问World Map服务,只需将url设为: http://localhost:8090/iserver/services/map-world/rest/maps/World+Map 即可。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。
* @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class QueryByBoundsService extends QueryService { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.QueryByBoundsService"; } /** * @override */ destroy() { super.destroy(); } /** * @function QueryByBoundsService.prototype.getJsonParameters * @description 将查询参数转化为 JSON 字符串。 * 在本类中重写此方法,可以实现不同种类的查询(sql, geometry, distance, bounds 等)。 * @param {QueryByBoundsParameters} params - Bounds 查询参数。 * @returns {Object} 转化后的 JSON 字符串。 */ getJsonParameters(params) { if (!(params instanceof QueryByBoundsParameters)) { return null; } var me = this, jsonParameters = "", qp = null, bounds = params.bounds; qp = me.getQueryParameters(params); jsonParameters += "'queryMode':'BoundsQuery','queryParameters':"; jsonParameters += Util.toJSON(qp); jsonParameters += ",'bounds': {'rightTop':{'y':" + bounds.top + ",'x':" + bounds.right + "},'leftBottom':{'y':" + bounds.bottom + ",'x':" + bounds.left + "}}"; jsonParameters = "{" + jsonParameters + "}"; return jsonParameters; } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryByDistanceParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryByDistanceParameters * @deprecatedclass SuperMap.QueryByDistanceParameters * @category iServer Map QueryResults * @classdesc Distance 查询参数类。 * 该类用于设置 Distance 查询的相关参数。 * @extends {QueryParameters} * @param {Object} options - 参数。 * @param {GeoJSONObject} options.geometry - 用于查询的几何对象。 * @param {Array.} options.queryParams - 查询过滤条件参数数组。 * @param {number} options.distance - 查询距离,单位与所查询图层对应的数据集单位相同。距离查询时,表示距离地物的距离。最近地物查询时,表示搜索的范围。此为必选参数。 * @param {string} [options.customParams] - 自定义参数,供扩展使用。 * @param {Object} [options.prjCoordSys] -自定义参数,供 SuperMap Online 提供的动态投影查询扩展使用。如 {"epsgCode":3857}。 * @param {number} [options.expectCount=100000] - 期望返回结果记录个数。 * @param {GeometryType} [options.networkType=GeometryType.LINE] - 网络数据集对应的查询类型。 * @param {QueryOption} [options.queryOption=QueryOption.ATTRIBUTEANDGEOMETRY] - 查询结果类型枚举类。 * @param {number} [options.startRecord=0] - 查询起始记录号。 * @param {number} [options.holdTime=10] - 资源在服务端保存的时间,单位为分钟。 * @param {boolean} [options.returnCustomResult=false] -仅供三维使用。 * @param {boolean} [options.isNearest=false] - 是否为最近距离查询。 * @param {boolean} [options.returnContent=true] - 是否立即返回新创建资源的表述还是返回新资源的 URI。 * @param {boolean} [options.returnFeatureWithFieldCaption = false] - 返回的查询结果要素字段标识是否为字段别名。为 false 时,返回的是字段名;为 true 时,返回的是字段别名。 * @usage */ class QueryByDistanceParameters extends QueryParameters { constructor(options) { options = options || {}; super(options); /** * @member {number} [QueryByDistanceParameters.prototype.distance=0] * @description 查询距离,单位与所查询图层对应的数据集单位相同。 * 距离查询时,表示距离地物的距离。最近地物查询时,表示搜索的范围。 */ /** * @member {GeoJSONObject} QueryByDistanceParameters.prototype.geometry * @description 用于查询的地理对象。
* 点类型可以是:{@link GeometryPoint}|{@link L.Marker}|{@link L.CircleMarker}|{@link L.Circle}|{@link L.GeoJSON}|{@link ol.geom.Point}|{@link ol.format.GeoJSON}|{@link mapboxgl.LngLat}|{@link mapboxgl.Point}|{@link GeoJSONObject}。
* 线类型可以是:{@link GeometryLineString}|{@link GeometryLinearRing}|{@link L.Polyline}|{@link L.GeoJSON}|{@link ol.geom.LineString}|{@link ol.format.GeoJSON}|{@link GeoJSONObject}。
* 面类型可以是:{@link GeometryPolygon}|{@link L.Polygon}|{@link L.GeoJSON}|{@link ol.geom.Polygon}|{@link ol.format.GeoJSON}|{@link mapboxgl.LngLatBounds}|{@link GeoJSONObject}。 */ this.geometry = null; /** * @member {boolean} [QueryByDistanceParameters.prototype.isNearest=false] * @description 是否为最近距离查询。
* 建议该属性与 expectCount(继承自 {@link QueryParameters})属性联合使用。 * 当该属性为 true 时,即表示查找最近地物,如果查询结果数大于期望返回的结果记录数(expectCount), * 则查找结果为查询总记录中距离中心最近的 expectCount 个地物。 * 当该属性为不为 true 时,如果查询结果数大于期望返回的结果记录数(expectCount), * 则查找结果为从查询总记录中随机抽取的 expectCount 个地物。 * 目前查询结果不支持按远近距离排序。 */ this.isNearest = null; /** * @member {boolean} [QueryByDistanceParameters.prototype.returnContent=true] * @description 是否立即返回新创建资源的表述还是返回新资源的 URI。 * 如果为 true,则直接返回新创建资源,即查询结果的表述。 * 为 false,则返回的是查询结果资源的 URI。 */ this.returnContent = true; Util.extend(this, options); this.CLASS_NAME = "SuperMap.QueryByDistanceParameters"; } /** * @function QueryByDistanceParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.returnContent = null; me.distance = null; me.isNearest = null; if (me.geometry) { me.geometry.destroy(); me.geometry = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryByDistanceService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryByDistanceService * @deprecatedclass SuperMap.QueryByDistanceService * @category iServer Map QueryResults * @classdesc Distance查询服务类。 * @extends {QueryService} * @example * var myQueryByDistService = new QueryByDistanceService(url, { * eventListeners: { * "processCompleted": queryCompleted, * "processFailed": queryError * } * }); * function queryCompleted(object){//todo}; * function queryError(object){//todo}; * @param {string} url - 服务地址。如访问World Map服务,只需将url设为:http://localhost:8090/iserver/services/map-world/rest/maps/World+Map 即可。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class QueryByDistanceService extends QueryService { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.QueryByDistanceService"; } /** * @override */ destroy() { super.destroy(); } /** * @function QueryByDistanceService.prototype.getJsonParameters * @description 将查询参数转化为 JSON 字符串。 * 在本类中重写此方法,可以实现不同种类的查询(sql, geometry, distance, bounds等)。 * @param {QueryByDistanceParameters} params - Distance 查询参数类。 * @returns {Object} 转化后的 JSON 字符串。 */ getJsonParameters(params) { if (!(params instanceof QueryByDistanceParameters)) { return; } var me = this, jsonParameters = "", qp = me.getQueryParameters(params); var sg = ServerGeometry.fromGeometry(params.geometry); jsonParameters += params.isNearest ? "'queryMode':'FindNearest','queryParameters':" : "'queryMode':'DistanceQuery','queryParameters':"; jsonParameters += Util.toJSON(qp); jsonParameters += ",'geometry':" + Util.toJSON(sg) + ",'distance':" + params.distance; jsonParameters = "{" + jsonParameters + "}"; return jsonParameters; } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryByGeometryParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryByGeometryParameters * @deprecatedclass SuperMap.QueryByGeometryParameters * @category iServer Map QueryResults * @classdesc Geometry 查询参数类。 * 该类用于设置 Geometry查询的相关参数。 * @extends {QueryParameters} * @param {Object} options - 参数。 * @param {Array.} options.queryParams - 查询过滤条件参数数组。 * @param {GeoJSONObject} options.geometry - 查询的几何对象。 * @param {string} [options.customParams] - 自定义参数,供扩展使用。 * @param {QueryOption} [options.queryOption=QueryOption.ATTRIBUTEANDGEOMETRY] - 查询结果类型枚举类。 * @param {Object} [options.prjCoordSys] -自定义参数,供SuperMap Online提供的动态投影查询扩展使用。如 {"epsgCode":3857}。 * @param {number} [options.expectCount=100000] - 期望返回结果记录个数。 * @param {GeometryType} [options.networkType=GeometryType.LINE] - 网络数据集对应的查询类型。 * @param {boolean} [options.returnCustomResult=false] -仅供三维使用。 * @param {number} [options.startRecord=0] - 查询起始记录号。 * @param {number} [options.holdTime=10] - 资源在服务端保存的时间,单位为分钟。 * @param {boolean} [options.returnContent=true] - 是否立即返回新创建资源的表述还是返回新资源的 URI。 * @param {boolean} [options.returnFeatureWithFieldCaption = false] - 返回的查询结果要素字段标识是否为字段别名。为 false 时,返回的是字段名;为 true 时,返回的是字段别名。 * @param {SpatialQueryMode} [spatialQueryMode=SpatialQueryMode.INTERSECT] - 空间查询模式。 * @usage */ class QueryByGeometryParameters extends QueryParameters { constructor(options) { options = options || {}; super(options); /** * @member {boolean} [QueryByGeometryParameters.prototype.returnContent=true] * @description 是否立即返回新创建资源的表述还是返回新资源的 URI。
* 如果为 true,则直接返回新创建资源,即查询结果的表述。
* 为 false,则返回的是查询结果资源的 URI。 */ this.returnContent = true; /** * @member {GeoJSONObject} QueryByGeometryParameters.prototype.geometry * @description 用于查询的几何对象。
* 点类型可以是:{@link GeometryPoint}|{@link L.Marker}|{@link L.CircleMarker}|{@link L.Circle}|{@link L.GeoJSON}|{@link ol.geom.Point}|{@link ol.format.GeoJSON}|{@link mapboxgl.LngLat}|{@link mapboxgl.Point}|{@link GeoJSONObject}。
* 线类型可以是:{@link GeometryLineString}|{@link GeometryLinearRing}|{@link L.Polyline}|{@link L.GeoJSON}|{@link ol.geom.LineString}|{@link ol.format.GeoJSON}|{@link GeoJSONObject}。
* 面类型可以是:{@link GeometryPolygon}|{@link L.Polygon}|{@link L.GeoJSON}|{@link ol.geom.Polygon}|{@link ol.format.GeoJSON}|{@link mapboxgl.LngLatBounds}|{@link GeoJSONObject}。 */ this.geometry = null; /** * @member {SpatialQueryMode} [QueryByGeometryParameters.prototype.spatialQueryMode=SpatialQueryMode.INTERSECT] * @description 空间查询模式。 */ this.spatialQueryMode = SpatialQueryMode.INTERSECT; Util.extend(this, options); this.CLASS_NAME = "SuperMap.QueryByGeometryParameters"; } /** * @function QueryByGeometryParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.returnContent = null; me.geometry = null; me.spatialQueryMode = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryByGeometryService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryByGeometryService * @deprecatedclass SuperMap.QueryByGeometryService * @category iServer Map QueryResults * @classdesc Geometry查询服务类。 * @extends {QueryService} * @example * var myQueryByGeometryService = new QueryByGeometryService(url, { * eventListeners: { * "processCompleted": queryCompleted, * "processFailed": queryError * } * }); * function queryCompleted(object){//todo}; * function queryError(object){//todo}; * @param {string} url - 服务地址。如访问World Map服务,只需将url设为: http://localhost:8090/iserver/services/map-world/rest/maps/World+Map 即可。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class QueryByGeometryService extends QueryService { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.QueryByGeometryService"; } /** * @override */ destroy() { super.destroy(); } /** * @function QueryByGeometryService.prototype.getJsonParameters * @description 将查询参数转化为 JSON 字符串。 * 在本类中重写此方法,可以实现不同种类的查询(sql, geometry, distance, bounds等)。 * @param {QueryByGeometryParameters} params - Geometry 查询参数类。 * @returns {Object} 转化后的 JSON 字符串。 */ getJsonParameters(params) { if (!(params instanceof QueryByGeometryParameters)) { return; } var me = this, jsonParameters = "", qp = null, geometry = params.geometry, sg = ServerGeometry.fromGeometry(geometry); qp = me.getQueryParameters(params); jsonParameters += "'queryMode':'SpatialQuery','queryParameters':"; jsonParameters += Util.toJSON(qp) + ",'geometry':" + Util.toJSON(sg) + ",'spatialQueryMode':" + Util.toJSON(params.spatialQueryMode); jsonParameters = "{" + jsonParameters + "}"; return jsonParameters; } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryBySQLParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryBySQLParameters * @deprecatedclass SuperMap.QueryBySQLParameters * @category iServer Map QueryResults * @classdesc SQL 查询参数类。 * 该类用于设置 SQL 查询的相关参数。 * @extends {QueryParameters} * @param {Object} options - 参数。 * @param {Array.} options.queryParams - 查询过滤条件参数数组。 * @param {string} [options.customParams] - 自定义参数,供扩展使用。 * @param {Object} [options.prjCoordSys] - 自定义参数,供 SuperMap Online 提供的动态投影查询扩展使用。如 {"epsgCode":3857}。 * @param {number} [options.expectCount=100000] - 期望返回结果记录个数。 * @param {GeometryType} [options.networkType=GeometryType.LINE] - 网络数据集对应的查询类型。 * @param {QueryOption} [options.queryOption=QueryOption.ATTRIBUTEANDGEOMETRY] - 查询结果类型枚举类。 * @param {number} [options.startRecord=0] - 查询起始记录号。 * @param {number} [options.holdTime=10] - 资源在服务端保存的时间,单位为分钟。 * @param {boolean} [options.returnCustomResult=false] - 仅供三维使用。 * @param {boolean} [options.returnContent=true] - 是否立即返回新创建资源的表述还是返回新资源的 URI。 * @param {boolean} [options.returnFeatureWithFieldCaption = false] - 返回的查询结果要素字段标识是否为字段别名。为 false 时,返回的是字段名;为 true 时,返回的是字段别名。 * @usage */ class QueryBySQLParameters extends QueryParameters { constructor(options) { options = options || {}; super(options); /** * @member {boolean} [QueryBySQLParameters.prototype.returnContent=true] * @description 是否立即返回新创建资源的表述还是返回新资源的 URI。 * 如果为 true,则直接返回新创建资源,即查询结果的表述。 * 为 false,则返回的是查询结果资源的 URI。 */ this.returnContent = true; Util.extend(this, options); this.CLASS_NAME = "SuperMap.QueryBySQLParameters"; } /** * @function QueryBySQLParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); var me = this; me.returnContent = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/QueryBySQLService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryBySQLService * @deprecatedclass SuperMap.QueryBySQLService * @category iServer Map QueryResults * @classdesc SQL 查询服务类。在一个或多个指定的图层上查询符合 SQL 条件的空间地物信息。 * @extends {QueryService} * @example * var queryParam = new FilterParameter({ * name: "Countries@World.1", * attributeFilter: "Pop_1994>1000000000 and SmArea>900" * }); * var queryBySQLParams = new QueryBySQLParameters({ * queryParams: [queryParam] * }); * var myQueryBySQLService = new QueryBySQLService(url, {eventListeners: { * "processCompleted": queryCompleted, * "processFailed": queryError * } * }); * queryBySQLService.processAsync(queryBySQLParams); * function queryCompleted(object){//todo}; * function queryError(object){//todo}; * @param {string} url - 服务地址。如访问World Map服务,只需将url设为: http://localhost:8090/iserver/services/map-world/rest/maps/World+Map 即可。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON、GeoJSON、FGB 三种格式。参数格式为 "ISERVER","GEOJSON","FGB"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class QueryBySQLService extends QueryService { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.QueryBySQLService"; } /** * @override */ destroy() { super.destroy(); } /** * @function QueryBySQLService.prototype.getJsonParameters * @description 将查询参数转化为 JSON 字符串。 * 在本类中重写此方法,可以实现不同种类的查询(sql, geometry, distance, bounds等)。 * @param {QueryBySQLParameters} params - SQL 查询参数类。 * @returns {Object} 转化后的 JSON 字符串。 */ getJsonParameters(params) { if (!(params instanceof QueryBySQLParameters)) { return; } var me = this, jsonParameters = "", qp = null; qp = me.getQueryParameters(params); jsonParameters += "'queryMode':'SqlQuery','queryParameters':"; jsonParameters += Util.toJSON(qp); jsonParameters = "{" + jsonParameters + "}"; return jsonParameters; } } ;// CONCATENATED MODULE: ./src/common/iServer/RouteCalculateMeasureParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class RouteCalculateMeasureParameters * @deprecatedclass SuperMap.RouteCalculateMeasureParameters * @category iServer SpatialAnalyst RouteCalculateMeasure * @classdesc 基于路由对象计算指定点 M 值操作的参数类。通过该类提供参数信息。 * @param {Object} options - 参数。 * @param {(Route|L.Polyline|ol.geom.LineString|GeoJSONObject)} options.sourceRoute - 路由对象。该对象可以是用户自己生成或在数据源中查询得到的符合标准的路由对象。 * @param {GeometryPoint|L.LatLng|L.Point|ol.geom.Point|mapboxgl.LngLat|Array.} options.point - 二维地理坐标点对象,包含 x,y 坐标值属性的对象。 * @param {number} [options.tolerance] - 容限值。 * @param {boolean} [options.isIgnoreGap=false] - 是否忽略子对象之间的距离。 * @usage */ class RouteCalculateMeasureParameters { constructor(options) { if (!options) { return this; } /** * @member {(Route|L.Polyline|ol.geom.LineString|GeoJSONObject)} RouteCalculateMeasureParameters.prototype.sourceRoute * @description 路由对象。该对象可以是用户自己生成或在数据源中查询得到的符合标准的路由对象。 */ this.sourceRoute = null; /** * @member {GeometryPoint|L.LatLng|L.Point|ol.geom.Point|mapboxgl.LngLat|Array.} RouteCalculateMeasureParameters.prototype.point * @description 二维地理坐标点对象,包含 x,y 坐标值属性的对象。 */ this.point = null; /** * @member {number} [RouteCalculateMeasureParameters.prototype.tolerance] * @description 容限值。 */ this.tolerance = null; /** * @member {boolean} [RouteCalculateMeasureParameters.prototype.isIgnoreGap=false] * @description 是否忽略子对象之间的距离。 */ this.isIgnoreGap = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.RouteCalculateMeasureParameters"; } /** * @function RouteCalculateMeasureParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.sourceRoute = null; me.point = null; if (me.tolerance) { me.tolerance = null; } if (me.isIgnoreGap) { me.isIgnoreGap = false; } } } ;// CONCATENATED MODULE: ./src/common/iServer/RouteCalculateMeasureService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class RouteCalculateMeasureService * @deprecatedclass SuperMap.RouteCalculateMeasureService * @category iServer SpatialAnalyst RouteCalculateMeasure * @classdesc 基于路由对象计算指定点 M 值操作的服务类。 * 该类负责将客户设置的计算指定点的 M 值参数传递给服务端,并接收服务端返回的 * 指定点的 M 值。通过该类支持的事件的监听函数参数获取。 * @extends {SpatialAnalystBase} * @param {string} url - 服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example 实例化该类如下例所示: * (start code) * var parameters = new RouteCalculateMeasureParameters({ * "sourceRoute":{ * "type":"LINEM", * "parts":[4], * "points":[ * { * "measure":0, * "y":-6674.466867067764, * "x":3817.3527876130133 * }, * { * "measure":199.57954019411724, * "y":-6670.830929417594, * "x":3617.806369901496 * }, * { * "measure":609.3656478634477, * "y":-6877.837541432356, * "x":3264.1498746678444 * }, * { * "measure":936.0174126282958, * "y":-7038.687780615184, * "x":2979.846206068903 * } * ] * }, * "tolerance":1, * "point":{ * "x":3330.7754269417, * "y":-6838.8394457216 * }, * "isIgnoreGap":false * }); * * var routeCalculateMeasureService = new RouteCalculateMeasureService(spatialAnalystURL, { * eventListeners:{ * processCompleted:calculateCompleted, * processFailed:calculateFailded * } * ); * routeCalculateMeasureService.processAsync(parameters); * * //执行 * function calculateCompleted(){todo} * function calculateFailded(){todo} * (end) * @usage */ class RouteCalculateMeasureService extends SpatialAnalystBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.RouteCalculateMeasureService"; } /** * @override */ destroy() { super.destroy(); } /** * @function RouteCalculateMeasureService.prototype.processAsync * @description 负责将客户端的基于路由对象计算指定点 M 值操作的参数传递到服务端。 * @param {RouteCalculateMeasureParameters} params - 基于路由对象计算指定点 M 值操作的参数类。 */ processAsync(params) { if (!(params instanceof RouteCalculateMeasureParameters)) { return; } var me = this, jsonParameters; jsonParameters = me.getJsonParameters(params); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function RouteCalculateMeasureService.prototype.getJsonParameters * @description 将参数转化为 JSON 字符串。 * @param {RouteCalculateMeasureParameters} params - 基于路由对象计算指定点 M 值操作的参数类。 * @returns {Object} 转化后的 JSON 字符串。 */ getJsonParameters(params) { var jsonParameters, jsonStr = "geometry/calculatemeasure", me = this; me.url = Util.urlPathAppend(me.url, jsonStr); me.url = Util.urlAppend(me.url, 'returnContent=true'); jsonParameters = Util.toJSON(params); return jsonParameters; } } ;// CONCATENATED MODULE: ./src/common/iServer/RouteLocatorParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class RouteLocatorParameters * @deprecatedclass SuperMap.RouteLocatorParameters * @category iServer SpatialAnalyst RouteLocator * @classdesc 路由对象定位空间对象的参数类。 * 参数有两种方式,分别为 Geometry 和 Dataset 两种,前者需要指定 sourceRoute 对象作为参数,后者需要 dataset,routeIDField,routeID 三个参数。如果用户两种参数均设置,优先选择 Dataset 方式。 * @param {Object} options - 参数。 * @param {(Route|L.Polyline|ol.geom.LineString|GeoJSONObject)} options.sourceRoute - 路由对象。 * @param {number} options.measure - 定位点的 M 值。只当路由对象定位点时有意义。 * @param {string} [options.type] - 类型:点 or 线。 * @param {number} [options.offset=0] - 定位点偏移量。只当路由对象定位点时有意义。 * @param {boolean} [options.isIgnoreGap=false] - 是否忽略子对象之间的距离。即不忽略子对象之间的距离。 * @param {number} [options.startMeasure] - 定位线的起始 M 值。只当路由对象定位线时有意义。 * @param {number} [options.endMeasure] - 定位线的终止 M 值。只当路由对象定位线时有意义。 * @usage */ class RouteLocatorParameters { constructor(options) { if (!options) { return this; } /** * @member {(Route|L.Polyline|ol.geom.LineString|GeoJSONObject)} RouteLocatorParameters.prototype.sourceRoute * @description 路由对象。 */ this.sourceRoute = null; /** * @member {string} RouteLocatorParameters.prototype.dataset * @description 要用来做缓冲区分析的数据源中数据集的名称。该名称用形如"数据集名称@数据源别名"形式来表示。 */ this.dataset = null; /** * @member {string} RouteLocatorParameters.prototype.routeIDField * @description 路由对象所在的字段名称。 * */ this.routeIDField = null; /** * @member {number} RouteLocatorParameters.prototype.routeID * @description 路由对象标识。 * */ this.routeID = null; /** * @member {string} [RouteLocatorParameters.prototype.type] * @description 类型:点 or 线。 * 可选值为: * LINE :根据起始 M 值及终止 M 值定位线对象。 * POINT : 根据 M 值定位点对象。 */ this.type = null; /** * @member {number} RouteLocatorParameters.prototype.measure * @description 定位点的 M 值。只当路由对象定位点时有意义。 */ this.measure = null; /** * @member {number} [RouteLocatorParameters.prototype.offset=0] * @description 定位点偏移量。只当路由对象定位点时有意义。 */ this.offset = 0; /** * @member {boolean} [RouteLocatorParameters.prototype.isIgnoreGap=false] * @description 是否忽略子对象之间的距离。 */ this.isIgnoreGap = false; /** * @member {number} [RouteLocatorParameters.prototype.startMeasure] * @description 定位线的起始 M 值。只当路由对象定位线时有意义。 */ this.startMeasure = null; /** * @member {number} [RouteLocatorParameters.prototype.endMeasure] * @description 定位线的终止 M 值。只当路由对象定位线时有意义。 */ this.endMeasure = null; var routeFromClient = options.sourceRoute; var routeHandle = {}; if (routeFromClient && routeFromClient instanceof Geometry_Geometry && routeFromClient.components) { routeHandle.type = routeFromClient.type; routeHandle.parts = routeFromClient.parts; var parts = []; for (var i = 0, len = routeFromClient.components.length; i < len; i++) { parts = parts.concat(routeFromClient.components[i].components); } routeHandle.points = parts; options.sourceRoute = routeHandle; } Util.extend(this, options); this.CLASS_NAME = "SuperMap.RouteLocatorParameters"; } /** * @function RouteLocatorParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.sourceRoute = null; me.type = null; me.measure = null; me.offset = 0; me.isIgnoreGap = false; me.startMeasure = null; me.endMeasure = null; me.dataset = null; me.routeID = null; me.routeIDField = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/RouteLocatorService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class RouteLocatorService * @deprecatedclass SuperMap.RouteLocatorService * @category iServer SpatialAnalyst RouteLocator * @classdesc 路由对象定位空间对象的服务类。 * @extends {SpatialAnalystBase} * @param {string} url -服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example 实例化该类如下例所示: * (start code) * var routeLocatorParameters_point = new RouteLocatorParameters({ * "sourceRoute":{ * "type":"LINEM", * "parts":[4], * "points":[ * { * "measure":0, * "y":-6674.466867067764, * "x":3817.3527876130133 * }, * { * "measure":199.57954019411724, * "y":-6670.830929417594, * "x":3617.806369901496 * }, * { * "measure":609.3656478634477, * "y":-6877.837541432356, * "x":3264.1498746678444 * }, * { * "measure":936.0174126282958, * "y":-7038.687780615184, * "x":2979.846206068903 * } * ] * }, * "type":"POINT", * "measure":10, * "offset":3, * "isIgnoreGap":true * }); * var routeLocatorService = new RouteLocatorService(spatialAnalystURL, { * eventListeners:{ * processCompleted:routeLocatorCompleted, * processFailed:routeLocatorFailded * } * ); * routeLocatorService.processAsync(routeLocatorParameters_point); * * //执行 * function routeLocatorCompleted(){todo} * function routeLocatorFailded(){todo} * (end) * @usage */ class RouteLocatorService extends SpatialAnalystBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.RouteLocatorService"; } /** * @override */ destroy() { super.destroy(); } /** * @function RouteLocatorService.prototype.processAsync * @description 负责将客户端的基于路由对象计算指定点 M 值操作的参数传递到服务端。 * @param {RouteLocatorParameters} params - 路由对象定位空间对象的参数类。 */ processAsync(params) { if (!(params instanceof RouteLocatorParameters)) { return; } var me = this, jsonParameters; jsonParameters = me.getJsonParameters(params); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function RouteLocatorService.prototype.processAsync * @description 将参数转化为 JSON 字符串。 * @param {RouteLocatorParameters} params - 路由对象定位空间对象的参数类。 * @returns {Object} 转化后的JSON字符串。 */ getJsonParameters(params) { var jsonParameters, jsonStr = "geometry/routelocator", me = this; if (params.dataset) { jsonStr = "datasets/" + params.dataset + "/linearreferencing/routelocator"; params.sourceRoute = null; } me.url = Util.urlPathAppend(me.url, jsonStr); me.url = Util.urlAppend(me.url, 'returnContent=true'); jsonParameters = Util.toJSON(params); return jsonParameters; } } ;// CONCATENATED MODULE: ./src/common/iServer/ServerFeature.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ServerFeature * @deprecatedclass SuperMap.ServerFeature * @category iServer Data Feature * @classdesc 服务端矢量要素类。该类描述了服务端返回的矢量要素的相关信息,包括字段和几何信息。 * @param {ServerGeometry} geometry - 矢量要素的几何信息。 * @param {Object} options - 参数。 * @param {Array.} [options.fieldNames] - 矢量要素的属性字段名集合。 * @param {Array.} [options.fieldValues] - 矢量要素的属性字段值集合。 * @usage */ class ServerFeature { constructor(options) { /** * @member {Array.} [ServerFeature.prototype.fieldNames] * @description 矢量要素的属性字段名集合。 */ this.fieldNames = null; /** * @member {Array.} [ServerFeature.prototype.fieldValues] * @description 矢量要素的属性字段值集合。 */ this.fieldValues = null; /** * @member {ServerGeometry} ServerFeature.prototype.geometry * @description 矢量要素的几何信息。 */ this.geometry = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ServerFeature"; } /** * @function ServerFeature.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.fieldNames = null; me.fieldValues = null; if (me.geometry) { me.geometry.destroy(); me.geometry = null; } } /** * @function ServerFeature.prototype.toFeature * @description 将服务端矢量要素 ServerFeature 转换为客户端矢量要素 Feature。 * @returns {Vector} 转换后的客户端矢量要素。 */ toFeature() { var names, values, geo, attr = {}, me = this, feature; names = me.fieldNames; values = me.fieldValues; for (var i in names) { attr[names[i]] = values[i]; } if (me.geometry) { geo = me.geometry.toGeometry(); } feature = new Vector(geo, attr); if (me.geometry && me.geometry.id) { feature.fid = me.geometry.id; } return feature; } /** * @function ServerFeature.prototype.fromJson * @description 将 JSON 对象表示服务端矢量要素转换为 ServerFeature。 * @param {Object} jsonObject - 要转换的 JSON 对象。 * @returns {ServerFeature} 转化后的 ServerFeature 对象。 */ static fromJson(jsonObject) { var geo = null; if (!jsonObject) { return; } geo = jsonObject.geometry; if (geo) { geo = ServerGeometry.fromJson(geo); } return new ServerFeature({ fieldNames: jsonObject.fieldNames, fieldValues: jsonObject.fieldValues, geometry: geo }); } } ;// CONCATENATED MODULE: ./src/common/iServer/SetDatasourceParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SetDatasourceParameters * @deprecatedclass SuperMap.SetDatasourceParameters * @category iServer Data Datasource * @classdesc 设置数据源信息参数类。 * @param {Object} options - 参数。 * @param {string} options.datasourceName - 数据源名称。 * @param {string} options.description - 数据源描述信息。 * @param {string} options.coordUnit - 坐标单位。 * @param {string} options.distanceUnit - 距离单位。 * @usage */ class SetDatasourceParameters { constructor(options) { if (!options) { return; } /** * @member {string} SetDatasourceParameters.prototype.datasourceName * @description 数据源名称。 */ this.datasourceName = null; /** * @member {string} SetDatasourceParameters.prototype.description * @description 数据源描述信息。 */ this.description = null; /** * @member {string} SetDatasourceParameters.prototype.coordUnit * @description 坐标单位。 */ this.coordUnit = null; /** * @member {string} SetDatasourceParameters.prototype.distanceUnit * @description 距离单位。 */ this.distanceUnit = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.SetDatasourceParameters"; } /** * @function SetDatasourceParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.datasourceName = null; me.description = null; me.coordUnit = null; me.distanceUnit = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/SetLayerInfoParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SetLayerInfoParameters * @deprecatedclass SuperMap.SetLayerInfoParameters * @category iServer Map TempLayersSet * @classdesc 设置图层信息参数类。 * @param {Object} options - 参数。 * @param {string} options.resourceID - 临时图层的资源 ID。 * @param {string} options.tempLayerName - 临时图层下的子图层名。 * @param {string} options.layerInfo - 要更新的图层信息。 * @usage */ class SetLayerInfoParameters { constructor(options) { options = options || {}; /** * @member {string} SetLayerInfoParameters.prototype.resourceID * @description 临时图层的资源 ID。 */ this.resourceID = null; /** * @member {string} SetLayerInfoParameters.prototype.tempLayerName * @description 临时图层下子图层(或者其子图层)名,如:Countries@World.3@@World。 */ this.tempLayerName = null; /** * @member {Object} SetLayerInfoParameters.prototype.layerInfo * @description 要更新的图层信息(包含修改和未修改的所有字段)。该参数可以通过图层信息服务获取,然后对返回值中 subLayers.layers[i] 图层信息属性进行修改。 */ this.layerInfo = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.SetLayerInfoParameters"; } /** * @function SetLayerInfoParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.resourceID = null; me.tempLayerName = null; me.layerInfo = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/SetLayerInfoService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SetLayerInfoService * @deprecatedclass SuperMap.SetLayerInfoService * @category iServer Map TempLayersSet * @classdesc 设置图层信息服务类。可以实现临时图层中子图层的修改 * 该类负责将图层设置参数传递到服务端,并获取服务端返回的结果信息。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求地图服务,URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{地图服务名}/rest/maps/{地图名}/tempLayersSet/{tempLayerID}/Rivers@World@@World"; * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class SetLayerInfoService extends CommonServiceBase { constructor(url, options) { super(url, options); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.SetLayerInfoService"; } /** * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function SetLayerInfoService.prototype.processAsync * @description 负责将客户端的更新参数传递到服务端。 * @param {Object} params - 修改后的图层资源信息。 * 该参数可以使用获取图层信息服务<{@link GetLayersInfoService}>返回图层信息,解析结果result.subLayers.layers[i],然后对其属性进行修改来获取。 */ processAsync(params) { if (!params) { return; } var me = this; var jsonParamsStr = Util.toJSON(params); me.request({ method: "PUT", data: jsonParamsStr, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/SetLayersInfoParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SetLayersInfoParameters * @deprecatedclass SuperMap.SetLayersInfoParameters * @category iServer Map TempLayersSet * @classdesc 设置图层信息参数类。 * @param {Object} options - 参数。 * @param {boolean} [options.isTempLayers=false] - 是否是临时图层。 * @param {string} options.resourceID - 临时图层资源 ID。 * @param {Object} options.layersInfo - 要更新的图层信息。 * @usage */ class SetLayersInfoParameters { constructor(options) { options = options || {}; /** * @member {boolean} [SetLayersInfoParameters.prototype.isTempLayers=false] * @description 是否是临时图层。 */ this.isTempLayers = null; /** * @member {string} SetLayersInfoParameters.prototype.resourceID * @description 临时图层资源 ID。 */ this.resourceID = null; /** * @member {Object} SetLayersInfoParameters.prototype.layersInfo * @description 要更新的图层信息(包含修改和未修改的所有字段)。该参数可以通过图层信息服务获取,然后对返回值中 subLayers.layers[i] 图层信息属性进行修改。 */ this.layersInfo = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.SetLayersInfoParameters"; } /** * @function SetLayersInfoParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.isTempLayers = null; me.resourceID = null; me.layersInfo = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/SetLayersInfoService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SetLayersInfoService * @deprecatedclass SuperMap.SetLayersInfoService * @category iServer Map TempLayersSet * @classdesc 设置图层信息服务类。可以实现创建新的临时图层和对现有临时图层的修改, * 当 isTempLayers 为 false的时候执行创建临时图层。当 isTempLayers 为 ture 并且临时图层资源 resourceID 被设置有效时执行对临时图层的编辑。 * 该类负责将图层设置参数传递到服务端,并获取服务端返回的结果信息。 * @extends {CommonServiceBase} * @param url - {string} 服务地址。请求地图服务,URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{地图服务名}/rest/maps/{地图名}; * @param {Object} options - 参数。 * @param {string} options.resourceID - 图层资源ID,临时图层的资源ID标记。 * @param {boolean} options.isTempLayers - 当前url对应的图层是否是临时图层。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class SetLayersInfoService extends CommonServiceBase { constructor(url, options) { super(url, options); /** * @member {string} SetLayersInfoService.prototype.resourceID * @description 图层资源ID,临时图层的资源ID标记。 */ this.resourceID = null; /** * @function {boolean} SetLayersInfoService.prototype.isTempLayers * @description 当前url对应的图层是否是临时图层。 */ this.isTempLayers = false; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.SetLayersInfoService"; } /** * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function SetLayersInfoService.prototype.processAsync * @description 负责将客户端的更新参数传递到服务端。 * @param {Object} params - 修改后的图层资源信息。该参数可以使用获取图层信息服务 <{@link GetLayersInfoService}>返回图层信息,然后对其属性进行修改来获取。 */ processAsync(params) { if (!params) { return; } var jsonParams, subLayers = [], me = this, method = ""; //创建临时图层和设置修改临时图层信息对应不同的资源URL if (me.isTempLayers) { me.url = Util.urlPathAppend(me.url, "tempLayersSet/" + me.resourceID); method = "PUT"; } else { me.url = Util.urlPathAppend(me.url, "tempLayersSet"); method = "POST"; } if (!params.subLayers) { params.subLayers = {layers: []} } if (!params.subLayers.layers) { params.subLayers.layers = []; } var layers = params.subLayers.layers, len = layers.length; for (let i in layers) { if (layers[i].ugcLayerType === "GRID") { var colorDictionary = {}; var colorDics = layers[i].colorDictionarys; for (var j in colorDics) { var key = colorDics[j].elevation; colorDictionary[key] = colorDics[j].color; } } layers[i].colorDictionary = colorDictionary; delete layers[i].colorDictionarys; } for (let i = 0; i < len; i++) { if (layers[i].toJsonObject) { //将图层信息转换成服务端能识别的简单json对象 subLayers.push(layers[i].toJsonObject()); } else { subLayers.push(layers[i]); } } jsonParams = Util.extend(jsonParams, params); jsonParams.subLayers = {"layers": subLayers}; jsonParams.object = null; var jsonParamsStr = Util.toJSON([jsonParams]); me.request({ method: method, data: jsonParamsStr, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/SetLayerStatusParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SetLayerStatusParameters * @deprecatedclass SuperMap.SetLayerStatusParameters * @category iServer Map TempLayersSet * @classdesc 子图层显示控制参数类,该类存储了各子图层是否可见的状态。 * 注意在 SuperMap iClient 系列产品中所说的图层与 SuperMap Deskpro 的地图对应,子图层与 SuperMap Deskpro 的图层对应。 * @param {Object} options - 参数。 * @param {Array.} options.layerStatusList - 获取或设置图层可见状态({@link LayerStatus})集合, * 集合中的每个 {@link LayerStatus} 对象代表一个子图层的可视状态。 * @param {number} [options.holdTime=15] - 获取或设置资源在服务端保存的时间。 * @param {string} [options.resourceID] - 获取或设置资源服务 ID。 * @usage */ class SetLayerStatusParameters { constructor(options) { /** * @member {Array.} SetLayerStatusParameters.prototype.layerStatusList * @description 获取或设置图层可见状态({@link LayerStatus})集合,集合中的每个 {@link LayerStatus} 对象代表一个子图层的可视状态。 */ this.layerStatusList = []; /** * @member {number} [SetLayerStatusParameters.prototype.holdTime=15] * @description 获取或设置资源在服务端保存的时间。单位为分钟。 */ this.holdTime = 15; /** * @member {string} SetLayerStatusParameters.prototype.resourceID * @description 获取或设置资源服务ID。如果设置该参数则会在指定的 TempLayer 中进行图层的显示控制; * 如果不设置该参数,则会首先创建一个 TempLayer ,然后在新创建的 TempLayer 中进行图层的显示控制。 */ this.resourceID = null; if (options) { Util.extend(this, options); } } /** * @function SetLayerStatusParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.layerStatusList = null; me.holdTime = null; me.resourceID = null; } /** * @function SetLayerStatusParameters.prototype.toJSON * @description 生成 JSON。 * @returns {Object} 对应的 JSON 对象。 */ toJSON() { var json = '{'; json += '"layers":['; var v = []; for (var i = 0, len = this.layerStatusList.length; i < len; i++) { v.push(this.layerStatusList[i].toJSON()); } json += v; json += ']'; json += '}'; return json; } } ;// CONCATENATED MODULE: ./src/common/iServer/SetLayerStatusService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SetLayerStatusService * @deprecatedclass SuperMap.SetLayerStatusService * @category iServer Map TempLayersSet * @classdesc 子图层显示控制服务类。该类负责将子图层显示控制参数传递到服务端,并获取服务端返回的图层显示状态。 * 用户获取服务端返回的各子图层显示状态有两种方式: * 一种是通过监听 SetLayerEvent.PROCESS_COMPLETE 事件; * 一种是使用 AsyncResponder 类实现异步处理。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求地图服务,URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{地图服务名}/rest/maps/{地图名}; * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class SetLayerStatusService extends CommonServiceBase { constructor(url, options) { super(url, options); this.lastparams = null; this.mapUrl = url; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.SetLayerStatusService"; } /** * @override */ destroy() { super.destroy(); Util.reset(this); } /** * @function SetLayerStatusService.prototype.processAsync * @description 负责将客户端的更新参数传递到服务端。 * @param {Object} params - 修改后的图层资源信息。该参数可以使用获取图层信息服务{@link SetLayerStatusParameters} * 返回图层信息,然后对其属性进行修改来获取。 */ processAsync(params) { if (!(params instanceof SetLayerStatusParameters)) { return; } var me = this, method = "POST"; me.url = me.mapUrl; if (params.resourceID == null) { me.url = Util.urlPathAppend(me.url, 'tempLayersSet'); me.lastparams = params; me.request({ method: method, scope: me, success: me.createTempLayerComplete, failure: me.serviceProcessFailed }); } else { me.url = Util.urlPathAppend(me.url, "tempLayersSet/" + params.resourceID); me.url = Util.urlAppend(me.url, "elementRemain=true&reference=" + params.resourceID + "&holdTime=" + params.holdTime.toString()); var jsonParameters = '[{'; jsonParameters += '"type":"UGC",'; if (params.layerStatusList != null && params.layerStatusList.length > 0) { jsonParameters += '"subLayers":' + params.toJSON(); } jsonParameters += ',"visible":' + true + ','; jsonParameters += '"name":"' + this.getMapName(this.mapUrl) + '"'; jsonParameters += '}]'; me.request({ method: "PUT", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } /** * @function SetLayerStatusService.prototype.createTempLayerComplete * @description 设置完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象,记录设置操作是否成功。 */ createTempLayerComplete(result) { var me = this; result = Util.transformResult(result); if (result.succeed) { me.lastparams.resourceID = result.newResourceID; } me.processAsync(me.lastparams); } /** * @function SetLayerStatusService.prototype.getMapName * @description 获取地图名称。 * @param {Object} url - 服务地址。 */ getMapName(url) { var mapUrl = url; if (mapUrl.charAt(mapUrl.length - 1) === "/") { mapUrl = mapUrl.substr(0, mapUrl.length - 1); } var index = mapUrl.lastIndexOf("/"); var mapName = mapUrl.substring(index + 1, mapUrl.length); return mapName; } /** * @function SetLayerStatusService.prototype.setLayerCompleted * @description 设置完成,执行此方法。 * @param {Object} result - 服务器返回的结果对象,记录设置操作是否成功。 */ serviceProcessCompleted(result) { var me = this; result = Util.transformResult(result); if (result != null && me.lastparams != null) { result.newResourceID = me.lastparams.resourceID; } me.events.triggerEvent("processCompleted", {result: result}); } } ;// CONCATENATED MODULE: ./src/common/iServer/SingleObjectQueryJobsParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SingleObjectQueryJobsParameter * @deprecatedclass SuperMap.SingleObjectQueryJobsParameter * @category iServer ProcessingService Query * @classdesc 单对象空间查询分析任务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {string} options.datasetQuery - 查询对象所在的数据集名称。 * @param {SpatialQueryMode} [options.mode=SpatialQueryMode.CONTAIN] - 空间查询模式。 * @param {OutputSetting} [options.output] - 输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class SingleObjectQueryJobsParameter { constructor(options) { if (!options) { return; } /** * @member {string} SingleObjectQueryJobsParameter.prototype.datasetName * @description 数据集名。 */ this.datasetName = ""; /** * @member {string} SingleObjectQueryJobsParameter.prototype.datasetQuery * @description 查询对象所在的数据集名称。 */ this.datasetQuery = ""; /** * @member {string} SingleObjectQueryJobsParameter.prototype.geometryQuery * @description 查询对象所在的几何对象。 */ this.geometryQuery = ""; /** * @member {SpatialQueryMode} [SingleObjectQueryJobsParameter.prototype.mode=SpatialQueryMode.CONTAIN] * @description 空间查询模式 。 */ this.mode = SpatialQueryMode.CONTAIN; /** * @member {OutputSetting} [SingleObjectQueryJobsParameter.prototype.output] * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [SingleObjectQueryJobsParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.SingleObjectQueryJobsParameter"; } /** * @function SingleObjectQueryJobsParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.datasetName = null; this.datasetQuery = null; this.geometryQuery = null; this.mode = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters){ this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function SingleObjectQueryJobsParameter.toObject * @param {Object} singleObjectQueryJobsParameter - 单对象空间查询分析任务参数。 * @param {Object} tempObj - 目标对象。 * @description 生成单对象空间查询分析任务对象。 */ static toObject(singleObjectQueryJobsParameter, tempObj) { for (var name in singleObjectQueryJobsParameter) { if (name === "datasetName") { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = singleObjectQueryJobsParameter[name]; continue; } if (name === "output"){ tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = singleObjectQueryJobsParameter[name]; continue; } tempObj['analyst'] = tempObj['analyst'] || {}; tempObj['analyst'][name] = singleObjectQueryJobsParameter[name]; if(name === 'mappingParameters'){ tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = singleObjectQueryJobsParameter[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/SingleObjectQueryJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SingleObjectQueryJobsService * @deprecatedclass SuperMap.SingleObjectQueryJobsService * @category iServer ProcessingService Query * @classdesc 单对象查询分析服务类 * @extends {ProcessingServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class SingleObjectQueryJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/query'); this.CLASS_NAME = 'SuperMap.SingleObjectQueryJobsService'; } /** *@override */ destroy() { super.destroy(); } /** * @function SingleObjectQueryJobsService.protitype.getQueryJobs * @description 获取单对象空间查询分析所有任务 */ getQueryJobs() { super.getJobs(this.url); } /** * @function KernelDensityJobsService.protitype.getQueryJob * @description 获取指定id的单对象空间查询分析服务 * @param {string} id - 指定要获取数据的id */ getQueryJob(id) { super.getJobs(Util.urlPathAppend(this.url, id)); } /** * @function SingleObjectQueryJobsService.protitype.addQueryJob * @description 新建单对象空间查询分析服务 * @param {SingleObjectQueryJobsParameter} params - 创建一个空间分析的请求参数。 * @param {number} seconds - 开始创建后,获取创建成功结果的时间间隔。 */ addQueryJob(params, seconds) { super.addJob(this.url, params, SingleObjectQueryJobsParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/StopQueryParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class StopQueryParameters * @deprecatedclass SuperMap.StopQueryParameters * @category iServer TrafficTransferAnalyst TransferStops * @classdesc 站点查询参数类。 * @param {Object} options - 参数。 * @param {string} options.keyWord - 站点名称关键字。 * @param {boolean} [options.returnPosition=false] - 是否返回站点坐标信息。 * @usage */ class StopQueryParameters { constructor(options) { options = options || {}; /** * @member {string} StopQueryParameters.prototype.keyWord * @description 站点名称关键字。 */ this.keyWord = null; /** * @member {boolean} [StopQueryParameters.prototype.returnPosition=false] * @description 是否返回站点坐标信息。 */ this.returnPosition = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.StopQueryParameters"; } /** * @function StopQueryParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { Util.reset(this); } } ;// CONCATENATED MODULE: ./src/common/iServer/StopQueryService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class StopQueryService * @deprecatedclass SuperMap.StopQueryService * @category iServer TrafficTransferAnalyst TransferStops * @classdesc 站点查询服务类。 * 返回结果通过该类支持的事件的监听函数参数获取 * @extends {CommonServiceBase} * @param {string} url - 服务地址。 * 例如:
"http://localhost:8090/iserver/services/traffictransferanalyst-sample/restjsr/traffictransferanalyst/Traffic-Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example 例如: * (start code) * var myService = new StopQueryService(url, {eventListeners: { * "processCompleted": StopQueryCompleted, * "processFailed": StopQueryError * } * }; * (end) * @usage * */ class StopQueryService extends CommonServiceBase { constructor(url, options) { super(url, options); options = options || {}; Util.extend(this, options); this.CLASS_NAME = "SuperMap.StopQueryService"; } /** *@override */ destroy() { super.destroy(); Util.reset(this); } /** * @function StopQueryService.prototype.processAsync * @description 负责将客户端的更新参数传递到服务端。 * @param {StopQueryParameters} params - 交通换乘参数。 */ processAsync(params) { if (!(params instanceof StopQueryParameters)) { return; } var me = this; me.url = Util.urlPathAppend(me.url, 'stops/keyword/' + params.keyWord); me.request({ method: "GET", params: {returnPosition: params.returnPosition}, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/SummaryAttributesJobsParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SummaryAttributesJobsParameter * @deprecatedclass SuperMap.SummaryAttributesJobsParameter * @category iServer ProcessingService SummaryAttributes * @classdesc 属性汇总分析任务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {string} options.groupField - 分组字段。 * @param {string} options.attributeField - 属性字段。 * @param {string} options.statisticModes - 统计模式。 * @param {OutputSetting} [options.output] -输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class SummaryAttributesJobsParameter { constructor(options) { if (!options) { return; } /** * @member {string} SummaryAttributesJobsParameter.prototype.datasetName * @description 汇总数据集名称。 */ this.datasetName = ""; /** * @member {string} SummaryAttributesJobsParameter.prototype.groupField * @description 分组字段。 */ this.groupField = ""; /** * @member {string} SummaryAttributesJobsParameter.prototype.attributeField * @description 属性字段。 */ this.attributeField = ""; /** * @member {string} SummaryAttributesJobsParameter.prototype.statisticModes * @description 属性汇总统计模式。 */ this.statisticModes = ""; /** * @member {OutputSetting} SummaryAttributesJobsParameter.prototype.output * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [SummaryAttributesJobsParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.SummaryAttributesJobsParameter"; } /** * @function SummaryAttributesJobsParameter.prototype.destroy * @description 释放资源,将资源的属性置空。 */ destroy() { this.datasetName = null; this.groupField = null; this.attributeField = null; this.statisticModes = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters){ this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function SummaryAttributesJobsParameter.toObject * @param {Object} SummaryAttributesJobsParameter - 属性汇总任务参数。 * @param {Object} tempObj - 目标对象。 * @description 生成属性汇总分析任务对象。 */ static toObject(SummaryAttributesJobsParameter, tempObj) { for (var name in SummaryAttributesJobsParameter) { if (name === "datasetName") { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = SummaryAttributesJobsParameter[name]; continue; } if (name === "output") { tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = SummaryAttributesJobsParameter[name]; continue; } tempObj['analyst'] = tempObj['analyst'] || {}; tempObj['analyst'][name] = SummaryAttributesJobsParameter[name]; if(name === 'mappingParameters'){ tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = SummaryAttributesJobsParameter[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/SummaryAttributesJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SummaryAttributesJobsService * @deprecatedclass SuperMap.SummaryAttributesJobsService * @category iServer ProcessingService SummaryAttributes * @classdesc 属性汇总分析服务类 * @extends {ProcessingServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class SummaryAttributesJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/summaryattributes'); this.CLASS_NAME = "SuperMap.SummaryAttributesJobsService"; } /** *@override */ destroy() { super.destroy(); } /** * @function SummaryAttributesJobsService.protitype.getSummaryAttributesJobs * @description 获取属性汇总分析所有任务 */ getSummaryAttributesJobs (){ super.getJobs(this.url); } /** * @function SummaryAttributesJobsService.protitype.getSummaryAttributesJob * @description 获取指定id的属性汇总分析服务 * @param {string} id - 指定要获取数据的id */ getSummaryAttributesJob(id) { super.getJobs(Util.urlPathAppend(this.url, id)); } /** * @function SummaryAttributesJobsService.protitype.addSummaryAttributesJob * @description 新建属性汇总分析服务 * @param {SummaryAttributesJobsParameter} params - 属性汇总分析任务参数类。 * @param {number} seconds - 创建成功结果的时间间隔。 */ addSummaryAttributesJob(params, seconds) { super.addJob(this.url, params, SummaryAttributesJobsParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/SummaryMeshJobParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SummaryMeshJobParameter * @deprecatedclass SuperMap.SummaryMeshJobParameter * @category iServer ProcessingService AggregatePoints * @classdesc 点聚合分析任务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} [options.query] - 分析范围(默认为全图范围)。 * @param {number} options.fields - 权重索引。 * @param {number} [options.resolution=100] - 分辨率。 * @param {StatisticAnalystMode} [options.statisticModes=StatisticAnalystMode.AVERAGE] - 分析模式。 * @param {number} [options.meshType=0] - 分析类型。 * @param {SummaryType} [options.type=SummaryType.SUMMARYMESH] - 聚合类型。 * @param {OutputSetting} [options.output] - 输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class SummaryMeshJobParameter { constructor(options) { if (!options) { return; } /** * @member {string} SummaryMeshJobParameter.prototype.datasetName * @description 数据集名。 */ this.datasetName = ""; /** * @member {string} SummaryMeshJobParameter.prototype.regionDataset * @description 聚合面数据集(聚合类型为多边形聚合时使用的参数)。 */ this.regionDataset = ""; /** * @member {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} SummaryMeshJobParameter.prototype.query * @description 分析范围(聚合类型为网格面聚合时使用的参数)。 */ this.query = ""; /** * @member {number} [SummaryMeshJobParameter.prototype.resolution=100] * @description 分辨率(聚合类型为网格面聚合时使用的参数)。 */ this.resolution = 100; /** * @member {number} [SummaryMeshJobParameter.prototype.meshType=0] * @description 网格面类型(聚合类型为网格面聚合时使用的参数),取值:0 或 1。 */ this.meshType = 0; /** * @member {StatisticAnalystMode} [SummaryMeshJobParameter.prototype.statisticModes=StatisticAnalystMode.AVERAGE] * @description 统计模式。 */ this.statisticModes = StatisticAnalystMode.AVERAGE; /** * @member {number} SummaryMeshJobParameter.prototype.fields * @description 权重字段。 */ this.fields = ""; /** * @member {SummaryType} [SummaryMeshJobParameter.prototype.type=SummaryType.SUMMARYMESH] * @description 聚合类型。 */ this.type = SummaryType.SUMMARYMESH; /** * @member {OutputSetting} [SummaryMeshJobParameter.prototype.output] * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [SummaryMeshJobParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.SummaryMeshJobParameter"; } /** * @function SummaryMeshJobParameter.prototype.destroy * @description 释放资源,将资源的属性置空。 */ destroy() { this.datasetName = null; this.query = null; this.resolution = null; this.statisticModes = null; this.meshType = null; this.fields = null; this.regionDataset = null; this.type = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters){ this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function SummaryMeshJobParameter.toObject * @param {Object} summaryMeshJobParameter - 点聚合分析任务参数。 * @param {Object} tempObj - 目标对象。 * @description 生成点聚合分析任务对象。 */ static toObject(summaryMeshJobParameter, tempObj) { for (var name in summaryMeshJobParameter) { if (name === "datasetName") { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = summaryMeshJobParameter[name]; continue; } if (name === "type") { tempObj['type'] = summaryMeshJobParameter[name]; continue; } if (name === "output") { tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = summaryMeshJobParameter[name]; continue; } if (summaryMeshJobParameter.type === 'SUMMARYMESH' && name !== 'regionDataset' || summaryMeshJobParameter.type === 'SUMMARYREGION' && !contains(['meshType', 'resolution', 'query'], name)) { tempObj['analyst'] = tempObj['analyst'] || {}; if (name === 'query' && summaryMeshJobParameter[name]) { tempObj['analyst'][name] = summaryMeshJobParameter[name].toBBOX(); } else { tempObj['analyst'][name] = summaryMeshJobParameter[name]; } if(name === 'mappingParameters'){ tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = summaryMeshJobParameter[name]; } } } function contains(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) { return true; } } return false; } } } ;// CONCATENATED MODULE: ./src/common/iServer/SummaryMeshJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SummaryMeshJobsService * @deprecatedclass SuperMap.SummaryMeshJobsService * @category iServer ProcessingService AggregatePoints * @classdesc 点聚合分析任务类。 * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {Events} options.events - 处理所有事件的对象。 * @param {Object} [options.eventListeners] - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {number} options.index - 服务地址在数组中的位置。 * @param {number} options.length - 服务地址数组长度。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class SummaryMeshJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/aggregatepoints'); this.CLASS_NAME = 'SuperMap.SummaryMeshJobsService'; } /** * @override */ destroy() { super.destroy(); } /** * @function SummaryMeshJobsService.prototype.getSummaryMeshJobs * @description 获取点聚合分析任务 */ getSummaryMeshJobs() { super.getJobs(this.url); } /** * @function SummaryMeshJobsService.prototype.getSummaryMeshJob * @description 获取指定ip的点聚合分析任务 * @param {string} id - 指定要获取数据的id */ getSummaryMeshJob(id) { super.getJobs(Util.urlPathAppend(this.url, id)); } /** * @function SummaryMeshJobsService.prototype.addSummaryMeshJob * @description 新建点聚合分析服务 * @param {SummaryMeshJobParameter} params - 创建一个空间分析的请求参数。 * @param {number} seconds - 开始创建后,获取创建成功结果的时间间隔。 */ addSummaryMeshJob(params, seconds) { super.addJob(this.url, params, SummaryMeshJobParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/SummaryRegionJobParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SummaryRegionJobParameter * @deprecatedclass SuperMap.SummaryRegionJobParameter * @category iServer ProcessingService SummaryRegion * @classdesc 区域汇总分析任务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} [options.query] - 分析范围(默认为全图范围)。 * @param {string} [options.standardFields] - 标准属性字段名称。 * @param {string} [options.weightedFields] - 权重字段名称。 * @param {StatisticAnalystMode} [options.standardStatisticModes] - 标准属性字段的统计模式。standardSummaryFields 为 true 时必填。 * @param {StatisticAnalystMode} [options.weightedStatisticModes] - 权重字段的统计模式。weightedSummaryFields 为 true 时必填。 * @param {boolean} [options.sumShape=true] - 是否统计长度或面积。 * @param {boolean} [options.standardSummaryFields=false] - 是否以标准属性字段统计。 * @param {boolean} [options.weightedSummaryFields=false] - 是否以权重字段统计。 * @param {number} [options.resolution=100] - 网格大小。 * @param {number} [options.meshType=0] - 网格面汇总类型。 * @param {AnalystSizeUnit} [options.meshSizeUnit=AnalystSizeUnit.METER] - 网格大小单位。 * @param {SummaryType} [options.type=SummaryType.SUMMARYMESH] - 汇总类型。 * @param {OutputSetting} [options.output] - 输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class SummaryRegionJobParameter { constructor(options) { if (!options) { return; } /** * @member {string} SummaryRegionJobParameter.prototype.datasetName * @description 数据集名。 */ this.datasetName = ""; /** * @member {string} SummaryRegionJobParameter.prototype.regionDataset * @description 汇总数据源(多边形汇总时用到的参数)。 */ this.regionDataset = ""; /** * @member {boolean} [SummaryRegionJobParameter.prototype.sumShape=true] * @description 是否统计长度或面积。 */ this.sumShape = true; /** * @member {(SuperMap.Bounds|L.Bounds|L.LatLngBounds|ol.extent|mapboxgl.LngLatBounds|GeoJSONObject)} SummaryRegionJobParameter.prototype.query * @description 分析范围。 */ this.query = ""; /** * @member {boolean} [SummaryRegionJobParameter.prototype.standardSummaryFields=false] * @description 是否以标准属字段统计。 */ this.standardSummaryFields = false; /** * @member {string} SummaryRegionJobParameter.prototype.standardFields * @description 标准属性字段名称。仅支持系统字段以外的整形、长整形、浮点型的字段的名称。standardSummaryFields 为 true 时必填。 */ this.standardFields = ""; /** * @member {StatisticAnalystMode} SummaryRegionJobParameter.prototype.standardStatisticModes * @description 标准属性字段的统计模式。standardSummaryFields 为 true 时必填。 */ this.standardStatisticModes = ""; /** * @member {boolean} [SummaryRegionJobParameter.prototype.weightedSummaryFields=false] * @description 是否以权重字段统计。 */ this.weightedSummaryFields = false; /** * @member {string} SummaryRegionJobParameter.prototype.weightedFields * @description 权重字段名称。仅支持系统字段以外的整形、长整形、浮点型的字段的名称。weightedSummaryFields 为 true 时必填。 */ this.weightedFields = ""; /** * @member {StatisticAnalystMode} SummaryRegionJobParameter.prototype.weightedStatisticModes * @description 以权重字段统计的统计模式。权重字段的统计模式。weightedSummaryFields 为 true 时必填。 */ this.weightedStatisticModes = ""; /** * @member {number} [SummaryRegionJobParameter.prototype.meshType=0] * @description 网格面汇总类型。 */ this.meshType = 0; /** * @member {number} [SummaryRegionJobParameter.prototype.resolution=100] * @description 网格大小。 */ this.resolution = 100; /** * @member {AnalystSizeUnit} [SummaryRegionJobParameter.prototype.meshSizeUnit=AnalystSizeUnit.METER] * @description 网格大小单位。 */ this.meshSizeUnit = AnalystSizeUnit.METER; /** * @member {SummaryType} [SummaryRegionJobParameter.prototype.type=SummaryType.SUMMARYMESH] * @description 汇总类型。 */ this.type = SummaryType.SUMMARYMESH; /** * @member {OutputSetting} SummaryRegionJobParameter.prototype.output * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [SummaryRegionJobParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.SummaryRegionJobParameter"; } /** * @function SummaryRegionJobParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.datasetName = null; this.sumShape = null; this.regionDataset = null; this.query = null; this.standardSummaryFields = null; this.standardFields = null; this.standardStatisticModes = null; this.weightedSummaryFields = null; this.weightedFields = null; this.weightedStatisticModes = null; this.meshType = null; this.resolution = null; this.meshSizeUnit = null; this.type = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters){ this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function SummaryRegionJobParameter.toObject * @param {Object} summaryRegionJobParameter - 矢量裁剪分析任务参数。 * @param {Object} tempObj - 目标对象。 * @description 生成区域汇总分析服务对象。 */ static toObject(summaryRegionJobParameter, tempObj) { for (var name in summaryRegionJobParameter) { if (name === "datasetName") { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = summaryRegionJobParameter[name]; continue; } if (name === "type") { tempObj['type'] = summaryRegionJobParameter[name]; continue; } if (name === "type") { tempObj['type'] = summaryRegionJobParameter[name]; continue; } if (name === "output") { tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = summaryRegionJobParameter[name]; continue; } if (summaryRegionJobParameter.type === "SUMMARYREGION" || summaryRegionJobParameter.type === "SUMMARYMESH" && name !== "regionDataset") { tempObj['analyst'] = tempObj['analyst'] || {}; if (name === 'query' && summaryRegionJobParameter[name]) { tempObj['analyst'][name] = summaryRegionJobParameter[name].toBBOX(); } else { tempObj['analyst'][name] = summaryRegionJobParameter[name]; } if(name === 'mappingParameters'){ tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = summaryRegionJobParameter[name]; } } } } } ;// CONCATENATED MODULE: ./src/common/iServer/SummaryRegionJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SummaryRegionJobsService * @deprecatedclass SuperMap.SummaryRegionJobsService * @category iServer ProcessingService SummaryRegion * @classdesc 区域汇总分析服务类 * @extends {ProcessingServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class SummaryRegionJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/summaryregion'); this.CLASS_NAME = 'SuperMap.SummaryRegionJobsService'; } /** *@override */ destroy() { super.destroy(); } /** * @function SummaryRegionJobsService.prototype.getSummaryRegionJobs * @description 获取区域汇总分析任务集合。 */ getSummaryRegionJobs() { super.getJobs(this.url); } /** * @function SummaryRegionJobsService.prototype.getSummaryRegionJob * @description 获取指定id的区域汇总分析任务。 * @param {string} id -要获取区域汇总分析任务的id */ getSummaryRegionJob(id) { super.getJobs(Util.urlPathAppend(this.url, id)); } /** * @function SummaryRegionJobsService.prototype.addSummaryRegionJob * @description 新建区域汇总任务。 * @param {SummaryRegionJobParameter} params - 区域汇总分析任务参数类。 * @param {number} seconds - 创建成功结果的时间间隔。 */ addSummaryRegionJob(params, seconds) { super.addJob(this.url, params, SummaryRegionJobParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/SupplyCenter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SupplyCenter * @deprecatedclass SuperMap.SupplyCenter * @category iServer NetworkAnalyst Location * @classdesc 资源供给中心类。在资源分配和选址分区分析两个功能中使用。 * @param {Object} options - 参数。 * @param {number} options.maxWeight - 最大耗费值。 * @param {number} options.nodeID - 结点 ID 号。资源供给中心必须是结点。 * @param {number} options.resourceValue - 能提供的最大服务量或商品数量。 * @param {SupplyCenterType} [options.type] - 资源供给中心点的类型常量。 * @usage */ class SupplyCenter { constructor(options) { /** * @member {number} SupplyCenter.prototype.maxWeight * @description 资源供给中心的最大耗费值。中心点最大阻值设置越小,表示中心点所提供的资源可影响范围越大。 * 最大阻力值是用来限制需求点到中心点的花费。 * 如果需求点(弧段或结点)到此中心的花费大于最大阻力值,则该需求点不属于该资源供给中心提供资源的范围。 */ this.maxWeight = null; /** * @member {number} SupplyCenter.prototype.nodeID * @description 资源供给中心点的结点 ID 号,资源供给中心必须是结点。 */ this.nodeID = null; /** * @member {number} SupplyCenter.prototype.resourceValue * @description 资源供给中心能提供的最大服务量或商品数量。例如资源中心为学校,资源中心资源量表示该学校能够接纳多少学生。 */ this.resourceValue = null; /** * @member {SupplyCenterType} [SupplyCenter.prototype.type] * @description 资源供给中心点的类型常量。资源供给中心点的类型包括非中心,固定中心和可选中心。 * 固定中心用于资源分配分析;固定中心和可选中心用于选址分析;非中心在两种网络分析时都不予考虑。 */ this.type = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.SupplyCenter"; } /** * @function SupplyCenter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.maxWeight = null; me.nodeID = null; me.resourceValue = null; me.type = null; } /** * @function SupplyCenter.fromJson * @description 将服务端 JSON 对象转换成当前客户端对象。 * @param {Object} jsonObject - 要转换的 JSON 对象。 * @returns {SupplyCenter} SupplyCenter 对象。 */ static fromJson(jsonObject) { if (!jsonObject) { return; } return new SupplyCenter({ maxWeight: jsonObject.maxWeight, nodeID: jsonObject.nodeID, resourceValue: jsonObject.resourceValue, type: jsonObject.type }); } } ;// CONCATENATED MODULE: ./src/common/iServer/SurfaceAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SurfaceAnalystService * @deprecatedclass SuperMap.SurfaceAnalystService * @category iServer SpatialAnalyst SurfaceAnalyst * @classdesc 表面分析服务类。 * 该类负责将客户设置的表面分析服务参数传递给服务端,并接收服务端返回的表面分析服务分析结果数据。 * 表面分析结果通过该类支持的事件的监听函数参数获取 * @param {string} url - 服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 例如: * (start code) * var mySurfaceAnalystService = new SurfaceAnalystService(url, { * eventListeners: { * "processCompleted": surfaceAnalysCompleted, * "processFailed": surfaceAnalysFailed * } * }); * (end) * @usage */ class SurfaceAnalystService extends SpatialAnalystBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.SurfaceAnalystService"; } /** * @function SurfaceAnalystService.prototype.destroy * @description 释放资源,将引用的资源属性置空。 */ destroy() { super.destroy(); } /** * @function SurfaceAnalystService.prototype.processAsync * @description 负责将客户端的表面分析服务参数传递到服务端。 * @param {SurfaceAnalystParameters} params - 表面分析提取操作参数类。 */ processAsync(params) { if (!(params instanceof SurfaceAnalystParameters)) { return; } var me = this, jsonParameters; jsonParameters = me.getJsonParameters(params); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function SurfaceAnalystService.prototype.getJsonParameters * @description 将参数转化为 JSON 字符串。 * @param {SurfaceAnalystParameters} params - 表面分析提取操作参数类。 * @returns {Object} 转化后的JSON字符串。 */ getJsonParameters(params) { var jsonParameters = ''; var parameterObject = {}; var me = this; if (params instanceof DatasetSurfaceAnalystParameters) { me.url = Util.urlPathAppend( me.url, 'datasets/' + params.dataset + '/' + params.surfaceAnalystMethod.toLowerCase() ); DatasetSurfaceAnalystParameters.toObject(params, parameterObject); jsonParameters = Util.toJSON(parameterObject); } else if (params instanceof GeometrySurfaceAnalystParameters) { me.url = Util.urlPathAppend(me.url, 'geometry/' + params.surfaceAnalystMethod.toLowerCase()); jsonParameters = Util.toJSON(params); } else { return; } this.returnContent = true; return jsonParameters; } dataFormat() { return [DataFormat.GEOJSON, DataFormat.ISERVER, DataFormat.FGB]; } } ;// CONCATENATED MODULE: ./src/common/iServer/TerrainCurvatureCalculationParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TerrainCurvatureCalculationParameters * @deprecatedclass SuperMap.TerrainCurvatureCalculationParameters * @category iServer SpatialAnalyst TerrainCalculation * @classdesc 地形曲率计算参数类。 * @param {Object} options - 参数。 * @param {string} options.dataset - 地形曲率计算数据源中数据集的名称。该名称用形如"数据集名称@数据源别名"形式来表示,例如:JingjinTerrain@Jingjin。 * @param {string} options.averageCurvatureName - 结果数据集:平均曲率数据集的名称。 * @param {string} options.profileCurvatureName - 结果数据集:剖面曲率数据集的名称。 * @param {string} options.planCurvatureName - 结果数据集:平面曲率数据集的名称。 * @param {number} [options.zFactor=1.0] - 指定的高程缩放系数。1.0 表示不缩放。 * @param {boolean} [options.deleteExistResultDataset=false] - 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 * @usage */ class TerrainCurvatureCalculationParameters { constructor(options) { if (!options) { return; } /** * @member {string} TerrainCurvatureCalculationParameters.prototype.dataset * @description 要用来做地形曲率计算数据源中数据集的名称。 * 该名称用形如"数据集名称@数据源别名"形式来表示,例如:JingjinTerrain@Jingjin。 * 注:地形曲率计算必须为栅格数据集。 */ this.dataset = null; /** * @member {number} [TerrainCurvatureCalculationParameters.prototype.zFactor=1.0] * @description 指定的高程缩放系数。1.0 表示不缩放。 * 该值是指在 DEM 栅格数据中,栅格值( Z 坐标,即高程值)相对于 X 和 Y 坐标的单位变换系数。 * 通常有 X,Y,Z 都参加的计算中,需要将高程值乘以一个高程缩放系数,使得三者单位一致。 * 例如,X、Y 方向上的单位是米,而 Z 方向的单位是英尺,由于 1 英尺等于 0.3048 米,则需要指定缩放系数为 0.3048。 */ this.zFactor = 1.0; /** * @member {string} TerrainCurvatureCalculationParameters.prototype.averageCurvatureName * @description 结果数据集:平均曲率数据集的名称。 */ this.averageCurvatureName = null; /** * @member {string} TerrainCurvatureCalculationParameters.prototype.profileCurvatureName * @description 结果数据集:剖面曲率数据集的名称。 */ this.profileCurvatureName = ""; /** * @member {string} TerrainCurvatureCalculationParameters.prototype.planCurvatureName * @description 结果数据集:平面曲率数据集的名称。 */ this.planCurvatureName = ""; /** * @member {boolean} [TerrainCurvatureCalculationParameters.prototype.deleteExistResultDataset=false] * @description 如果用户命名的结果数据集名称与已有的数据集重名,是否删除已有的数据集。 */ this.deleteExistResultDataset = false; Util.extend(this, options); this.CLASS_NAME = "SuperMap.TerrainCurvatureCalculationParameters"; } /** * @function TerrainCurvatureCalculationParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.dataset = null; me.zFactor = 1.0; me.averageCurvatureName = null; me.profileCurvatureName = null; me.planCurvatureName = null; me.deleteExistResultDataset = true; } /** * @function TerrainCurvatureCalculationParameters.toObject * @param {Object} derrainCurvatureCalculationParameters - 地形曲率计算参数。 * @param {Object} tempObj - 目标对象。 * @description 生成地形曲率计算对象。 */ static toObject(derrainCurvatureCalculationParameters, tempObj) { for (var name in derrainCurvatureCalculationParameters) { if (name !== "dataset") { tempObj[name] = derrainCurvatureCalculationParameters[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/TerrainCurvatureCalculationService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TerrainCurvatureCalculationService * @deprecatedclass SuperMap.TerrainCurvatureCalculationService * @category iServer SpatialAnalyst TerrainCalculation * @classdesc 地形曲率计算服务类。 * @extends {SpatialAnalystBase} * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {string} options.url - 服务的访问地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst 。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example 例如: * (start code) * var myTerrainCurvatureCalculationService = new TerrainCurvatureCalculationService(url); * myTerrainCurvatureCalculationService.on({ * "processCompleted": processCompleted, * "processFailed": processFailed * } * ); * (end) * @usage */ class TerrainCurvatureCalculationService extends SpatialAnalystBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.TerrainCurvatureCalculationService"; } /** *@override */ destroy() { super.destroy(); } /** * @function TerrainCurvatureCalculationService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {TerrainCurvatureCalculationParameters} parameter - 地形曲率计算参数类。 */ processAsync(parameter) { var me = this; var parameterObject = {}; if (parameter instanceof TerrainCurvatureCalculationParameters) { me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/terraincalculation/curvature'); } TerrainCurvatureCalculationParameters.toObject(parameter, parameterObject); var jsonParameters = Util.toJSON(parameterObject); me.url = Util.urlAppend(me.url, 'returnContent=true'); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeFlow.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeFlow * @deprecatedclass SuperMap.ThemeFlow * @private * @category iServer Map Theme * @classdesc 标签或符号流动显示和牵引线风格设置类。 * 通过该类可以设置专题图中符号是否流动显示、是否使用牵引线以及牵引线风格。 * @param {Object} options - 可选参数。 * @param {boolean} [options.flowEnabled=false] - 是否流动显示标签或符号。 * @param {boolean} [options.leaderLineDisplayed=false] - 是否显示标签或符号和它标注的对象之间的牵引线。 * @param {ServerStyle} [options.leaderLineStyle] - 标签或符号与其标注对象之间牵引线的风格。 * @usage */ class ThemeFlow { constructor(options) { /** * @member {boolean} [ThemeFlow.prototype.flowEnabled=false] * @description 是否流动显示标签或符号。
* 对于标签专题图而言,对于跨越比较大的区域和线条状的几何对象,在一个地图窗口中不能完全显示的情况下,如果其标签位置比较固定, * 在当前地图窗口中该对象的标签不可见,则需要通过平移地图来查看对象的标签信息。如果采用了流动显示的效果,在当前地图窗口中,对象即使是部分显示, * 其标签也会显示在当前地图窗口中。当平移地图时,对象的标签会随之移动,以保证在当前地图窗口中部分或全部显示的对象其标签都可见,从而可以方便地查看各要素的标签信息。 */ this.flowEnabled = false; /** * @member {boolean} [ThemeFlow.prototype.leaderLineDisplayed=false] * @description 是否显示标签或符号和它标注的对象之间的牵引线。false表示不显示标签或符号和它标注的对象之间的牵引线。
* 只有当 flowEnabled 为 true 时,牵引线才起作用。在当标签流动显示时,其位置不固定,由于牵引线始终指向要素的内点, * 因而通过牵引线显示功能可以找到流动的标签或符号实际对应的要素。或者渲染符号偏移它所指向的对象时,图与对象之间可以采用牵引线进行连接。 */ this.leaderLineDisplayed = false; /** * @member {ServerStyle} ThemeFlow.prototype.leaderLineStyle * @description 标签或符号与其标注对象之间牵引线的风格。 */ this.leaderLineStyle = new ServerStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeFlow"; } /** * @function ThemeFlow.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.flowEnabled = null; me.leaderLineDisplayed = null; if (me.leaderLineStyle) { me.leaderLineStyle.destroy(); me.leaderLineStyle = null; } } /** * @function ThemeFlow.fromObj * @description 从传入对象获取标签或符号流动显示和牵引线风格设置类。 * @param {Object} obj - 传入对象。 * @returns {ThemeFlow} ThemeFlow 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeFlow(); Util.copy(res, obj); res.leaderLineStyle = ServerStyle.fromJson(obj.leaderLineStyle); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGridRangeItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGridRangeItem * @deprecatedclass SuperMap.ThemeGridRangeItem * @category iServer Map Theme * @classdesc 栅格分段专题图子项类。在栅格分段专题图中,将栅格值按照某种分段模式被分成多个范围段。 * 本类用来设置每个范围段的分段起始值、终止值、名称和颜色等。每个分段所表示的范围为 [Start,End)。 * @param {Object} options - 参数。 * @param {ServerColor} options.color - 栅格分段专题图中每一个分段专题图子项的对应的颜色。 * @param {string} [options.caption] - 栅格分段专题图子项的标题。 * @param {number} [options.end=0] - 栅格分段专题图子项的终止值。 * @param {number} [options.start=0] - 栅格分段专题图子项的起始值。 * @param {boolean} [options.visible=true] - 栅格分段专题图子项是否可见。 * @usage */ class ThemeGridRangeItem { constructor(options) { /** * @member {string} [ThemeGridRangeItem.prototype.caption] * @description 栅格分段专题图子项的标题。 */ this.caption = null; /** * @member {ServerColor} ThemeGridRangeItem.prototype.color * @description 栅格分段专题图中每一个分段专题图子项的对应的颜色。 */ this.color = new ServerColor(); /** * @member {number} [ThemeGridRangeItem.prototype.end=0] * @description 栅格分段专题图子项的终止值,即该段专题值范围的最大值。 */ this.end = 0; /** * @member {number} [ThemeGridRangeItem.prototype.start=0] * @description 栅格分段专题图子项的起始值,即该段专题值范围的最小值。 */ this.start = 0; /** * @member {boolean} [ThemeGridRangeItem.prototype.visible=true] * @description 栅格分段专题图子项是否可见。 */ this.visible = true; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGridRangeItem"; } /** * @function ThemeGridRangeItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.caption = null; me.end = null; me.start = null; //需要验证是够存在destroy方法 if (me.color) { me.color.destroy(); me.color = null; } me.visible = null; } /** * @function ThemeGridRangeItem.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj = Util.copyAttributes(obj, this); if (obj.color) { if (obj.color.toServerJSONObject) { obj.color = obj.color.toServerJSONObject(); } } return obj; } /** * @function ThemeGridRangeItem.fromObj * @description 从传入对象获取栅格分段专题图子项类。 * @param {Object} obj - 传入对象。 * @returns {ThemeGridRangeItem} ThemeGridRangeItem 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeGridRangeItem(); Util.copy(res, obj); res.color = ServerColor.fromJson(obj.color); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGridRange.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGridRange * @deprecatedclass SuperMap.ThemeGridRange * @category iServer Map Theme * @classdesc 栅格分段专题图。栅格分段专题图,是将所有单元格的值按照某种分段方式分成多个范围段,值在同一个范围段中的单元格使用相同的颜色进行显示。一般用来反映连续分布现象的数量或程度特征。 * 比如某年的全国降水量分布图,将各气象站点的观测值经过内插之后生成的栅格数据进行分段显示。 * 该类类似于分段专题图类,不同点在于分段专题图的操作对象是矢量数据,而栅格分段专题图的操作对象是栅格数据。 * @extends {CommonTheme} * @param {Object} options - 参数。 * @param {Array.} options.items - 栅格分段专题图子项数组。 * @param {boolean} [options.reverseColor=false] - 是否对栅格分段专题图中分段的颜色风格进行反序显示。 * @param {RangeMode} [options.rangeMode=RangeMode.EQUALINTERVAL] - 分段专题图的分段模式。 * @param {number} [options.rangeParameter=0] - 分段参数。 * @param {ColorGradientType} [options.colorGradientType=ColorGradientType.YELLOW_RED] - 渐变颜色枚举类。 * @usage */ class ThemeGridRange extends Theme { constructor(options) { super("GRIDRANGE", options); /** * @member {Array.} ThemeGridRange.prototype.items * @description 栅格分段专题图子项数组。
* 在栅格分段专题图中,将栅格值按照某种分段模式被分成多个范围段。 * 本类用来设置每个栅格范围段的分段起始值、终止值、名称和颜色等。每个分段所表示的范围为 [Start,End)。 */ this.items = null; /** * @member {RangeMode} [ThemeGridRange.prototype.rangeMode=RangeMode.EQUALINTERVAL] * @description 分段专题图的分段模式。
* 在栅格分段专题图中,作为专题变量的字段或表达式的值按照某种分段方式被分成多个范围段。 * 目前 SuperMap 提供的分段方式包括:等距离分段法、平方根分段法、标准差分段法、对数分段法、等计数分段法和自定义距离法, * 显然这些分段方法根据一定的距离进行分段,因而范围分段专题图所基于的专题变量必须为数值型。 */ this.rangeMode = RangeMode.EQUALINTERVAL; /** * @member {number} [ThemeGridRange.prototype.rangeParameter=0] * @description 分段参数。
* 当分段模式为等距离分段法,平方根分段,对数分段法,等计数分段法其中一种模式时,该参数用于设置分段个数,必设;当分段模式为标准差分段法时, * 该参数不起作用;当分段模式为自定义距离时,该参数用于设置自定义距离。 */ this.rangeParameter = 0; /** * @member {ColorGradientType} [ThemeGridRange.prototype.colorGradientType=ColorGradientType.YELLOW_RED] * @description 渐变颜色枚举类。 * */ this.colorGradientType = ColorGradientType.YELLOW_RED; /** * @member {boolean} ThemeGridRange.prototype.reverseColor * @description 是否对栅格分段专题图中分段的颜色风格进行反序显示。 */ this.reverseColor = false; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGridRange"; } /** * @function ThemeGridRange.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.items) { if (me.items.length > 0) { for (var item in me.items) { me.items[item].destroy(); me.items[item] = null; } } me.items = null; } me.reverseColor = null; me.rangeMode = null; me.rangeParameter = null; me.colorGradientType = null; } /** * @function ThemeGridRange.fromObj * @description 从传入对象获取栅格分段专题图。 * @param {Object} obj - 传入对象。 * @returns {ThemeGridRange} ThemeGridRange 对象。 */ static fromObj(obj) { if (!obj) { return; } var res = new ThemeGridRange(); Util.copy(res, obj); var itemsR = obj.items; var len = itemsR ? itemsR.length : 0; res.items = []; for (var i = 0; i < len; i++) { res.items.push(ThemeGridRangeItem.fromObj(itemsR[i])); } return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGridUniqueItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGridUniqueItem * @deprecatedclass SuperMap.ThemeGridUniqueItem * @category iServer Map Theme * @classdesc 栅格单值专题图子项类。 * 栅格单值专题图是将值相同的单元格归为一类,每一类是一个专题图子项。 * @param {Object} options - 可选参数。 * @param {string} [options.caption] - 子项的名称。 * @param {ServerColor} [options.color] - 子项的显示颜色。 * @param {number} options.unique - 子项的专题值,即单元格的值,值相同的单元格位于一个子项内。 * @param {boolean} [options.visible=true] - 子项是否可见。 * @usage */ class ThemeGridUniqueItem { constructor(options) { /** * @member {string} [ThemeGridUniqueItem.prototype.caption] * @description 栅格单值专题图子项的名称。 */ this.caption = null; /** * @member {ServerColor} [ThemeGridUniqueItem.prototype.color] * @description 栅格单值专题图子项的显示颜色。 */ this.color = new ServerColor(); /** * @member {number} ThemeGridUniqueItem.prototype.unique * @description 栅格单值专题图子项的专题值,即单元格的值,值相同的单元格位于一个子项内。 */ this.unique = null; /** * @member {boolean} [ThemeGridUniqueItem.prototype.visible=true] * @description 栅格单值专题图子项是否可见。 */ this.visible = true; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGridUniqueItem"; } /** * @function ThemeGridUniqueItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.caption = null; me.unique = null; if (me.color) { me.color.destroy(); me.color = null; } me.visible = null; } /** * @function ThemeGridUniqueItem.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象。 */ toServerJSONObject() { var obj = {}; obj = Util.copyAttributes(obj, this); if (obj.color) { if (obj.color.toServerJSONObject) { obj.color = obj.color.toServerJSONObject(); } } return obj; } /** * @function ThemeGridUniqueItem.fromObj * @description 从传入对象获取栅格单值专题图子项类。 * @param {Object} obj - 传入对象。 * @returns {ThemeGridUniqueItem} ThemeGridUniqueItem 对象。 */ static fromObj(obj) { var res = new ThemeGridUniqueItem(); Util.copy(res, obj); res.color = ServerColor.fromJson(obj.color); return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeGridUnique.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeGridUnique * @deprecatedclass SuperMap.ThemeGridUnique * @category iServer Map Theme * @classdesc 栅格单值专题图类。栅格单值专题图是将单元格值相同的归为一类,为每一类设定一种颜色,从而用来区分不同的类别。 * 适用于离散栅格数据和部分连续栅格数据,对于单元格值各不相同的那些连续栅格数据,使用栅格单值专题图不具有任何意义。 * @extends {CommonTheme} * @param {Object} options - 参数。 * @param {Array.} options.items - 栅格单值专题图子项数组。 * @param {ServerColor} [options.defaultcolor] - 栅格单值专题图的默认颜色。 * @usage */ class ThemeGridUnique extends Theme { constructor(options) { super("GRIDUNIQUE", options); /** * @member {ServerColor} ThemeGridUnique.prototype.defaultcolor * @description 栅格单值专题图的默认颜色。 * 对于那些未在格网单值专题图子项之列的要素使用该颜色显示。 */ this.defaultcolor = new ServerColor(); /** * @member {Array.} ThemeGridUnique.prototype.items * @description 栅格单值专题图子项数组。 * 栅格单值专题图将值相同的单元格归为一类,每一类是一个专题图子项。 */ this.items = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeGridUnique"; } /** * @function ThemeGridUnique.prototype.destroy * @override */ destroy() { super.destroy(); var me = this; if (me.items) { if (me.items.length > 0) { for (var item in me.items) { me.items[item].destroy(); me.items[item] = null; } } me.items = null; } if (me.defaultcolor) { me.defaultcolor.destroy(); me.defaultcolor = null; } } /** * @function ThemeGridUnique.prototype.toServerJSONObject * @description 转换成对应的 JSON 格式对象。 * @returns {Object} 对应的 JSON 格式对象 */ toServerJSONObject() { var obj = {}; obj = Util.copyAttributes(obj, this); if (obj.defaultcolor) { if (obj.defaultcolor.toServerJSONObject) { obj.defaultcolor = obj.defaultcolor.toServerJSONObject(); } } if (obj.items) { var items = [], len = obj.items.length; for (var i = 0; i < len; i++) { items.push(obj.items[i].toServerJSONObject()); } obj.items = items; } return obj; } /** * @function ThemeGridUnique.fromObj * @description 从传入对象获取栅格单值专题图类。 * @param {Object} obj - 传入对象 * @returns {ThemeGridUnique} ThemeGridUnique 对象 */ static fromObj(obj) { var res = new ThemeGridUnique(); var uItems = obj.items; var len = uItems ? uItems.length : 0; Util.extend(res, obj); res.items = []; res.defaultcolor = ServerColor.fromJson(obj.defaultcolor); for (var i = 0; i < len; i++) { res.items.push(ThemeGridUniqueItem.fromObj(uItems[i])); } return res; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeLabelUniqueItem.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeLabelUniqueItem * @deprecatedclass SuperMap.ThemeLabelUniqueItem * @category iServer Map Theme * @classdesc 单值标签专题图的子项。标签专题图用专题值对点、线、面等对象做标注,值得注意的是,单值标签专题图允许用户通过 uniqueExpression * 字段指定用于单值的字段,同一值的标签具有相同的显示风格,其中每一个值就是一个专题图子项, * 每一个子项都具有其名称、风格、指定的单值、X 方向偏移量和 Y 方向偏移量。 * @param {Object} options - 参数。 * @param {string} options.unique - 子项的值,可以为数字、字符串等。 * @param {string} [options.caption] - 子项的名称。 * @param {number} [options.offsetX=0] - 标签在 X 方向偏移量。 * @param {number} [options.offsetY=0] - 标签在 Y 方向偏移量。 * @param {boolean} [options.visible=true] - 子项是否可见。 * @param {ServerTextStyle} [options.style] - 子项文本的显示风格。 * @usage */ class ThemeLabelUniqueItem { constructor(options) { /** * @member {string} [ThemeLabelUniqueItem.prototype.caption] * @description 标签专题子项的标题。 */ this.caption = null; /** * @member {string} ThemeLabelUniqueItem.prototype.unique * @description 单值专题图子项的值,可以为数字、字符串等。 */ this.unique = null; /** * @member {number} [ThemeLabelUniqueItem.prototype.offsetX=0] * @description 标签在 X 方向偏移量。 */ this.offsetX = 0; /** * @member {number} [ThemeLabelUniqueItem.prototype.offsetY=0] * @description 标签在 Y 方向偏移量。 */ this.offsetY = 0; /** * @member {boolean} [ThemeLabelUniqueItem.prototype.visible=true] * @description 标签专题图子项是否可见。如果标签专题图子项可见,则为 true,否则为 false。 */ this.visible = true; /** * @member {ServerTextStyle} ThemeLabelUniqueItem.prototype.style * @description 标签专题图子项文本的显示风格。各种风格的优先级从高到低为:
* uniformMixedStyle(标签文本的复合风格),ThemeLabelUniqueItem.style(单值子项的文本风格),uniformStyle(统一文本风格)。 */ this.style = new ServerTextStyle(); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeLabelUniqueItem"; } /** * @function ThemeLabelUniqueItem.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.unique = null; me.caption = null; me.offsetX = null; me.offsetY = null; if (me.style) { me.style.destroy(); me.style = null; } me.visible = null; } /** * @function ThemeLabelUniqueItem.fromObj * @description 从传入对象获取单值标签专题图的子项类。 * @param {Object} obj - 传入对象。 * @returns {ThemeLabelUniqueItem} ThemeLabelUniqueItem 对象。 */ static fromObj(obj) { if (!obj) { return; } var t = new ThemeLabelUniqueItem(); Util.copy(t, obj); return t; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeMemoryData.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeMemoryData * @deprecatedclass SuperMap.ThemeMemoryData * @category iServer Map Theme * @classdesc 专题图内存数据类。 * @param {Array} srcData - 原始值数组。 * @param {Array} targetData - 外部值数组。 * @usage */ class ThemeMemoryData { constructor(srcData, targetData) { /** * @member {Array} ThemeMemoryData.prototype.srcData * @description 原始值数组,该属性值将被 targetData 属性所指定的值替换掉,然后制作专题图,但数据库中的值并不会改变。 */ this.srcData = srcData; /** * @member {Array} ThemeMemoryData.prototype.targetData * @description 外部值数组,即用于制作专题图的内存数据,设定该属性值后,会将 srcData 属性所指定的原始值替换掉制作专题图,但数据库中的值并不会改变。 */ this.targetData = targetData; this.CLASS_NAME = "SuperMap.ThemeMemoryData"; } /** * @function ThemeMemoryData.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.srcData = null; me.targetData = null; } /** * @function ThemeMemoryData.prototype.toJSON * @description 将 ThemeMemoryData 对象转化为 JSON 字符串。 * @returns {string} 返回转换后的 JSON 字符串。 */ toJSON() { if (this.srcData && this.targetData) { var memoryDataStr = ""; var count = Math.min(this.srcData.length, this.targetData.length); for (var i = 0; i < count; i++) { memoryDataStr += "\'" + this.srcData[i] + "\':\'" + this.targetData[i] + "\',"; } //去除多余的逗号 if (i > 0) { memoryDataStr = memoryDataStr.substring(0, memoryDataStr.length - 1); } return "{" + memoryDataStr + "}"; } else { return null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeParameters * @deprecatedclass SuperMap.ThemeParameters * @category iServer Map Theme * @classdesc 专题图参数类。 * 该类存储了制作专题所需的参数,包括数据源、数据集名称和专题图对象。 * @param {Object} options - 参数。 * @param {Array.} options.datasetNames - 数据集数组。 * @param {Array.} options.dataSourceNames - 数据源数组。 * @param {Array.} [options.joinItems] - 专题图外部表的连接信息 JoinItem 数组。 * @param {Array.} options.themes - 专题图对象列表。 * @param {Array.} [options.displayFilters] - 专题图属性过滤条件。 * @param {Array.} [options.displayOrderBys] - 专题图对象生成符号叠加次序排序字段。 * @param {Object} [options.fieldValuesDisplayFilter] - 图层要素的显示和隐藏的过滤属性,其带有三个属性,分别是:values、fieldName、fieldValuesDisplayMode。 * @usage */ class ThemeParameters { constructor(options) { /** * @member {Array.} ThemeParameters.prototype.datasetNames * @description 要制作专题图的数据集数组。 */ this.datasetNames = null; /** * @member {Array.} ThemeParameters.prototype.dataSourceNames * @description 要制作专题图的数据集所在的数据源数组。 */ this.dataSourceNames = null; /** * @member {Array.} [ThemeParameters.prototype.joinItems] * @description 设置与外部表的连接信息 JoinItem 数组。 * 使用此属性可以制作与外部表连接的专题图。 */ this.joinItems = null; /** * @member {Array.} ThemeParameters.prototype.themes * @description 专题图对象列表。 * 该参数为实例化的各类专题图对象的集合。 */ this.themes = null; /** * @member {Array.} [ThemeParameters.prototype.displayFilters] * @description 专题图属性过滤条件。 */ this.displayFilters = null; /** * @member {Array.} [ThemeParameters.prototype.displayOrderBys] * @description 专题图对象生成符号叠加次序排序字段。 */ this.displayOrderBys = null; /** * @member {Object} [ThemeParameters.prototype.fieldValuesDisplayFilter] * @property {Array.} values - 待过滤的值。 * @property {string} fieldName - 待过滤的字段名称只支持数字类型的字段。 * @property {string} fieldValuesDisplayMode - 目前为 DISPLAY/DISABLE。当为 DISPLAY 时,表示只显示以上设置的相应属性值的要素,否则表示不显示以上设置的相应属性值的要素。 */ this.fieldValuesDisplayFilter = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThemeParameters"; } /** * @function ThemeParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.datasetNames = null; me.dataSourceNames = null; if (me.joinItems) { for (let i = 0, joinItems = me.joinItems, len = joinItems.length; i < len; i++) { joinItems[i].destroy(); } me.joinItems = null; } if (me.themes) { for (let i = 0, themes = me.themes, len = themes.length; i < len; i++) { themes[i].destroy(); } me.themes = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/ThemeService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeService * @deprecatedclass SuperMap.ThemeService * @category iServer Map Theme * @classdesc 专题图服务类。 * @extends {CommonServiceBase} * @example * var myThemeService = new ThemeService(url, { * eventListeners: { * "processCompleted": themeCompleted, * "processFailed": themeFailed * } * }); * @param {string} url - 服务地址。如:http://localhost:8090/iserver/services/map-world/rest/maps/World+Map 。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ThemeService_ThemeService extends CommonServiceBase { constructor(url, options) { super(url, options); if (options) { Util.extend(this, options); } this.url = Util.urlPathAppend(this.url, 'tempLayersSet'); this.CLASS_NAME = 'SuperMap.ThemeService'; } /** * @override */ destroy() { super.destroy(); } /** * @function ThemeService.prototype.processAsync * @description 负责将客户端的专题图参数传递到服务端。 * @param {ThemeParameters} params - 专题图参数类。 */ processAsync(params) { if (!(params instanceof ThemeParameters)) { return; } var me = this, jsonParameters = null; jsonParameters = me.getJsonParameters(params); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ThemeService.prototype.getJsonParameters * @description 将专题图参数参数转化为 JSON 字符串。 * @param {ThemeParameters} parameter - 专题图参数类。 * @returns {Object} 转化后的JSON字符串。 */ getJsonParameters(parameter) { var jsonParameters = "", themeObj = null, filters = null, orderBys = null, fieldValuesDisplayFilter; jsonParameters += "[{'type': 'UGC','subLayers': {'layers': ["; for (var i = 0; i < parameter.themes.length; i++) { themeObj = parameter.themes[i]; var jsonTheme = Util.toJSON(themeObj); jsonTheme = jsonTheme.slice(0, -1); jsonParameters += "{'theme': " + jsonTheme + "},'type': 'UGC','ugcLayerType': 'THEME',"; filters = parameter.displayFilters; if (filters && filters.length > 0) { if (filters.length === 1) { jsonParameters += "'displayFilter':\"" + filters[0] + "\","; } else { jsonParameters += "'displayFilter':\"" + filters[i] + "\","; } } orderBys = parameter.displayOrderBy; if (orderBys && orderBys.length > 0) { if (orderBys.length === 1) { jsonParameters += "'displayOrderBy':'" + orderBys[0] + "',"; } else { jsonParameters += "'displayOrderBy':'" + orderBys[i] + "',"; } } fieldValuesDisplayFilter = parameter.fieldValuesDisplayFilter; if (fieldValuesDisplayFilter) { jsonParameters += "'fieldValuesDisplayFilter':" + Util.toJSON(fieldValuesDisplayFilter) + ","; } if (parameter.joinItems && parameter.joinItems.length > 0 && parameter.joinItems[i]) { jsonParameters += "'joinItems':[" + Util.toJSON(parameter.joinItems[i]) + "],"; } if (parameter.datasetNames && parameter.dataSourceNames) { var datasetID = parameter.datasetNames[i] ? i : (parameter.datasetNames.length - 1); var dataSourceID = parameter.dataSourceNames[i] ? i : (parameter.dataSourceNames.length - 1); jsonParameters += "'datasetInfo': {'name': '" + parameter.datasetNames[datasetID] + "','dataSourceName': '" + parameter.dataSourceNames[dataSourceID] + "'}},"; } else { jsonParameters += "},"; } } //去除多余的逗号 if (parameter.themes && parameter.themes.length > 0) { jsonParameters = jsonParameters.substring(0, jsonParameters.length - 1); } jsonParameters += "]},"; var urlArray = this.url.split("/"); var jsonMapName = urlArray[urlArray.length - 2]; jsonParameters += "'name': '" + jsonMapName + "'}]"; return jsonParameters; } } ;// CONCATENATED MODULE: ./src/common/iServer/ThiessenAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThiessenAnalystService * @deprecatedclass SuperMap.ThiessenAnalystService * @category iServer SpatialAnalyst ThiessenPolygonAnalyst * @classdesc * 泰森多边形分析服务类 * 该类负责将客户设置的泰森多边形分析参数传递给服务端,并接收服务端返回的分析结果数据。 * 泰森多边形分析结果通过该类支持的事件的监听函数参数获取 * 泰森多边形分析的参数支持两种,当参数为 {@link DatasetThiessenAnalystParameters} 类型 * 时,执行数据集泰森多边形分析,当参数为 {@link GeometryThiessenAnalystParameters} 类型时, * 执行几何对象泰森多边形分析。 * @param {string} url - 服务地址。如 http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {SpatialAnalystBase} * @example 例如: * (start code) * var myThiessenAnalystService = new ThiessenAnalystService(url, { * eventListeners: { * "processCompleted": bufferCompleted, * "processFailed": bufferFailed * } * }); * (end) * @usage */ class ThiessenAnalystService extends SpatialAnalystBase { constructor(url, options) { super(url, options); /** * @member {string} ThiessenAnalystService.prototype.mode * @description 缓冲区分析类型 */ this.mode = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.ThiessenAnalystService"; } /** * @override */ destroy() { super.destroy(); this.mode = null; } /** * @function ThiessenAnalystService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {DatasetThiessenAnalystParameters|GeometryThiessenAnalystParameters} parameter - 泰森多边形分析参数基类。 */ processAsync(parameter) { var parameterObject = {}; var me = this; if (parameter instanceof DatasetThiessenAnalystParameters) { me.mode = "datasets"; me.url = Util.urlPathAppend(me.url, 'datasets/' + parameter.dataset + '/thiessenpolygon'); DatasetThiessenAnalystParameters.toObject(parameter, parameterObject); } else if (parameter instanceof GeometryThiessenAnalystParameters) { me.mode = "geometry"; me.url = Util.urlPathAppend(me.url, 'geometry/thiessenpolygon'); GeometryThiessenAnalystParameters.toObject(parameter, parameterObject); } var jsonParameters = Util.toJSON(parameterObject); this.returnContent = true; me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } dataFormat() { return [DataFormat.GEOJSON, DataFormat.ISERVER, DataFormat.FGB]; } } ;// CONCATENATED MODULE: ./src/common/iServer/GeometryBatchAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeometryBatchAnalystService * @deprecatedclass SuperMap.GeometryBatchAnalystService * @category iServer SpatialAnalyst BatchAnalyst * @classdesc 批量空间分析服务类 * @description 该类负责将客户设置的叠加分析参数传递给服务端,并接收服务端返回的叠加分析结果数据。 * 获取的结果数据包括 originResult 、result 两种, * 其中,originResult 为服务端返回的用 JSON 对象表示的量算结果数据,result 为服务端返回的量算结果数据。 * @extends {SpatialAnalystBase} * @param {string} url - 服务地址。如:http://localhost:8090/iserver/services/spatialanalyst-changchun/restjsr/spatialanalyst。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * var myOverlayAnalystService = new GeometryBatchAnalystService(url, { * eventListeners: { * "processCompleted": OverlayCompleted, * "processFailed": OverlayFailed * } * }); * @usage */ class GeometryBatchAnalystService extends SpatialAnalystBase { constructor(url, options) { super(url, options); if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.GeometryBatchAnalystService"; } /** * @function GeometryBatchAnalystService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 * @param {GeometryOverlayAnalystParameter} parameter - 批量几何对象叠加分析参数类 * */ processAsync(parameters) { var me = this; me.url = Util.urlPathAppend(me.url, 'geometry/batchanalyst'); me.url = Util.urlAppend(me.url, 'returnContent=true&ignoreAnalystParam=true'); var parameterObjects = me._processParams(parameters); var jsonParameters = Util.toJSON(parameterObjects); me.request({ method: "POST", data: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } _processParams(parameters) { var me = this; if (!Util.isArray(parameters)) { return; } var processParams = []; parameters.map(function (item) { processParams.push(me._toJSON(item)); return item; }); return processParams; } _toJSON(parameter) { var tempObj = {}; if(parameter.analystName ==="buffer"){ tempObj.analystName = "buffer"; tempObj.param = {}; //几何对象的批量空间分析, GeometryBufferAnalystParameters.toObject(parameter.param, tempObj.param); }else if(parameter.analystName ==="overlay"){ tempObj.analystName = "overlay"; tempObj.param = {}; GeometryOverlayAnalystParameters.toObject(parameter.param, tempObj.param); }else if(parameter.analystName ==="interpolationDensity"){ tempObj.analystName = "interpolationDensity"; tempObj.param = {}; InterpolationAnalystParameters.toObject(parameter.param, tempObj.param); }else if(parameter.analystName ==="interpolationidw"){ tempObj.analystName = "interpolationidw"; tempObj.param = {}; InterpolationAnalystParameters.toObject(parameter.param, tempObj.param); }else if(parameter.analystName ==="interpolationRBF"){ tempObj.analystName = "interpolationRBF"; tempObj.param = {}; InterpolationAnalystParameters.toObject(parameter.param, tempObj.param); }else if(parameter.analystName ==="interpolationKriging"){ tempObj.analystName = "interpolationKriging"; tempObj.param = {}; InterpolationAnalystParameters.toObject(parameter.param, tempObj.param); }else if(parameter.analystName ==="thiessenpolygon"){ tempObj.analystName = "thiessenpolygon"; tempObj.param = {}; GeometryThiessenAnalystParameters.toObject(parameter.param, tempObj.param); }else { //isoline; isoregion; calculatemeasure; routelocator 四种分析不需要再处理参数 return parameter; } return tempObj; } /** * @override */ destroy() { super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/iServer/TilesetsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TilesetsService * @deprecatedclass SuperMap.TilesetsService * @category iServer Map Tilesets * @classdesc 切片列表信息查询服务类;即查询切片地图服务的切片列表,返回切片集名称、地图切片元数据信息、切片版本集信息。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{服务名}/rest/maps/map; * 例如: "http://localhost:8090/iserver/services/test/rest/maps/tianlocal"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有 processCompleted 属性可传入处理完成后的回调函数。processFailed 属性传入处理失败后的回调函数。 * @param {DataFormat} [options.format=DataFormat.GEOJSON] - 查询结果返回格式,目前支持 iServerJSON 和 GeoJSON 两种格式。参数格式为 "ISERVER","GEOJSON"。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class TilesetsService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.TilesetsService"; } /** * @override */ destroy() { super.destroy(); } /** * @function TilesetsService.prototype.processAsync * @description 负责将客户端的查询参数传递到服务端。 */ processAsync() { if (!this.url) { return; } var me = this; me.url = Util.urlPathAppend(me.url, 'tilesets'); me.request({ method: "GET", scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/TopologyValidatorJobsParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TopologyValidatorJobsParameter * @deprecatedclass SuperMap.TopologyValidatorJobsParameter * @category iServer ProcessingService TopologyValidator * @classdesc 拓扑检查分析任务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {string} options.datasetTopology -检查对象所在的数据集名称。 * @param {TopologyValidatorRule} [options.rule=TopologyValidatorRule.REGIONNOOVERLAP] - 拓扑检查规则。 * @param {string} [options.tolerance] - 容限。 * @param {OutputSetting} [options.output] - 输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class TopologyValidatorJobsParameter { constructor(options) { if (!options) { return; } /** * @member {string} TopologyValidatorJobsParameter.prototype.datasetName * @description 数据集名。 */ this.datasetName = ""; /** * @member {string} TopologyValidatorJobsParameter.prototype.datasetTopology * @description 拓扑检查对象所在的数据集名称。 */ this.datasetTopology = ""; /** * @member {string} [TopologyValidatorJobsParameter.prototype.tolerance] * @description 容限,指定的拓扑错误检查时使用的容限。 */ this.tolerance = ""; /** * @member {TopologyValidatorRule} [TopologyValidatorJobsParameter.prototype.rule=TopologyValidatorRule.REGIONNOOVERLAP] * @description 拓扑检查模式。 */ this.rule = TopologyValidatorRule.REGIONNOOVERLAP; /** * @member {OutputSetting} [TopologyValidatorJobsParameter.prototype.output] * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [TopologyValidatorJobsParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.TopologyValidatorJobsParameter"; } /** * @function TopologyValidatorJobsParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.datasetName = null; this.datasetTopology = null; this.tolerance = null; this.rule = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters) { this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function TopologyValidatorJobsParameter.toObject * @param {Object} TopologyValidatorJobsParameter -拓扑检查分析任务参数。 * @param {Object} tempObj - 目标对象。 * @description 生成拓扑检查分析任务对象。 */ static toObject(TopologyValidatorJobsParameter, tempObj) { for (var name in TopologyValidatorJobsParameter) { if (name === "datasetName") { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = TopologyValidatorJobsParameter[name]; continue; } if (name === "output") { tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = TopologyValidatorJobsParameter[name]; continue; } tempObj['analyst'] = tempObj['analyst'] || {}; tempObj['analyst'][name] = TopologyValidatorJobsParameter[name]; if(name === 'mappingParameters'){ tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = TopologyValidatorJobsParameter[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/TopologyValidatorJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TopologyValidatorJobsService * @deprecatedclass SuperMap.TopologyValidatorJobsService * @category iServer ProcessingService TopologyValidator * @classdesc 拓扑检查分析服务类 * @extends {ProcessingServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class TopologyValidatorJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/topologyvalidator'); this.CLASS_NAME = "SuperMap.TopologyValidatorJobsService"; } /** *@override */ destroy() { super.destroy(); } /** * @function TopologyValidatorJobsService.protitype.getTopologyValidatorJobs * @description 获取拓扑检查分析所有任务 */ getTopologyValidatorJobs() { super.getJobs(this.url); } /** * @function TopologyValidatorJobsService.protitype.getTopologyValidatorJob * @description 获取指定id的拓扑检查分析服务 * @param {string} id - 指定要获取数据的id */ getTopologyValidatorJob(id) { super.getJobs( Util.urlPathAppend(this.url, id)); } /** * @function TopologyValidatorJobsService.protitype.addTopologyValidatorJob * @description 新建拓扑检查分析服务 * @param {TopologyValidatorJobsParameter} params - 拓扑检查分析任务参数类。 * @param {number} seconds -创建成功结果的时间间隔。 */ addTopologyValidatorJob(params, seconds) { super.addJob(this.url, params, TopologyValidatorJobsParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/TransferLine.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TransferLine * @deprecatedclass SuperMap.TransferLine * @category iServer TrafficTransferAnalyst TransferPath * @classdesc 换乘路线信息类。 * @param {Object} options - 参数。 * @param {number} options.lineID - 乘车路线 ID。 * @param {string} options.lineName - 乘车路线名称。 * @param {string} options.lineAliasName - 乘车路线别名。 * @param {number} options.startStopIndex - 上车站点在本公交路线中的索引。 * @param {string} options.startStopName - 上车站点名称。 * @param {string} options.startStopAliasName - 上车站点别名。 * @param {number} options.endStopIndex - 下车站点在本公交路线中的索引。 * @param {string} options.endStopName - 下车站点名称。 * @param {string} options.endStopAliasName - 下车站点别名。 * @usage */ class TransferLine { constructor(options) { options = options || {}; /** * @member {number} TransferLine.prototype.lineID * @description 乘车路线 ID。 */ this.lineID = null; /** * @member {string} TransferLine.prototype.lineName * @description 乘车路线名称。 */ this.lineName = null; /** * @member {string} TransferLine.prototype.lineAliasName * @description 乘车路线别名。 */ this.lineAliasName = null; /** * @member {number} TransferLine.prototype.startStopIndex * @description 上车站点在本公交路线中的索引。 */ this.startStopIndex = null; /** * @member {string} TransferLine.prototype.startStopName * @description 上车站点名称。 */ this.startStopName = null; /** * @member {string} TransferLine.prototype.startStopAliasName * @description 上车站点别名。 */ this.startStopAliasName = null; /** * @member {number} TransferLine.prototype.endStopIndex * @description 下车站点在本公交路线中的索引。 */ this.endStopIndex = null; /** * @member {string} TransferLine.prototype.endStopName * @description 下车站点名称。 */ this.endStopName = null; /** * @member {string} TransferLine.prototype.endStopAliasName * @description 下车站点别名。 */ this.endStopAliasName = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.TransferLine"; } /** * @function TransferLine.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { Util.reset(this); } /** * @function TransferLine.fromJson * @description 将返回结果转化为 {@link TransferLine} 对象。 * @param {Object} jsonObject - 新的返回结果。 * @returns {TransferLine} 转化后的 {@link TransferLine} 对象。 */ static fromJson(jsonObject) { if (!jsonObject) { return; } return new TransferLine({ lineID: jsonObject['lineID'], lineName: jsonObject['lineName'], lineAliasName: jsonObject['lineAliasName'], startStopIndex: jsonObject['startStopIndex'], startStopName: jsonObject['startStopName'], startStopAliasName: jsonObject['startStopAliasName'], endStopIndex: jsonObject['endStopIndex'], endStopName: jsonObject['endStopName'], endStopAliasName: jsonObject['endStopAliasName'] }); } } ;// CONCATENATED MODULE: ./src/common/iServer/TransferPathParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TransferPathParameters * @deprecatedclass SuperMap.TransferPathParameters * @category iServer TrafficTransferAnalyst TransferPath * @classdesc 交通换乘线路查询参数类。 * @param {Object} options - 参数。 * @param {Array.} options.transferLines - 本换乘分段内可乘车的路线集合。 * @param {Array.|number>} options.points - 两种查询方式:按照公交站点的起止 ID 进行查询和按照起止点的坐标进行查询。 * @usage */ class TransferPathParameters { constructor(options) { options = options || {}; /** * @member {Array.} TransferPathParameters.prototype.transferLines * @description 本换乘分段内可乘车的路线集合,通过交通换乘方案查询得到。 */ this.transferLines = null; /** * @member {Array.|number>} TransferPathParameters.prototype.points * @description 两种查询方式:
* 1. 按照公交站点的起止ID进行查询,则 points 参数的类型为 int[],形如:[起点ID、终点ID],公交站点的 ID 对应服务提供者配置中的站点 ID 字段; * 2. 按照起止点的坐标进行查询,则 points 参数的类型为 Point2D[],形如:[{"x":44,"y":39},{"x":45,"y":40}]。 */ this.points = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.TransferPathParameters"; } /** * @function TransferPathParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { Util.reset(this); } /** * @function TransferPathParameters.toJson * @description 将 {@link TransferPathParameters} 对象参数转换为 JSON 字符串。 * @param {TransferPathParameters} params - 交通换乘参数。 * @returns {string} 转化后的 JSON 字符串。 */ static toJson(params) { if (params) { return Util.toJSON(params); } } } ;// CONCATENATED MODULE: ./src/common/iServer/TransferPathService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TransferPathService * @deprecatedclass SuperMap.TransferPathService * @category iServer TrafficTransferAnalyst TransferPath * @classdesc 交通换乘线路查询服务类,根据交通换乘分析结果(TransferSolutionResult),获取某一条乘车路线的详细信息。 * 返回结果通过该类支持的事件的监听函数参数获取 * @extends {CommonServiceBase} * @example 例如: * var myService = new TransferPathService(url, {eventListeners: { * "processCompleted": TrafficTransferCompleted, * "processFailed": TrafficTransferError * } * }; * @param {string} url - 服务地址。 * 例如:
"http://localhost:8090/iserver/services/traffictransferanalyst-sample/restjsr/traffictransferanalyst/Traffic-Changchun"。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class TransferPathService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.TransferPathService"; } /** * @override */ destroy() { super.destroy(); } /** * @function TransferPathService.prototype.processAsync * @description 负责将客户端的更新参数传递到服务端。 * @param {TransferPathParameters} params - 交通换乘参数。 */ processAsync(params) { if (!(params instanceof TransferPathParameters)) { return; } var me = this, method = "GET", jsonParameters; me.url = Util.urlPathAppend(me.url, 'path'); jsonParameters = { points: Util.toJSON(params.points), transferLines: Util.toJSON(params['transferLines']) }; me.request({ method: method, params: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/TransferSolutionParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TransferSolutionParameters * @deprecatedclass SuperMap.TransferSolutionParameters * @category iServer TrafficTransferAnalyst TransferSolutions * @classdesc 交通换乘方案查询参数类。 * @param {Object} options - 参数。 * @param {Array.|number>} options.points - 两种查询方式:按照公交站点的起止ID进行查询和按照起止点的坐标进行查询。 * @param {number} [options.solutionCount=6] - 乘车方案的数量。 * @param {TransferTactic} [options.transferTactic=TransferTactic.LESS_TIME] - 交通换乘策略类型,包括时间最短、距离最短、最少换乘、最少步行四种选择。 * @param {TransferPreference} [options.transferPreference=TransferPreference.NONE] - 乘车偏好枚举。 * @param {number} [options.walkingRatio=10] - 步行与公交的消耗权重比。 * @param {Array.} [options.evadeLines] - 避让路线的 ID。 * @param {Array.} [options.evadeStops] - 避让站点的 ID。 * @param {Array.} [options.priorLines] - 优先路线的 ID。 * @param {Array.} [options.priorStops] - 优先站点的 ID。 * @param {string} [options.travelTime] - 出行的时间。 * @usage */ class TransferSolutionParameters { constructor(options) { options = options || {}; /** * @member {number} [TransferSolutionParameters.prototype.solutionCount=6] * @description 乘车方案的数量。 */ this.solutionCount = 6; /** * @member {TransferPreference} [TransferSolutionParameters.prototype.transferPreference=TransferPreference.NONE] * @description 乘车偏好枚举。 */ this.transferPreference = TransferPreference.NONE; /** * @member {TransferTactic} [TransferSolutionParameters.prototype.transferTactic=TransferTactic|TransferTactic.LESS_TIME] * @description 交通换乘策略类型,包括时间最短、距离最短、最少换乘、最少步行四种选择。 */ this.transferTactic = TransferTactic.LESS_TIME; /** * @member {number} [TransferSolutionParameters.prototype.walkingRatio=10] * @description 步行与公交的消耗权重比。此值越大,则步行因素对于方案选择的影响越大。例如:
* 例如现在有两种换乘方案(在仅考虑消耗因素的情况下):
* 方案1:坐车 10 公里,走路 1 公里;
* 方案2:坐车 15 公里,走路 0.5 公里;
* 1. 假设权重比为 15:
* •方案 1 的总消耗为:10 + 1*15 = 25
* •方案 2 的总消耗为:15 + 0.5*15 = 22.5
* 此时方案 2 消耗更低。
* 2. 假设权重比为2:
* •方案 1 的总消耗为:10+1*2 = 12
* •方案 2 的总消耗为:15+0.5*2 = 17
* 此时方案 1 消耗更低。
*/ this.walkingRatio = null; /** * @member {Array.|number>} TransferSolutionParameters.prototype.points * @description 两种查询方式:
* 1. 按照公交站点的起止 ID 进行查询,则 points 参数的类型为 int[],形如:[起点 ID、终点 ID],公交站点的 ID 对应服务提供者配置中的站点 ID 字段; * 2. 按照起止点的坐标进行查询,则 points 参数的类型为 Point2D[],形如:[{"x":44,"y":39},{"x":45,"y":40}]。 */ this.points = false; /** * @member {Array.} [TransferSolutionParameters.prototype.evadeLinesnull] * @description 避让路线 ID。 * */ this.evadeLines = null; /** * @member {Array.} [TransferSolutionParameters.prototype.evadeStops=TransferLine] * @description 避让站点 ID。 * */ this.evadeStops = null; /** * @member {Array.} [TransferSolutionParameters.prototype.priorLines] * @description 优先路线 ID。 * */ this.priorLines = null; /** * @member {Array.} [TransferSolutionParameters.prototype.priorStops] * @description 优先站点 ID。 * */ this.priorStops = null; /** * @member {string} TransferSolutionParameters.prototype.travelTime * @description 出行的时间;格式是:"小时:分钟",如:"08:30"。如果设置了该参数,在分析时,则会考虑线路的首末班车时间的限制,即在返回的结果中会提示公交的首末班发车时间。 */ this.travelTime = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.TransferSolutionParameters"; } /** * @function TransferSolutionParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { Util.reset(this); } /** * @function TransferSolutionParameters.toJsonParameters * @description 将 {@link TransferSolutionParameters} 对象参数转换为 JSON 字符串。 * @param {TransferSolutionParameters} params - 交通换乘参数。 * @returns {string} 转化后的 JSON 字符串。 */ static toJson(params) { if (params) { return Util.toJSON(params); } } } ;// CONCATENATED MODULE: ./src/common/iServer/TransferSolutionService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TransferSolutionService * @deprecatedclass SuperMap.TransferSolutionService * @category iServer TrafficTransferAnalyst TransferSolutions * @classdesc 交通换乘方案查询服务类。 * 返回结果通过该类支持的事件的监听函数参数获取。 * @param {string} url - 服务地址。 * 例如:
"http://localhost:8090/iserver/services/traffictransferanalyst-sample/restjsr/traffictransferanalyst/Traffic-Changchun"。 * @param {Object} options - 参数。
* @param {Object} options.eventListeners - 需要被注册的监听器对象。
* @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {CommonServiceBase} * @example 例如: * (start code) * var myService = new TransferSolutionService(url, {eventListeners: { * "processCompleted": trafficTransferCompleted, * "processFailed": trafficTransferError * } * }; * (end) * @usage */ class TransferSolutionService extends CommonServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.TransferSolutionService"; } /** * @override */ destroy() { super.destroy(); } /** * @function TransferSolutionService.prototype.processAsync * @description 负责将客户端的更新参数传递到服务端。 * @param {TransferSolutionParameters} params - 交通换乘参数。 */ processAsync(params) { if (!(params instanceof TransferSolutionParameters)) { return; } var me = this, method = "GET", jsonParameters; me.url = Util.urlPathAppend(me.url, 'solutions'); jsonParameters = { points: Util.toJSON(params.points), walkingRatio: params['walkingRatio'], transferTactic: params['transferTactic'], solutionCount: params['solutionCount'], transferPreference: params["transferPreference"] }; if (params.evadeLines) { jsonParameters["evadeLines"] = Util.toJSON(params.evadeLines); } if (params.evadeStops) { jsonParameters["evadeStops"] = Util.toJSON(params.evadeStops); } if (params.priorLines) { jsonParameters["priorLines"] = Util.toJSON(params.priorLines); } if (params.priorStops) { jsonParameters["priorStops"] = Util.toJSON(params.priorStops); } if (params.travelTime) { jsonParameters["travelTime"] = params.travelTime; } me.request({ method: method, params: jsonParameters, scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/UpdateEdgeWeightParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UpdateEdgeWeightParameters * @deprecatedclass SuperMap.UpdateEdgeWeightParameters * @category iServer NetworkAnalyst EdgeWeight * @classdesc 边的耗费权重更新服务参数类。 * @param {Object} options - 参数。 * @param {string} options.edgeId - 所在边的 ID。 * @param {string} options.fromNodeId - 起始转向点的 ID。 * @param {string} options.toNodeId - 终止转向点的 ID。 * @param {string} options.weightField - 边的耗费字段。 * @param {string} options.edgeWeight - 耗费权重。 * @usage */ class UpdateEdgeWeightParameters { constructor(options) { if (!options) { return; } /** * @member {string} UpdateEdgeWeightParameters.prototype.edgeId * @description 所在边的 ID。 */ this.edgeId = ""; /** * @member {string} UpdateEdgeWeightParameters.prototype.fromNodeId * @description 起始转向点的 ID。 */ this.fromNodeId = ""; /** * @member {string} UpdateEdgeWeightParameters.prototype.toNodeId * @description 终止转向点的 ID。 */ this.toNodeId = ""; /** * @member {string} UpdateEdgeWeightParameters.prototype.weightField * @description 边的耗费字段。 */ this.weightField = ""; /** * @member {string} UpdateEdgeWeightParameters.prototype.edgeWeight * @description 耗费权重。 */ this.edgeWeight = ""; Util.extend(this, options); this.CLASS_NAME = "SuperMap.UpdateEdgeWeightParameters"; } /** * @function UpdateEdgeWeightParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.edgeId = null; this.fromNodeId = null; this.toNodeId = null; this.weightField = null; this.edgeWeight = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/CreateDatasetParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class CreateDatasetParameters * @deprecatedclass SuperMap.CreateDatasetParameters * @category iServer Data Dataset * @classdesc 数据集创建参数类。 * @param {Object} options - 参数。 * @param {string} options.datasourceName - 数据源名称,此为必选参数。 * @param {string} options.datasetName - 数据集名称,此为必选参数。 * @param {string} options.datasetType - 数据集类型。目前支持创建的数据集类型有:点、线、面、文本、复合(CAD)和属性数据集。 * @usage */ class CreateDatasetParameters { constructor(options) { if (!options) { return; } /** * @member {string} CreateDatasetParameters.prototype.datasourceName * @description 数据源名称,此为必选参数。 */ this.datasourceName = null; /** * @member {string} CreateDatasetParameters.prototype.datasetName * @description 数据集名称,此为必选参数。 */ this.datasetName = null; /** * @member {string} CreateDatasetParameters.prototype.datasetType * @description 数据集类型。目前支持创建的数据集类型有:点、线、面、文本、复合(CAD)和属性数据集。 */ this.datasetType = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.CreateDatasetParameters"; } /** * @function CreateDatasetParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.datasourceName = null; me.datasetName = null; me.datasetType = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/UpdateEdgeWeightService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UpdateEdgeWeightService * @deprecatedclass SuperMap.UpdateEdgeWeightService * @category iServer NetworkAnalyst EdgeWeight * @classdesc 更新边的边的耗费权重服务 * @extends {NetworkAnalystServiceBase} * @example *(start code) * var updateEdgeWeightService = new UpdateEdgeWeightService(url, { * eventListeners: { * "processCompleted": UpdateEdgeWeightCompleted, * "processFailed": UpdateEdgeWeightError * } * }); * (end) * @param {string} url - 服务地址。如:http://localhost:8090/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun 。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class UpdateEdgeWeightService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.UpdateEdgeWeightService"; } /** * @override */ destroy() { super.destroy(); } /** * @function UpdateEdgeWeightService.prototype.processAsync * @description 开始异步执行边的边的耗费权重的更新 * @param {UpdateEdgeWeightParameters} params - 边的耗费权重更新服务参数类 * @example * (code) * var updateEdgeWeightParam=new SuperMapUpdateEdgeWeightParameters({ * edgeId:"20", * fromNodeId:"26", * toNodeId:"109", * weightField:"time", * edgeWeight:"25" * }); * updateEdgeWeightService.processAsync(updateEdgeWeightParam); * (end) */ processAsync(params) { if (!(params instanceof UpdateEdgeWeightParameters)) { return; } var me = this; var paramStr = me.parse(params); me.url = Util.urlPathAppend(me.url, paramStr); var data = params.edgeWeight ? params.edgeWeight : null; me.request({ method: "PUT", scope: me, data: data, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function UpdateEdgeWeightService.prototype.parse * @description 将更新服务参数解析为用‘/’做分隔的字符串 */ parse(params) { if (!params) { return; } var paramStr = ""; for (var attr in params) { if (params[attr] === "" || params[attr] === "edgeWeight") { continue; } switch (attr) { case "edgeId": paramStr += "/edgeweight/" + params[attr]; break; case "fromNodeId": paramStr += "/fromnode/" + params[attr]; break; case "toNodeId": paramStr += "/tonode/" + params[attr]; break; case "weightField": paramStr += "/weightfield/" + params[attr]; break; default : break; } } return paramStr; } } ;// CONCATENATED MODULE: ./src/common/iServer/UpdateTurnNodeWeightParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UpdateTurnNodeWeightParameters * @deprecatedclass SuperMap.UpdateTurnNodeWeightParameters * @category iServer NetworkAnalyst TurnNodeWeight * @classdesc 转向耗费权重更新服务参数类。 * @param {Object} options - 参数。 * @param {string} options.nodeId - 转向结点的 ID。 * @param {string} options.fromEdgeId - 起始边的 ID。 * @param {string} options.toEdgeId - 终止边的 ID。 * @param {string} options.weightField - 转向结点的耗费字段。 * @param {string} options.turnNodeWeight - 耗费权重。 * @usage */ class UpdateTurnNodeWeightParameters { constructor(options) { if (!options) { return; } /** * @member {string} UpdateTurnNodeWeightParameters.prototype.nodeId * @description 转向结点的 ID。 */ this.nodeId = ""; /** * @member {string} UpdateTurnNodeWeightParameters.prototype.fromEdgeId * @description 起始边的 ID。 */ this.fromEdgeId = ""; /** * @member {string} UpdateTurnNodeWeightParameters.prototype.toEdgeId * @description 终止边的 ID。 */ this.toEdgeId = ""; /** * @member {string} UpdateTurnNodeWeightParameters.prototype.weightField * @description 转向结点的耗费字段。 */ this.weightField = ""; /** * @member {string} UpdateTurnNodeWeightParameters.prototype.turnNodeWeight * @description 耗费权重。 */ this.turnNodeWeight = ""; Util.extend(this, options); this.CLASS_NAME = "SuperMap.UpdateTurnNodeWeightParameters"; } /** * @function UpdateTurnNodeWeightParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.nodeId = null; this.fromEdgeId = null; this.toEdgeId = null; this.weightField = null; this.turnNodeWeight = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/UpdateTurnNodeWeightService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UpdateTurnNodeWeightService * @deprecatedclass SuperMap.UpdateTurnNodeWeightService * @category iServer NetworkAnalyst TurnNodeWeight * @classdesc 转向耗费权重更新服务类 * @extends {NetworkAnalystServiceBase} * @example * var UpdateTurnNodeWeightService = new UpdateTurnNodeWeightService(url, { * eventListeners: { * "processCompleted": UpdateTurnNodeWeightCompleted, * "processFailed": UpdateTurnNodeWeightError * } * }); * @param {string} url - 服务地址。如: * http://localhost:8090/iserver/services/transportationanalyst-sample/rest/networkanalyst/RoadNet@Changchun 。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 需要被注册的监听器对象。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class UpdateTurnNodeWeightService extends NetworkAnalystServiceBase { constructor(url, options) { super(url, options); this.CLASS_NAME = "SuperMap.UpdateTurnNodeWeightService"; } /** * @override */ destroy() { super.destroy(); } /** * @function UpdateTurnNodeWeightService.prototype.processAsync * @description 开始异步执行转向耗费权重的更新 * @param {UpdateTurnNodeWeightParameters} params - 转向耗费权重更新服务参数类 * @example * (code) * var updateTurnNodeWeightParam=new UpdateTurnNodeWeightParameters({ * nodeId:"106", * fromEdgeId:"6508", * toEdgeId:"6504", * weightField:"TurnCost", * turnNodeWeight:"50" * }); * updateTurnNodeWeightService.processAsync(updateTurnNodeWeightParam); * (end) **/ processAsync(params) { if (!(params instanceof UpdateTurnNodeWeightParameters)) { return; } var me = this; var paramStr = me.parse(params); me.url = Util.urlPathAppend(me.url, paramStr); var data = params.turnNodeWeight ? params.turnNodeWeight : null; me.request({ method: "PUT", scope: me, data: data, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function UpdateTurnNodeWeightService.prototype.parse * @description 将更新服务参数解析为用‘/’做分隔的字符串 */ parse(params) { if (!params) { return; } var paramStr = ""; for (var attr in params) { if (params[attr] === "" || params[attr] === "turnNodeWeight") { continue; } switch (attr) { case "nodeId": paramStr += "/turnnodeweight/" + params[attr]; break; case "fromEdgeId": paramStr += "/fromedge/" + params[attr]; break; case "toEdgeId": paramStr += "/toedge/" + params[attr]; break; case "weightField": paramStr += "/weightfield/" + params[attr]; break; default : break; } } return paramStr; } } ;// CONCATENATED MODULE: ./src/common/iServer/UpdateDatasetParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class UpdateDatasetParameters * @deprecatedclass SuperMap.UpdateDatasetParameters * @category iServer Data Dataset * @classdesc 数据集信息更改参数类。 * @param {Object} options - 参数。 * @param {string} options.datasourceName - 数据源名称。 * @param {string} options.datasetName - 数据集名称。 * @param {boolean} options.isFileCache - 是否使用文件形式的缓存。仅对数据库型数据源中的矢量数据集有效。 * @param {string} options.description - 数据集描述信息。 * @param {string} options.prjCoordSys - 投影坐标系。 * @param {Object} options.charset - 矢量数据集的字符集。当数据集类型为矢量数据集时,可以传递此参数。如果用户传递空值,则编码方式保持不变。 * @param {Array.} options.palette - 影像数据的颜色调色板。当数据集类型为影像数据集时,可以传递此参数。 * @param {number} options.noValue - 栅格数据集中没有数据的像元的栅格值。当数据集类型为栅格数据集时,可以传递此参数。 * @usage */ class UpdateDatasetParameters { constructor(options) { if (!options) { return; } /** * @member {string} UpdateDatasetParameters.prototype.datasourceName * @description 数据源名称。 */ this.datasourceName = null; /** * @member {string} UpdateDatasetParameters.prototype.datasetName * @description 数据集名称。 */ this.datasetName = null; /** * @member {boolean} UpdateDatasetParameters.prototype.isFileCache * @description 是否使用文件形式的缓存。仅对数据库型数据源中的矢量数据集有效。 */ this.isFileCache = null; /** * @member {string} UpdateDatasetParameters.prototype.description * @description 数据集描述信息。 */ this.description = null; /** * @member {string} UpdateDatasetParameters.prototype.prjCoordSys * @description 投影坐标系。 */ this.prjCoordSys = null; /** * @member {Object} UpdateDatasetParameters.prototype.charset * @description 矢量数据集的字符集。 */ this.charset = null; /** * @member {Array.} UpdateDatasetParameters.prototype.palette * @description 影像数据的颜色调色板。 */ this.palette = null; /** * @member {number} UpdateDatasetParameters.prototype.noValue * @description 栅格数据集中没有数据的像元的栅格值。 */ this.noValue = null; if (options) { Util.extend(this, options); } this.CLASS_NAME = "SuperMap.UpdateDatasetParameters"; } /** * @function UpdateDatasetParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.datasourceName = null; me.datasetName = null; me.isFileCache = null; me.prjCoordSys = null; me.charset = null; me.palette = null; me.noValue = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/VectorClipJobsParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class VectorClipJobsParameter * @deprecatedclass SuperMap.VectorClipJobsParameter * @category iServer ProcessingService VectorClip * @classdesc 矢量裁剪分析任务参数类。 * @param {Object} options - 参数。 * @param {string} options.datasetName - 数据集名。 * @param {string} options.datasetOverlay - 裁剪对象数据集。 * @param {ClipAnalystMode} [options.mode=ClipAnalystMode.CLIP] - 裁剪分析模式。 * @param {OutputSetting} [options.output] - 输出参数设置。 * @param {MappingParameters} [options.mappingParameters] - 分析后结果可视化的参数类。 * @usage */ class VectorClipJobsParameter { constructor(options) { options = options || {}; /** * @member {string} VectorClipJobsParameter.prototype.datasetName * @description 数据集名。 */ this.datasetName = ""; /** * @member {string} VectorClipJobsParameter.prototype.datasetOverlay * @description 裁剪对象数据集。 */ this.datasetVectorClip = ""; /** * @member {string} VectorClipJobsParameter.prototype.geometryClip * @description 裁剪几何对象。 */ this.geometryClip = ""; /** * @member {ClipAnalystMode} [VectorClipJobsParameter.prototype.mode=ClipAnalystMode.CLIP] * @description 裁剪分析模式 。 */ this.mode = ClipAnalystMode.CLIP; /** * @member {OutputSetting} VectorClipJobsParameter.prototype.output * @description 输出参数设置类。 */ this.output = null; /** * @member {MappingParameters} [VectorClipJobsParameter.prototype.mappingParameters] * @description 分析后结果可视化的参数类。 */ this.mappingParameters = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.VectorClipJobsParameter"; } /** * @function VectorClipJobsParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.datasetName = null; this.datasetVectorClip = null; this.geometryClip = null; this.mode = null; if (this.output instanceof OutputSetting) { this.output.destroy(); this.output = null; } if (this.mappingParameters instanceof MappingParameters) { this.mappingParameters.destroy(); this.mappingParameters = null; } } /** * @function VectorClipJobsParameter.toObject * @param {Object} vectorClipJobsParameter - 区域汇总分析服务参数。 * @param {Object} tempObj - 目标对象。 * @description 矢量裁剪分析任务对象。 */ static toObject(vectorClipJobsParameter, tempObj) { for (var name in vectorClipJobsParameter) { if (name === "datasetName") { tempObj['input'] = tempObj['input'] || {}; tempObj['input'][name] = vectorClipJobsParameter[name]; continue; } if (name === "output"){ tempObj['output'] = tempObj['output'] || {}; tempObj['output'] = vectorClipJobsParameter[name]; continue; } tempObj['analyst'] = tempObj['analyst'] || {}; tempObj['analyst'][name] = vectorClipJobsParameter[name]; if(name === 'mappingParameters'){ tempObj['analyst'][name] = tempObj['analyst'][name] || {}; tempObj['analyst']['mappingParameters'] = vectorClipJobsParameter[name]; } } } } ;// CONCATENATED MODULE: ./src/common/iServer/VectorClipJobsService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class VectorClipJobsService * @deprecatedclass SuperMap.VectorClipJobsService * @category iServer ProcessingService VectorClip * @classdesc 矢量裁剪分析服务类 * @extends {ProcessingServiceBase} * @param {string} url -服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class VectorClipJobsService extends ProcessingServiceBase { constructor(url, options) { super(url, options); this.url = Util.urlPathAppend(this.url, 'spatialanalyst/vectorclip'); this.CLASS_NAME = 'SuperMap.VectorClipJobsService'; } /** *@override */ destroy() { super.destroy(); } /** * @function VectorClipJobsService.protitype.getVectorClipJobs * @description 获取矢量裁剪分析所有任务 */ getVectorClipJobs() { super.getJobs(this.url); } /** * @function KernelDensityJobsService.protitype.getVectorClipJob * @description 获取指定id的矢量裁剪分析服务 * @param {string} id - 指定要获取数据的id */ getVectorClipJob(id) { super.getJobs(Util.urlPathAppend(this.url, id)); } /** * @function VectorClipJobsService.protitype.addVectorClipJob * @description 新建矢量裁剪分析服务 * @param {VectorClipJobsParameter} params - 创建一个空间分析的请求参数。 * @param {number} seconds - 开始创建后,获取创建成功结果的时间间隔。 */ addVectorClipJob(params, seconds) { super.addJob(this.url, params, VectorClipJobsParameter, seconds); } } ;// CONCATENATED MODULE: ./src/common/iServer/RasterFunctionParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class RasterFunctionParameter * @deprecatedclass SuperMap.RasterFunctionParameter * @category iServer Map Tile * @classdesc iServer 地图服务栅格分析参数基类。 * @param {Object} options - 参数。 * @param {RasterFunctionType} options.type - 栅格分析方法。 * @usage */ class RasterFunctionParameter { constructor(options) { options = options || {}; /** * @member {RasterFunctionType} [RasterFunctionParameter.prototype.type] * @description 栅格分析方法。 */ this.type = null; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.RasterFunctionParameter'; } /** * @function RasterFunctionParameter.prototype.destroy * @description 释放资源,将资源的属性置空。 */ destroy() { this.type = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/NDVIParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class NDVIParameter * @deprecatedclass SuperMap.NDVIParameter * @category iServer Map Tile * @classdesc 归一化植被指数参数类。 * @param {Object} options - 参数。 * @param {number} [options.redIndex=0] - 红光谱波段索引。 * @param {number} [options.nirIndex=1] - 近红外光谱波段索引。 * @param {string} [options.colorMap="0:ffffe5ff;0.1:f7fcb9ff;0.2:d9f0a3ff;0.3:addd8eff;0.4:78c679ff;0.5:41ab5dff;0.6:238443ff;0.7:006837ff;1:004529ff"] - 颜色表。由栅格的中断值和颜色停止之间的映射组成的,如0.3->d9f0a3ff 指的是[0,0.3)显示d9f0a3ff。仅单波段数据时设定。 * @extends {RasterFunctionParameter} * @usage */ class NDVIParameter extends RasterFunctionParameter { constructor(options) { super(options); /** * @member {number} [NDVIParameter.prototype.redIndex=0] * @description 红光谱波段索引。 */ this.redIndex = 0; /** * @member {number} [NDVIParameter.prototype.nirIndex=1] * @description 近红外光谱波段索引。 */ this.nirIndex = 1; /** * @member {string} [NDVIParameter.prototype.colorMap="0:ffffe5ff;0.1:f7fcb9ff;0.2:d9f0a3ff;0.3:addd8eff;0.4:78c679ff;0.5:41ab5dff;0.6:238443ff;0.7:006837ff;1:004529ff"] * @description 颜色表。由栅格的中断值和颜色停止之间的映射组成的,如0.3->d9f0a3ff 指的是[0,0.3)显示d9f0a3ff。仅单波段数据时设定。 */ this.colorMap = '0:ffffe5ff;0.1:f7fcb9ff;0.2:d9f0a3ff;0.3:addd8eff;0.4:78c679ff;0.5:41ab5dff;0.6:238443ff;0.7:006837ff;1:004529ff'; /** * @member {RasterFunctionType} [NDVIParameter.prototype.type] * @description 栅格分析方法。 */ this.type = RasterFunctionType.NDVI; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.NDVIParameter'; } /** * @function NDVIParameter.prototype.destroy * @override */ destroy() { super.destroy(); this.redIndex = null; this.nirIndex = null; this.colorMap = null; } /** * @function NDVIParameter.prototype.toJSON * @description 将 NDVIParameter 对象转化为 JSON 字符串。 * @returns {string} 返回转换后的 JSON 字符串。 */ toJSON() { return { redIndex: this.redIndex, nirIndex: this.nirIndex, colorMap: this.colorMap, type: this.type }; } } ;// CONCATENATED MODULE: ./src/common/iServer/HillshadeParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class HillshadeParameter * @deprecatedclass SuperMap.HillshadeParameter * @category iServer Map Tile * @classdesc 阴影面分析参数类。 * @param {Object} options - 可选参数。 * @param {number} [options.altitude=45] - 高于地平线的光源高度角。高度角由正度数表示,0 度代表地平线,而 90 度代表头顶正上方。 * @param {number} [options.azimuth=315] - 光源的方位角。方位角由0到360度之间的正度数表示,以北为基准方向按顺时针进行测量。 * @param {number} [options.zFactor=1] - 一个表面 z 单位中地面 x,y 单位的数量。z 单位与输入表面的 x,y 单位不同时,可使用 z 因子调整 z 单位的测量单位。计算最终输出表面时,将用 z 因子乘以输入表面的 z 值。 * z 单位与输入表面的 x,y 单位不同时,可使用 z 因子调整 z 单位的测量单位。计算最终输出表面时,将用 z 因子乘以输入表面的 z 值。 * 如果 x,y 单位和 z 单位采用相同的测量单位,则 z 因子为 1。这是默认设置。 * 如果 x,y 单位和 z 单位采用不同的测量单位,则必须将 z 因子设置为适当的因子,否则会得到错误的结果。例如,如果 z 单位是英尺而 x,y 单位是米,则应使用 z 因子 0.3048 将 z 单位从英尺转换为米(1 英尺 = 0.3048 米)。 * 如果输入栅格位于球面坐标系中(如十进制度球面坐标系),则生成的山体阴影可能看起来很独特。这是因为水平地面单位与高程 z 单位之间的测量值存在差异。由于经度的长度随着纬度而变化,因此需要为该纬度指定一个适当的 z 因子。如果 x,y 单位是十进制度而 Z 单位是米,特定纬度的一些合适的 Z 因子为: * Latitude Z-factor * 0 0.00000898 * 10 0.00000912 * 20 0.00000956 * 30 0.00001036 * 40 0.00001171 * 50 0.00001395 * 60 0.00001792 * 70 0.00002619 * 80 0.00005156 * @extends {RasterFunctionParameter} * @usage */ class HillshadeParameter extends RasterFunctionParameter { constructor(options) { super(options); /** * @member {number} [HillshadeParameter.prototype.altitude = 45] * @description 高于地平线的光源高度角。高度角由正度数表示,0 度代表地平线,而 90 度代表头顶正上方。 */ this.altitude = 45; /** * @member {number} [HillshadeParameter.prototype.azimuth = 315] * @description 光源的方位角。方位角由0到360度之间的正度数表示,以北为基准方向按顺时针进行测量。 */ this.azimuth = 315; /** * @member {number} [HillshadeParameter.prototype.zFactor = 1] * @description 一个表面 z 单位中地面 x,y 单位的数量。z 单位与输入表面的 x,y 单位不同时,可使用 z 因子调整 z 单位的测量单位。计算最终输出表面时,将用 z 因子乘以输入表面的 z 值。 */ this.zFactor = 1; /** * @member {RasterFunctionType} HillshadeParameter.prototype.type * @description 栅格分析方法。 */ this.type = RasterFunctionType.HILLSHADE; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.HillshadeParameter'; } /** * @function HillshadeParameter.prototype.destroy * @override */ destroy() { super.destroy(); this.altitude = null; this.azimuth = null; this.zFactor = null; } /** * @function HillshadeParameter.prototype.toJSON * @description 将 HillshadeParameter 对象转化为 JSON 字符串。 * @returns {string} 返回转换后的 JSON 字符串。 */ toJSON() { return { altitude: this.altitude, azimuth: this.azimuth, zFactor: this.zFactor, type: this.type }; } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobCustomItems.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobCustomItems * @deprecatedclass SuperMap.WebPrintingJobCustomItems * @classdesc Web 打印图例元素参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {string} option.name - 图例元素的名称。 * @param {string} option.picAsUrl - 图例元素 Base64 格式图片。 * @param {string} [option.picAsBase64] - 图例元素图片的获取地址。如果已填了 URL 参数,此参数可不传。 * @usage */ class WebPrintingJobCustomItems { constructor(option) { /** * @member {string} WebPrintingJobCustomItems.prototype.name * @description 图例元素的名称。 */ this.name = null; /** * @member {string} [WebPrintingJobCustomItems.prototype.picAsUrl] * @description 图例元素 Base64 格式图片。 */ this.picAsUrl = null; /** * @member {string} [WebPrintingJobCustomItems.prototype.picAsBase64] * @description 图例元素图片的获取地址。 */ this.picAsBase64 = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobCustomItems'; Util.extend(this, option); } /** * @function WebPrintingJobCustomItems.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.name = null; me.picAsUrl = null; me.picAsBase64 = null; } /** * @function WebPrintingJobCustomItems.prototype.toJSON * @description 将 WebPrintingJobCustomItems 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = { name: this.name }; if (this.title) { params.title = this.title; } if (this.picAsUrl) { params.picAsUrl = this.picAsUrl; } else if (this.picAsBase64) { params.picAsBase64 = this.picAsBase64.replace(/^data:.+;base64,/, ''); } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobImage.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobImage * @deprecatedclass SuperMap.WebPrintingJobImage * @classdesc 表达小地图的静态图片参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {string} option.picAsUrl - 小地图的图片 URL 地址。 * @param {string} [option.picAsBase64] - 小地图的base64位图片信息。如果已填了 URL 参数,此参数可不传。 * @usage */ class WebPrintingJobImage { constructor(option) { /** * @member {string} [WebPrintingJobImage.prototype.picAsUrl] * @description 小地图的图片 URL 地址。 */ this.picAsUrl = null; /** * @member {string} [WebPrintingJobImage.prototype.picAsBase64] * @description 小地图的base64位图片信息。 */ this.picAsBase64 = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobImage'; Util.extend(this, option); } /** * @function WebPrintingJobImage.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.picAsUrl = null; this.picAsBase64 = null; } /** * @function WebPrintingJobImage.prototype.toJSON * @description 将 WebPrintingJobImage 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = {}; if (this.picAsUrl) { params.picAsUrl = this.picAsUrl; } if (this.picAsBase64) { params.picAsBase64 = this.picAsBase64.replace(/^data:.+;base64,/, ''); } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobLayers.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobLayers * @deprecatedclass SuperMap.WebPrintingJobLayers * @classdesc 将图例添加到布局的业务图层参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {string} option.name - 图层 name 的字符串。此 name 必须唯一,并且必须与定义业务图层的 LegendOptions_layers 元素中的图层 name 匹配。 * @usage */ class WebPrintingJobLayers { constructor(option) { /** * @member {string} WebPrintingJobLayers.prototype.name * @description 图层 name。 */ this.name = null; /** * @member {string} WebPrintingJobLayers.prototype.layerType * @description 图层 type。 */ this.layerType = null; /** * @member {string} WebPrintingJobLayers.prototype.url * @description 图层 URL。 */ this.url = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobLayers'; Util.extend(this, option); } /** * @function WebPrintingJobLayers.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.name = null; this.layerType = null; this.url = null; } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobLegendOptions.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobLegendOptions * @deprecatedclass SuperMap.WebPrintingJobLegendOptions * @classdesc Web 打印图例参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {string} [option.title] - 图例名称。 * @param {string} [option.picAsUrl] - 图例的图片 URL 地址。 * @param {string} [option.picAsBase64] - 图例的 base64 位图片信息。 * @param {WebPrintingJobLayers} [option.layers] - 图例的布局业务图层参数类。 * @param {WebPrintingJobCustomItems} [option.customItems] - 自定义图例元素参数类。 * @usage */ class WebPrintingJobLegendOptions { constructor(option) { /** * @member {string} WebPrintingJobLegendOptions.prototype.title * @description 图例名称。 */ this.title = null; /** * @member {string} [WebPrintingJobLegendOptions.prototype.picAsUrl] * @description 图例的图片 URL 地址。 */ this.picAsUrl = null; /** * @member {string} [WebPrintingJobLegendOptions.prototype.picAsBase64] * @description 图例的 base64 位图片信息。 */ this.picAsBase64 = null; /** * @member {WebPrintingJobLayers} [WebPrintingJobLegendOptions.prototype.layers] * @description 图例的布局业务图层参数类。 */ this.layers = null; /** * @member {WebPrintingJobCustomItems} [WebPrintingJobLegendOptions.prototype.customItems] * @description 自定义图例元素参数类。 */ this.customItems = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobLegendOptions'; Util.extend(this, option); } /** * @function WebPrintingJobLegendOptions.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.title = null; this.picAsUrl = null; this.picAsBase64 = null; if (this.layers instanceof WebPrintingJobLayers) { this.layers.destroy(); this.layers = null; } if (this.customItems instanceof WebPrintingJobCustomItems) { this.customItems.destroy(); this.customItems = null; } } /** * @function WebPrintingJobLegendOptions.prototype.toJSON * @description 将 WebPrintingJobLegendOptions 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = { title: this.title || "" }; if (this.picAsUrl) { params.picAsUrl = this.picAsUrl; } else if (this.picAsBase64) { params.picAsBase64 = this.picAsBase64.replace(/^data:.+;base64,/, ''); } else if (this.customItems) { params.customItems = this.customItems; } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobLittleMapOptions.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobLittleMapOptions * @deprecatedclass SuperMap.WebPrintingJobLittleMapOptions * @classdesc Web 打印小地图参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {GeometryPoint|L.Point|L.LatLng|ol.geom.Point|mapboxgl.LngLat|mapboxgl.Point|Array.} option.center - 小地图的中心点。 * @param {number} [option.scale] - 小地图的比例尺。 * @param {Array.} [option.layerNames] - 指定 WebMap中图层名称的列表,用于渲染小地图。 * @param {WebPrintingJobImage} [option.image] - 表达小地图的静态图类。 * @param {WebPrintingJobLayers} [option.layers] - 指定 WebMap 中的 layers 图层类。 * @usage */ class WebPrintingJobLittleMapOptions { constructor(option) { /** * @member {GeometryPoint|L.Point|L.LatLng|ol.geom.Point|mapboxgl.LngLat|mapboxgl.Point|Array.} WebPrintingJobLittleMapOptions.prototype.center * @description 小地图的中心点。 */ this.center = null; /** * @member {number} [WebPrintingJobLittleMapOptions.prototype.scale] * @description 小地图的比例尺。 */ this.scale = null; /** * @member {Array.} WebPrintingJobLittleMapOptions.prototype.layerNames * @description 指定 WebMap中图层名称的列表,用于渲染小地图。 */ this.layerNames = null; /** * @member {WebPrintingJobImage} [WebPrintingJobLittleMapOptions.prototype.image] * @description 表达小地图的静态图类。暂不支持。 */ this.image = null; /** * @member {WebPrintingJobLayers} [WebPrintingJobLittleMapOptions.prototype.layers] * @description 指定 WebMap 中的 layers 图层类。 */ this.layers = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobLittleMapOptions'; Util.extend(this, option); } /** * @function WebPrintingJobLittleMapOptions.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.center = null; this.scale = null; this.layerNames = null; if (this.image instanceof WebPrintingJobImage) { this.image.destroy(); this.image = null; } if (this.layers instanceof WebPrintingJobLayers) { this.layers.destroy(); this.layers = null; } } /** * @function WebPrintingJobLittleMapOptions.prototype.toJSON * @description 将 WebPrintingJobLittleMapOptions 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = { scale: this.scale, center: this.center }; if (this.layerNames) { params.layerNames = this.layerNames; } else if (this.layers) { params.layers = this.layers; } if (this.image) { params.image = this.image; } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobNorthArrowOptions.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobNorthArrowOptions * @deprecatedclass SuperMap.WebPrintingJobNorthArrowOptions * @classdesc Web 打印地图指北针参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {string} option.picAsUrl - 指北针的图片 URL 地址。 * @param {string} [option.picAsBase64] - 指北针的base64位图片信息。 * @usage */ class WebPrintingJobNorthArrowOptions { constructor(option) { /** * @member {string} WebPrintingJobNorthArrowOptions.prototype.picAsUrl * @description 指北针的图片 URL 地址。 */ this.picAsUrl = null; /** * @member {string} [WebPrintingJobNorthArrowOptions.prototype.picAsBase64] * @description 指北针的base64位图片信息。 */ this.picAsBase64 = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobNorthArrowOptions'; Util.extend(this, option); } /** * @function WebPrintingJobNorthArrowOptions.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.picAsUrl = null; this.picAsBase64 = null; } /** * @function WebPrintingJobNorthArrowOptions.prototype.toJSON * @description 将 WebPrintingJobNorthArrowOptions 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = {}; if (this.picAsUrl) { params.picAsUrl = this.picAsUrl; } else if (this.picAsBase64) { params.picAsBase64 = this.picAsBase64.replace(/^data:.+;base64,/, ''); } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobScaleBarOptions.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobScaleBarOptions * @deprecatedclass SuperMap.WebPrintingJobScaleBarOptions * @classdesc Web 打印比例尺参数类。 * @category iServer WebPrintingJob * @version 10.1.0 * @param {Object} option - 参数。 * @param {string} [option.scaleText] - 比例尺文本信息。例如:1:1000000。 * @param {WebScaleOrientationType} [option.orientation] - 比例尺的方位样式。 * @param {WebScaleType} [option.type] - 比例尺的样式。 * @param {number} [option.intervals] - 比例尺条的段数。 * @param {WebScaleUnit} [option.unit] - 比例尺的单位制。 * @usage */ class WebPrintingJobScaleBarOptions { constructor(option) { /** * @member {string} WebPrintingJobScaleBarOptions.prototype.scaleText * @description 比例尺文本信息。 */ this.scaleText = null; /** * @member {WebScaleOrientationType} [WebPrintingJobScaleBarOptions.prototype.orientation] * @description 比例尺的方位样式。 */ this.orientation = null; /** * @member {WebScaleType} [WebPrintingJobScaleBarOptions.prototype.type] * @description 比例尺的样式。 */ this.type = null; /** * @member {Object} [WebPrintingJobScaleBarOptions.prototype.intervals] * @description 比例尺条的段数。 */ this.intervals = null; /** * @member {WebScaleUnit} [WebPrintingJobScaleBarOptions.prototype.unit] * @description 比例尺的单位制。 */ this.unit = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobScaleBarOptions'; Util.extend(this, option); } /** * @function WebPrintingJobScaleBarOptions.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.scaleText = null; this.orientation = null; this.type = null; this.intervals = null; this.unit = null; } /** * @function WebPrintingJobScaleBarOptions.prototype.toJSON * @description 将 WebPrintingJobScaleBarOptions 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = { scaleText: this.scaleText || "", type: this.type || "BAR", intervals: this.intervals || "", unit: this.unit || "METER" }; if (this.orientation) { params.orientation = this.orientation; } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobContent.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobContent * @deprecatedclass SuperMap.WebPrintingJobContent * @classdesc Web 打印内容参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {string} option.type - Web 打印内容支持的类型。目前支持的类型:WEBMAP。 * @param {string} [option.url] - 待打印的 SuperMap iPortal WebMap 的 URL 地址。例如:http://supermapiportal:8190/iportal/web/maps/{mapid}/map.rjson 。 * @param {string} [option.token] - 如果待打印的是 SuperMap iPortal 用户私有的 WebMap,需要提供 SuperMap iPortal 用户的 token。 * @param {WebMapSummaryObject} [option.value] - 传递的是一个符合 SuperMap WebMap 规范的 WebMap 的 JSON 表达,也可以是一个完整的 SuperMap iPortal 数据上图制作的 WebMap 的 JSON 表达。如果已填了 URL 参数,此参数可不传。 * @usage */ class WebPrintingJobContent { constructor(option) { /** * @member {string} WebPrintingJobContent.prototype.type * @description Web 打印内容支持的类型。 */ this.type = null; /** * @member {string} [WebPrintingJobContent.prototype.url] * @description 待打印的 SuperMap iPortal WebMap 的 URL 地址。 */ this.url = null; /** * @member {string} [WebPrintingJobContent.prototype.token] * @description 如果待打印的是 SuperMap iPortal 用户私有的 WebMap,需要提供 SuperMap iPortal 用户的 token。 */ this.token = null; /** * @member {WebMapSummaryObject} [WebPrintingJobContent.prototype.value] * @description 传递的是一个符合 SuperMap WebMap 规范的 WebMap 的 JSON 表达,也可以是一个完整的 SuperMap iPortal 数据上图制作的 WebMap 的 JSON 表达。 */ this.value = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobContent'; Util.extend(this, option); } /** * @function WebPrintingJobContent.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.type = false || "WEBMAP"; this.url = null; this.token = null; this.value = null; } /** * @function WebPrintingJobContent.prototype.toJSON * @description 将 WebPrintingJobContent 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = { type: this.type }; if (this.token) { params.token = this.token; } if (this.url) { params.url = this.url; } else if (this.value) { params.value = this.value; } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobLayoutOptions.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobLayoutOptions * @deprecatedclass SuperMap.WebPrintingJobLayoutOptions * @classdesc Web 打印的布局参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {string} option.templateName - 布局模板的名称。 * @param {string} option.title - 地图主标题名称。 * @param {string} option.subTitle - 地图副标题名称。 * @param {string} option.author - 作者名称。 * @param {string} option.copyright - 版权信息。 * @param {WebPrintingJobLittleMapOptions} option.littleMapOptions - 小地图参数类。 * @param {WebPrintingJobLegendOptions} option.legendOptions - 图例参数类。 * @param {WebPrintingJobScaleBarOptions} [option.scaleBarOptions] - 地图比例尺参数类。 * @param {WebPrintingJobNorthArrowOptions} [option.northArrowOptions] - 地图指北针参数类。 * @usage */ class WebPrintingJobLayoutOptions { constructor(option) { /** * @member {string} WebPrintingJobLayoutOptions.prototype.templateName * @description 布局模板的名称。 */ this.templateName = null; /** * @member {string} WebPrintingJobLayoutOptions.prototype.title * @description 地图主标题名称。 */ this.title = null; /** * @member {string} WebPrintingJobLayoutOptions.prototype.subTitle * @description 地图副标题名称。 */ this.subTitle = null; /** * @member {string} WebPrintingJobLayoutOptions.prototype.author * @description 地图作者名称。 */ this.author = null; /** * @member {string} WebPrintingJobLayoutOptions.prototype.copyright * @description 地图版权信息。 */ this.copyright = null; /** * @member {WebPrintingJobScaleBarOptions} [WebPrintingJobLayoutOptions.prototype.scaleBarOptions] * @description 地图比例尺参数类。 */ this.scaleBarOptions = null; /** * @member {WebPrintingJobNorthArrowOptions} [WebPrintingJobLayoutOptions.prototype.northArrowOptions] * @description 地图指北针参数类。 */ this.northArrowOptions = null; /** * @member {WebPrintingJobLittleMapOptions} WebPrintingJobLayoutOptions.prototype.littleMapOptions * @description 小地图参数类。 */ this.littleMapOptions = null; /** * @member {WebPrintingJobLegendOptions} WebPrintingJobLayoutOptions.prototype.legendOptions * @description 图例参数类。 */ this.legendOptions = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobLayoutOptions'; Util.extend(this, option); } /** * @function WebPrintingJobLayoutOptions.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.templateName = null; this.title = null; this.subTitle = null; this.author = null; this.copyright = null; if (this.scaleBarOptions instanceof WebPrintingJobScaleBarOptions) { this.scaleBarOptions.destroy(); this.scaleBarOptions = null; } if (this.northArrowOptions instanceof WebPrintingJobNorthArrowOptions) { this.northArrowOptions.destroy(); this.northArrowOptions = null; } if (this.littleMapOptions instanceof WebPrintingJobLittleMapOptions) { this.littleMapOptions.destroy(); this.littleMapOptions = null; } if (this.legendOptions instanceof WebPrintingJobLegendOptions) { this.legendOptions.destroy(); this.legendOptions = null; } } /** * @function WebPrintingJobLayoutOptions.prototype.toJSON * @description 将 WebPrintingJobLayoutOptions 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = { templateName: this.templateName, title: this.title, subTitle: this.subTitle, author: this.author, copyright: this.copyright }; if (this.scaleBarOptions) { params.scaleBarOptions = this.scaleBarOptions; } if (this.northArrowOptions) { params.northArrowOptions = this.northArrowOptions; } if (this.littleMapOptions) { params.littleMapOptions = this.littleMapOptions; } if (this.legendOptions) { params.legendOptions = this.legendOptions; } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobExportOptions.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobExportOptions * @deprecatedclass SuperMap.WebPrintingJobExportOptions * @classdesc Web 打印的输出参数类。 * @version 10.1.0 * @category iServer WebPrintingJob * @param {Object} option - 参数。 * @param {WebExportFormatType} option.format - Web 打印输出的格式,目前支持:PNG、PDF。 * @param {number} [option.dpi=96] - Web 打印输出的分辨率,单位为每英寸点数。默认值为 96 DPI。 * @param {number} [option.scale] - Web 打印输出的地图比例尺。 * @param {number} [option.rotation] - Web 打印输出的地图角度。 * @param {GeometryPoint|L.Point|L.LatLng|ol.geom.Point|mapboxgl.LngLat|mapboxgl.Point|Array.} [option.center] - Web 打印输出的地图中心点。 * @usage */ class WebPrintingJobExportOptions { constructor(option) { /** * @member {WebExportFormatType} WebPrintingJobExportOptions.prototype.format * @description Web 打印输出的格式。 */ this.format = null; /** * @member {number} [WebPrintingJobExportOptions.prototype.dpi=96] * @description Web 打印输出的分辨率,单位为每英寸点数。 */ this.dpi = 96; /** * @member {number} [WebPrintingJobExportOptions.prototype.scale] * @description Web 打印输出的地图比例尺。 */ this.scale = null; /** * @member {number} [WebPrintingJobExportOptions.prototype.rotation] * @description Web 打印输出的地图角度。 */ this.rotation = null; /** * @member {GeometryPoint|L.Point|L.LatLng|ol.geom.Point|mapboxgl.LngLat|mapboxgl.Point|Array.} [WebPrintingJobExportOptions.prototype.center] * @description Web 打印输出的地图中心点。 */ this.center = null; this.CLASS_NAME = 'SuperMap.WebPrintingJobExportOptions'; Util.extend(this, option); } /** * @function WebPrintingJobExportOptions.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.format = null; this.dpi = null; this.scale = null; this.rotation = null; this.center = null; this.outputSize = null; } /** * @function WebPrintingJobExportOptions.prototype.toJSON * @description 将 WebPrintingJobExportOptions 对象转化为 JSON 字符串。 * @returns {string} 转换后的 JSON 字符串。 */ toJSON() { var params = { format: this.format || "PDF", dpi: this.dpi, scale: this.scale, center: this.center }; if (this.rotation) { params.rotation = this.rotation; } if (this.outputSize) { params.outputSize = this.outputSize; } return Util.toJSON(params); } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingJobParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobParameters * @deprecatedclass SuperMap.WebPrintingJobParameters * @category iServer WebPrintingJob * @version 10.1.0 * @classdesc Web 打印参数类。 * @param {Object} options - 参数。 * @param {WebPrintingJobContent} options.content - Web 打印的内容类。 * @param {WebPrintingJobLayoutOptions} options.layoutOptions - Web 打印的布局类,包含各种布局元素的设置。 * @param {WebPrintingJobExportOptions} options.exportOptions - Web 打印的输出类,包含 DPI、页面大小等。 * @usage */ class WebPrintingJobParameters { constructor(options) { if (!options) { return; } /** * @member {WebPrintingJobContent} WebPrintingJobParameters.prototype.content * @description Web 打印的内容类。 */ this.content = null; /** * @member {WebPrintingJobLayoutOptions} WebPrintingJobParameters.prototype.layoutOptions * @description Web 打印的布局类,包含各种布局元素的设置。 */ this.layoutOptions = null; /** * @member {WebPrintingJobExportOptions} WebPrintingJobParameters.prototype.exportOptions * @description Web 打印的输出类,包含 DPI、页面大小等。 */ this.exportOptions = null; Util.extend(this, options); this.CLASS_NAME = 'SuperMap.WebPrintingJobParameters'; } /** * @function WebPrintingJobParameters.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { if (this.content instanceof WebPrintingJobContent) { this.content.destroy(); this.content = null; } if (this.layoutOptions instanceof WebPrintingJobLayoutOptions) { this.layoutOptions.destroy(); this.layoutOptions = null; } if (this.exportOptions instanceof WebPrintingJobExportOptions) { this.exportOptions.destroy(); this.exportOptions = null; } } } ;// CONCATENATED MODULE: ./src/common/iServer/WebPrintingService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingService * @deprecatedclass SuperMap.WebPrintingService * @category iServer WebPrintingJob * @version 10.1.0 * @classdesc 打印地图服务基类。 * @extends {CommonServiceBase} * @param {string} url - 服务地址。请求打印地图服务的 URL 应为:http://{服务器地址}:{服务端口号}/iserver/services/webprinting/rest/webprinting/v1。 * @param {Object} options - 参数。 * @param {Object} options.eventListeners - 事件监听器对象。有processCompleted属性可传入处理完成后的回调函数。processFailed属性传入处理失败后的回调函数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class WebPrintingService extends CommonServiceBase { constructor(url, options) { super(url, options); if (options) { Util.extend(this, options); } this.CLASS_NAME = 'SuperMap.WebPrintingService'; if (!this.url) { return; } } /** * @function WebPrintingService.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { super.destroy(); } /** * @function WebPrintingService.prototype.createWebPrintingJob * @description 创建 Web 打印任务。 * @param {WebPrintingJobParameters} params - Web 打印的请求参数。 */ createWebPrintingJob(params) { if (!params) { return; } if (params.layoutOptions) { if (params.layoutOptions.legendOptions) { !params.layoutOptions.legendOptions.title && (params.layoutOptions.legendOptions.title = ''); params.layoutOptions.legendOptions.picAsBase64 = params.layoutOptions.legendOptions.picAsBase64 && params.layoutOptions.legendOptions.picAsBase64.replace(/^data:.+;base64,/, ''); if ( params.layoutOptions.legendOptions.customItems && params.layoutOptions.legendOptions.customItems.hasOwnProperty('picAsBase64') ) { params.layoutOptions.legendOptions.customItems.picAsBase64 = params.layoutOptions.legendOptions.customItems.picAsBase64.replace( /^data:.+;base64,/, '' ); } } } var me = this; me.request({ url: me._processUrl('jobs'), method: 'POST', data: Util.toJSON(params), scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function WebPrintingService.prototype.getPrintingJob * @description 获取 Web 打印输出文档任务。 * @param {string} jobId - Web 打印任务 ID */ getPrintingJob(jobId) { var me = this; var url = me._processUrl(`jobs/${jobId}`); me.request({ url, method: 'GET', scope: me, success: function (result) { me.rollingProcess(result, url); }, failure: me.serviceProcessFailed }); } /** * @function WebPrintingService.prototype.getPrintingJobResult * @description 获取 Web 打印任务的输出文档。 * @param {string} jobId - Web 打印输入文档任务 ID。 */ getPrintingJobResult(jobId) { var me = this; me.request({ url: me._processUrl(`jobs/${jobId}/result`), method: 'GET', scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function WebPrintingService.prototype.getLayoutTemplates * @description 查询 Web 打印服务所有可用的模板信息。 */ getLayoutTemplates() { var me = this; me.request({ url: me._processUrl('layouts'), method: 'GET', scope: me, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function WebPrintingService.prototype.rollingProcess * @description 轮询查询 Web 打印任务。 * @param {Object} result - 服务器返回的结果对象。 */ rollingProcess(result, url) { var me = this; if (!result) { return; } var id = setInterval(function () { me.request({ url, method: 'GET', scope: me, success: function (result) { switch (result.status) { case 'FINISHED': clearInterval(id); me.serviceProcessCompleted(result); break; case 'ERROR': clearInterval(id); me.serviceProcessFailed(result); break; case 'RUNNING': me.events.triggerEvent('processRunning', result); break; } }, failure: me.serviceProcessFailed }); }, 1000); } _processUrl(appendContent) { if (appendContent) { return Util.urlPathAppend(this.url, appendContent); } return this.url; } } ;// CONCATENATED MODULE: ./src/common/iServer/ImageCollectionService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageCollectionService * @deprecatedclass SuperMap.ImageCollectionService * @classdesc 影像集合服务类。 * @version 10.2.0 * @category iServer Image * @param {string} url - 服务地址。例如: http://{ip}:{port}/iserver/{imageservice-imageserviceName}/restjsr/ * @param {Object} options - 参数。 * @param {string} options.collectionId 影像集合(Collection)的ID,在一个影像服务中唯一标识影像集合。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {CommonServiceBase} * @usage */ class ImageCollectionService_ImageCollectionService extends CommonServiceBase { constructor(url, options) { super(url, options); this.options = options || {}; if (options) { Util.extend(this, options); } this.CLASS_NAME = 'SuperMap.ImageCollectionService'; } /** * @function ImageCollectionService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function ImageCollectionService.prototype.getLegend * @description 返回当前影像集合的图例信息。默认为服务发布所配置的风格,支持根据风格参数生成新的图例。 * @param {Object} queryParams query参数。 * @param {ImageRenderingRule} [queryParams.renderingRule] renderingRule 对象,用来指定影像的渲染风格,从而确定图例内容。影像的渲染风格包含拉伸显示方式、颜色表、波段组合以及应用栅格函数进行快速处理等。该参数未设置时,将使用发布服务时所配置的风格。 */ getLegend(queryParams) { var me = this; var pathParams = { collectionId: me.options.collectionId }; var path = Util.convertPath('/collections/{collectionId}/legend', pathParams); var url = Util.urlPathAppend(me.url, path); this.request({ method: 'GET', url, params: queryParams, scope: this, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ImageCollectionService.prototype.getStatistics * @description 返回当前影像集合的统计信息。包括文件数量,文件大小等信息。 */ getStatistics() { var me = this; var pathParams = { collectionId: me.options.collectionId }; var path = Util.convertPath('/collections/{collectionId}/statistics', pathParams); var url = Util.urlPathAppend(me.url, path); this.request({ method: 'GET', url, scope: this, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ImageCollectionService.prototype.getTileInfo * @description 返回影像集合所提供的服务瓦片的信息,包括:每层瓦片的分辨率,比例尺等信息,方便前端进行图层叠加。 */ getTileInfo() { var me = this; var pathParams = { collectionId: me.options.collectionId }; var path = Util.convertPath('/collections/{collectionId}/tileInfo', pathParams); var url = Util.urlPathAppend(me.url, path); this.request({ method: 'GET', url, scope: this, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ImageCollectionService.prototype.deleteItemByID * @description 删除影像集合中指定 ID 的 Item,即从影像集合中删除指定的影像。 * @param {string} featureId Feature 的本地标识符。 */ deleteItemByID(featureId) { var me = this; var pathParams = { collectionId: me.options.collectionId, featureId: featureId }; var path = Util.convertPath('/collections/{collectionId}/items/{featureId}', pathParams); var url = Util.urlPathAppend(me.url, path); this.request({ method: 'DELETE', url, scope: this, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ImageCollectionService.prototype.getItemByID * @description 返回指定ID(`collectionId`)的影像集合中的指定ID(`featureId`)的Item对象,即返回影像集合中指定的影像。 * @param {string} featureId Feature 的本地标识符。 */ getItemByID(featureId) { var me = this; var pathParams = { collectionId: me.options.collectionId, featureId: featureId }; var path = Util.convertPath('/collections/{collectionId}/items/{featureId}', pathParams); var url = Util.urlPathAppend(me.url, path); this.request({ method: 'GET', url, scope: this, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/ImageService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageService * @deprecatedclass SuperMap.ImageService * @classdesc 影像服务类。 * @version 10.2.0 * @category iServer Image * @param {string} url - 服务地址。例如: http://{ip}:{port}/iserver/{imageservice-imageserviceName}/restjsr/ * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {CommonServiceBase} * @usage */ class ImageService_ImageService extends CommonServiceBase { constructor(url, options) { super(url, options); this.options = options || {}; if (options) { Util.extend(this, options); } this.CLASS_NAME = 'SuperMap.ImageService'; } /** * @function ImageService.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function ImageService.prototype.getCollections * @description 返回当前影像服务中的影像集合列表(Collections)。 */ getCollections() { var me = this; var path = Util.convertPath('/collections'); var url = Util.urlPathAppend(me.url, path); this.request({ method: 'GET', url, scope: this, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ImageService.prototype.getCollectionByID * @description ID值等于`collectionId`参数值的影像集合(Collection)。ID值用于在服务中唯一标识该影像集合。 * @param {string} collectionId 影像集合(Collection)的ID,在一个影像服务中唯一标识影像集合。 */ getCollectionByID(collectionId) { var pathParams = { collectionId: collectionId }; var me = this; var path = Util.convertPath('/collections/{collectionId}', pathParams); var url = Util.urlPathAppend(me.url, path); this.request({ method: 'GET', url, scope: this, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } /** * @function ImageSearchService.prototype.search * @description 查询与过滤条件匹配的影像数据。 * @param {ImageSearchParameter} [imageSearchParameter] 查询参数。 */ search(imageSearchParameter) { var postBody = { ...(imageSearchParameter || {}) }; var me = this; var path = Util.convertPath('/search'); var url = Util.urlPathAppend(me.url, path); this.request({ method: 'POST', url, data: postBody, scope: this, success: me.serviceProcessCompleted, failure: me.serviceProcessFailed }); } } ;// CONCATENATED MODULE: ./src/common/iServer/FieldsFilter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FieldsFilter * @deprecatedclass SuperMap.FieldsFilter * @category iServer Data Field * @classdesc 指定返回的用于描述 Feature 的字段。 * @param {Object} options - 可选参数。 * @param {Array.} [options.include] 对返回的字段内容进行过滤,需保留的字段列表。 * @param {Array.} [options.exclude] 对返回的字段内容进行过滤,需排除的字段列表。 * @usage */ class FieldsFilter { constructor(options) { /** * @description 对返回的字段内容进行过滤,需保留的字段列表。 * @member {Array.} FieldsFilter.prototype.include */ this.include = undefined; /** * @description 对返回的字段内容进行过滤,需排除的字段列表。 * @member {Array.} FieldsFilter.prototype.exclude */ this.exclude = undefined; this.CLASS_NAME = 'SuperMap.FieldsFilter'; Util.extend(this, options); } /** * @function FieldsFilter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.include = undefined; me.exclude = undefined; } /** * @function FieldsFilter.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {FieldsFilter} obj 返回的模型。 * @return {FieldsFilter} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new FieldsFilter(); if (data.hasOwnProperty('include')) { obj.include = data.include } if (data.hasOwnProperty('exclude')) { obj.exclude = data.exclude } } return obj; } } ;// CONCATENATED MODULE: ./src/common/iServer/Sortby.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Sortby * @deprecatedclass SuperMap.Sortby * @classdesc 通过指定字段进行排序的方法类。 * @category BaseTypes Util * @param {Object} options - 参数。 * @param {string} options.field 属性名称。 * @param {Sortby.Direction} options.direction 排序规则,默认升序。 * @usage */ class Sortby { constructor(options) { /** * @description 属性名称。 * @member {string} Sortby.prototype.field */ this.field = undefined; /** * @description 排序规则。 * @member {Sortby.Direction} Sortby.prototype.direction * @default Sortby.Direction.ASC */ this.direction = Sortby.Direction.ASC; this.CLASS_NAME = 'SuperMap.Sortby'; Util.extend(this, options); } /** * @function Sortby.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.field = undefined; me.direction = 'ASC'; } /** * @function Sortby.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {Sortby} obj 返回的模型。 * @return {Sortby} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new Sortby(); if (data.hasOwnProperty('field')) { obj.field = data.field; } if (data.hasOwnProperty('direction')) { obj.direction = data.direction; } } return obj; } } /** * @enum Direction * @description 排序的类型枚举。 * @memberOf Sortby * @readonly * @type {string} */ Sortby.Direction = { /** 升序。 */ ASC: 'ASC', /** 降序。 */ DESC: 'DESC' }; ;// CONCATENATED MODULE: ./src/common/iServer/ImageSearchParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageSearchParameter * @deprecatedclass SuperMap.ImageSearchParameter * @classdesc 影像服务查询参数类。 * @category iServer Image * @param {Object} options - 可选参数。 * @param {Array.} [options.bbox] 指定查询范围。只有具有几何对象(geometry)属性的Features,并且该几何对象与该参数指定的范围相交的 Features 才会被选择出来。该参数可以包含4个数值或者6个数值,这取决于使用的坐标参考系统是否包含高程值: * 左下角坐标轴 1 的值 * 左下角坐标轴 2 的值 * 坐标轴 3 的最小值(可选) * 右上角坐标轴 1 的值 * 右上角坐标轴 2 的值 * 坐标轴 3 的最大值(可选) 坐标参考系统为 WGS 84 经度/纬度 (http://www.opengis.net/def/crs/OGC/1.3/CRS84)。对于 “WGS 84 经度/纬度” 坐标参考系统,该参数值的格式通常为:最小经度,最小纬度,最大经度,最大纬度。如果包含了高程值,该参数的格式为:最小经度,最小纬度,最小高程值,最大经度,最大纬度,最大高程值。如果一个 Feature 具有多个空间几何对象(geometry)属性,由服务器决定是否使用单一的空间几何对象属性,还是使用所有相关的几何对象作为最终的查询空间范围。 * @param {Array.} [options.collections] 影像集合的ID数组,将在该指定的Collection中搜索Items。 * @param {Array.} [options.ids] 只返回指定 Item 的 ID 数组中的Item。返回的 Item 的 ID 值数组。设置了该参数,所有其他过滤器参数(除了next和limit)将被忽略。 * @param {number} [options.limit] 返回的最大结果数,即响应文档包含的 Item 的数目。 * @param {FieldsFilter} [options.fields] 通过‘include’和‘exclude’属性分别指定哪些字段包含在查询结果的 Feature 描述中,哪些需要排除。返回结果中的stac_version,id,bbox,assets,links,geometry,type,properties这些字段为必须字段,若要返回结果中不含这种字段信息,需要显示地进行排除设置,如:排除geometry和bbox字段;在POST请求中,则需要将这些字段添加到“exclude”字段中,例如: "fields": { "exclude": ["geometry","bbox"] } } 。而对于返回的“properties”对象中的扩展字段内容,可以将字段前添加到‘include’字段中,如: "fields": { "include": ["properties.SmFileName","properties.SmHighPS"] } ,表示properties.SmFileName和properties.SmHighPS 属性都包含在查询结果中。 * @param {Object} [options.query] 定义查询哪些属性,查询运算符将应用于这些属性。运算符包括:eq、neq、gt、lt、gte、lte、startsWith、endsWith、contains、in。其中in是Array.类型,例如:{ "SmFileName": { "eq":"B49C001002.tif" }} * @param {Array.} [options.sortby] 由包含属性名称和排序规则的对象构成的数组。 * @usage */ class ImageSearchParameter { constructor(options) { /** * @description 指定查询范围。只有具有几何对象(geometry)属性的Features,并且该几何对象与该参数指定的范围相交的 Features 才会被选择出来该参数可以包含4个数值或者6个数值,这取决于使用的坐标参考系统是否包含高程值: * 左下角坐标轴 1 的值 * 左下角坐标轴 2 的值 * 坐标轴 3 的最小值(可选) * 右上角坐标轴 1 的值 * 右上角坐标轴 2 的值 * 坐标轴 3 的最大值(可选) 坐标参考系统为 WGS 84 经度/纬度 (http://www.opengis.net/def/crs/OGC/1.3/CRS84). 对于 “WGS 84 经度/纬度” 坐标参考系统,该参数值的格式通常为:最小经度,最小纬度,最大经度,最大纬度。如果包含了高程值,该参数的格式为:最小经度,最小纬度,最小高程值,最大经度,最大纬度,最大高程值。如果一个 Feature 具有多个空间几何对象(geometry)属性,由服务器决定是否使用单一的空间几何对象属性,还是使用所有相关的几何对象作为最终的查询空间范围。 * @member {Array.} ImageSearchParameter.prototype.bbox */ this.bbox = undefined; /** * @description 影像集合的ID数组,将在该指定的Collection中搜索Items。 * @member {Array.} ImageSearchParameter.prototype.collections */ this.collections = undefined; /** * @description 返回的 Item 的 ID 值数组。设置了该参数,所有其他过滤器参数(除了next和limit)将被忽略。 * @member {Array.} ImageSearchParameter.prototype.ids */ this.ids = undefined; /** * @description 单页返回的最大结果数。最小值为1,最大值为10000。 * @member {number} ImageSearchParameter.prototype.limit */ this.limit = undefined; /** * @description 通过‘include’和‘exclude’属性分别指定哪些字段包含在查询结果的 Feature 描述中,哪些需要排除。返回结果中的stac_version,id,bbox,assets,links,geometry,type,properties这些字段为必须字段,若要返回结果中不含这种字段信息,需要显示地进行排除设置,如:排除geometry和bbox字段;在POST请求中,则需要将这些字段添加到“exclude”字段中,例如: "fields": { "exclude": ["geometry","bbox"] } } 。而对于返回的“properties”对象中的扩展字段内容,可以将字段前添加到‘include’字段中,如: "fields": { "include": ["properties.SmFileName","properties.SmHighPS"] } } ,表示properties.SmFileName和properties.SmHighPS 属性都包含在查询结果中。 * @member {FieldsFilter} ImageSearchParameter.prototype.fields */ this.fields = undefined; /** * @description 定义查询哪些属性,查询运算符将应用于这些属性。 * @member {Object} ImageSearchParameter.prototype.query */ this.query = undefined; /** * @description 由包含属性名称和排序规则的对象构成的数组。 * @member {Array.} ImageSearchParameter.prototype.sortby */ this.sortby = undefined; this.CLASS_NAME = 'SuperMap.ImageSearchParameter'; Util.extend(this, options); } /** * @function ImageSearchParameter.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.bbox = undefined; me.collections = undefined; me.ids = undefined; me.limit = undefined; me.fields = undefined; me.query = undefined; me.sortby = undefined; } /** * @function ImageSearchParameter.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {ImageSearchParameter} obj 返回的模型。 * @return {ImageSearchParameter} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new ImageSearchParameter(); if (data.hasOwnProperty('bbox')) { obj.bbox = data.bbox; } if (data.hasOwnProperty('collections')) { obj.collections = data.collections; } if (data.hasOwnProperty('ids')) { obj.ids = data.ids; } if (data.hasOwnProperty('limit')) { obj.limit = data.limit; } if (data.hasOwnProperty('fields')) { obj.fields = (FieldsFilter.constructFromObject && FieldsFilter.constructFromObject(data.fields, {})) || data.fields; } if (data.hasOwnProperty('query')) { obj.query = data.query; } if (data.hasOwnProperty('sortby')) { obj.sortby = data.sortby; if (data.sortby) { obj.sortby = data.sortby.map((item) => { return (Sortby.constructFromObject && Sortby.constructFromObject(item, {})) || item; }); } } } return obj; } } ;// CONCATENATED MODULE: ./src/common/iServer/ImageStretchOption.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageStretchOption * @deprecatedclass SuperMap.ImageStretchOption * @classdesc 影像拉伸类。 * @category iServer Image * @param {Object} options - 可选参数。 * @param {ImageStretchOption.StretchType} [options.stretchType] 影像拉伸类型。该属性的值有以下几种情况:NONE,无拉伸;GAUSSIAN,高斯拉伸;PERCENTCLIP,百分比截断拉伸;MINIMUMMAXIMUM,最值拉伸;STANDARDDEVIATION,标准差拉伸。 * @param {number} [options.stdevCoefficient] 标准差系数。 * @param {number} [options.gaussianCoefficient] 高斯系数。 * @param {boolean} [options.useMedianValue] 高斯拉伸时,是否使用中间值,若该属性值为true,表示使用中间值;false,表示使用平均值。 * @param {number} [options.minPercent] 使用百分比截断拉伸时,排除影像直方图最低值区域的像元,该参数值为这部分像元占总像元百分比。 * @param {number} [options.maxPercent] 使用百分比截断拉伸时,排除影像直方图最高值区域的像元,该参数值为这部分像元占总像元百分比。 * @usage */ class ImageStretchOption { constructor(options) { /** * @description 影像拉伸类型。该属性的值有以下几种情况:NONE,无拉伸;GAUSSIAN,高斯拉伸;PERCENTCLIP,百分比截断拉伸;MINIMUMMAXIMUM,最值拉伸;STANDARDDEVIATION,标准差拉伸。 * @member {ImageStretchOption.StretchType} ImageStretchOption.prototype.stretchType */ this.stretchType = undefined; /** * @description 标准差系数。 * @member {number} ImageStretchOption.prototype.stdevCoefficient */ this.stdevCoefficient = undefined; /** * @description 高斯系数。 * @member {number} ImageStretchOption.prototype.gaussianCoefficient */ this.gaussianCoefficient = undefined; /** * @description 高斯拉伸时,是否使用中间值,若该属性值为true,表示使用中间值;false,表示使用平均值。 * @member {boolean} ImageStretchOption.prototype.useMedianValue */ this.useMedianValue = undefined; /** * @description 使用百分比截断拉伸时,排除影像直方图最低值区域的像元,该参数值为这部分像元占总像元百分比。 * @member {number} ImageStretchOption.prototype.minPercent */ this.minPercent = undefined; /** * @description 使用百分比截断拉伸时,排除影像直方图最高值区域的像元,该参数值为这部分像元占总像元百分比。 * @member {number} ImageStretchOption.prototype.maxPercent */ this.maxPercent = undefined; this.CLASS_NAME = 'SuperMap.ImageStretchOption'; Util.extend(this, options); } /** * @function ImageStretchOption.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.stretchType = undefined; me.stdevCoefficient = undefined; me.gaussianCoefficient = undefined; me.useMedianValue = undefined; me.minPercent = undefined; me.maxPercent = undefined; } /** * @function ImageStretchOption.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {ImageStretchOption} obj 返回的模型。 * @return {ImageStretchOption} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new ImageStretchOption(); if (data.hasOwnProperty('stretchType')) { obj.stretchType = data.stretchType; } if (data.hasOwnProperty('stdevCoefficient')) { obj.stdevCoefficient = data.stdevCoefficient; } if (data.hasOwnProperty('gaussianCoefficient')) { obj.gaussianCoefficient = data.gaussianCoefficient; } if (data.hasOwnProperty('useMedianValue')) { obj.useMedianValue = data.useMedianValue; } if (data.hasOwnProperty('minPercent')) { obj.minPercent = data.minPercent; } if (data.hasOwnProperty('maxPercent')) { obj.maxPercent = data.maxPercent; } } return obj; } } /** * @enum StretchType * @description 影像拉伸类型枚举。 * @memberOf ImageStretchOption * @readonly * @type {string} */ ImageStretchOption.StretchType = { /** 无拉伸。 */ NONE: 'NONE', /** 高斯拉伸。 */ GAUSSIAN: 'GAUSSIAN', /** 百分比截断拉伸。 */ PERCENTCLIP: 'PERCENTCLIP', /** 最值拉伸。 */ MINIMUMMAXIMUM: 'MINIMUMMAXIMUM', /** 标准差拉伸。 */ STANDARDDEVIATION: 'STANDARDDEVIATION' }; ;// CONCATENATED MODULE: ./src/common/iServer/ImageRenderingRule.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageRenderingRule * @deprecatedclass SuperMap.ImageRenderingRule * @classdesc 定义请求的影像如何进行渲染或者处理,如:影像的拉伸显示方式、颜色表、波段组合以及应用栅格函数进行快速处理等。 * @category iServer Image * @param {Object} options - 可选参数。 * @param {ImageRenderingRule.DisplayMode} [options.displayMode] 影像显示模式,其中:Composite表示多波段组合显示;Stretched表示单波段拉伸显示。 * @param {string} [options.displayBands] 影像显示的波段或者波段组合。若影像的显示模式为STRETCHED,该属性指定一个波段的索引号(波段索引号从0开始计数);若影像的显示模式为COMPOSITE,该属性为组合的波段索引号,例如:属性值3,2,1表示采用4波段、3波段、2波段分别对应 R、G、B颜色通道进行组合显示。 * @param {ImageStretchOption} [options.stretchOption] 影像的拉伸参数。 * @param {ImageRenderingRule.InterpolationMode} [options.interpolationMode] 影像显示时使用的插值算法。 * @param {Array.} [options.colorScheme] 影像拉伸显示的颜色方案。颜色方案为RGBA颜色数组。RGBA是代表Red(红色)Green(绿色)Blue(蓝色)和Alpha的色彩空间。Alpha值可以省略不写,表示完全不透明。Alpha通道表示不透明度参数,若该值为0表示完全透明。例如:"255,0,0","0,255,0","0,0,255" 表示由红色、绿色、蓝色三种颜色构成的色带。 * @param {Array.} [options.colorTable] 影像的颜色表。颜色表为栅格值与RGBA颜色值的对照表。RGBA是代表Red(红色)Green(绿色)Blue(蓝色)和Alpha的色彩空间。Alpha值可以省略不写,表示完全不透明。Alpha通道表示不透明度参数,若该值为0表示完全透明。以下示例表示该颜色对照表由三组构成,第一组高程值为500,对应的颜色为红色;第二组高程值为700,对应的颜色为绿色;第三组高程值为700,对应的颜色为蓝色。示例:"500: 255,0,0", "700: 0,255,0" , "900: 0,0,255"。 * @param {number} [options.brightness] 影像显示的亮度。数值范围为-100到100,增加亮度为正,降低亮度为负。 * @param {number} [options.contrast] 影像显示的对比度。数值范围为-100到100,增加对比度为正,降低对比度为负。 * @param {string} [options.noData] 影像的无值。影像为多波段时,通过逗号分隔 R,G,B 颜色通道对应波段的无值。 * @param {string} [options.noDataColor] 影像的无值的显示颜色,支持RGB颜色,例如:255,0,0(红色),那么无值将以指定的红色显示。 * @param {boolean} [options.noDataTransparent] 无值是否透明显示,true表示透明显示无值;否则为false。 * @param {string} [options.backgroundValue] 影像的背景值。影像为多波段时,通过逗号分隔 R,G,B 颜色通道对应波段的背景值。 * @param {string} [options.backgroundColor] 指定背景值的颜色。支持指定RGB颜色,例如:255,0,0(红色),那么背景值将以指定的红色显示。 * @param {boolean} [options.backgroundTransparent] 背景值是否透明显示,true表示透明显示背景值;否则为false。 * @param {Array.} [options.gridFunctions] 栅格函数链。 * @usage */ class ImageRenderingRule { constructor(options) { /** * @description 影像显示模式,其中:Composite表示多波段组合显示;Stretched表示单波段拉伸显示。 * @member {ImageRenderingRule.DisplayMode} ImageRenderingRule.prototype.displayMode */ this.displayMode = undefined; /** * @description 影像显示的波段或者波段组合。该参数为一个数组,数组元素为波段索引号。若影像的显示模式为Stretched,该属性指定一个显示的波段;若影像的显示模式为Composite,该属性为组合的波段索引号,例如:属性值4,3,2表示采用4波段、3波段、2波段分别对应 R、G、B颜色通道进行组合显示。 * @member {string} ImageRenderingRule.prototype.displayBands */ this.displayBands = undefined; /** * @description 影像的拉伸参数。 * @member {ImageStretchOption} ImageRenderingRule.prototype.stretchOption */ this.stretchOption = undefined; /** * @description 影像显示时使用的插值算法。 * @member {ImageRenderingRule.InterpolationMode} ImageRenderingRule.prototype.interpolationMode */ this.interpolationMode = undefined; /** * @description 影像拉伸显示的颜色方案。颜色方案为RGBA颜色数组。RGBA是代表Red(红色)Green(绿色)Blue(蓝色)和Alpha的色彩空间。Alpha值可以省略不写,表示完全不透明。Alpha通道表示不透明度参数,若该值为0表示完全透明。例如:"255,0,0","0,255,0","0,0,255" 表示由红色、绿色、蓝色三种颜色构成的色带。 * @member {Array.} ImageRenderingRule.prototype.colorScheme */ this.colorScheme = undefined; /** * @description 影像的颜色表。颜色表为栅格值与RGBA颜色值的对照表。RGBA是代表Red(红色)Green(绿色)Blue(蓝色)和Alpha的色彩空间。Alpha值可以省略不写,表示完全不透明。Alpha通道表示不透明度参数,若该值为0表示完全透明。以下示例表示该颜色对照表由三组构成,第一组高程值为500,对应的颜色为红色;第二组高程值为700,对应的颜色为绿色;第三组高程值为700,对应的颜色为蓝色。示例:"500: 255,0,0", "700: 0,255,0" , "900: 0,0,255" * @member {Array.} ImageRenderingRule.prototype.colorTable */ this.colorTable = undefined; /** * @description 影像显示的亮度。数值范围为-100到100,增加亮度为正,降低亮度为负。 * @member {number} ImageRenderingRule.prototype.brightness */ this.brightness = undefined; /** * @description 影像显示的对比度。数值范围为-100到100,增加对比度为正,降低对比度为负。 * @member {number} ImageRenderingRule.prototype.contrast */ this.contrast = undefined; /** * @description 影像的无值。影像为多波段时,通过逗号分隔 R,G,B 颜色通道对应波段的无值。 * @member {string} ImageRenderingRule.prototype.noData */ this.noData = undefined; /** * @description 影像的无值的显示颜色,支持RGB颜色,例如:255,0,0(红色),那么无值将以指定的红色显示。 * @member {string} ImageRenderingRule.prototype.noDataColor */ this.noDataColor = undefined; /** * @description 无值是否透明显示,true表示透明显示无值;否则为false。 * @member {boolean} ImageRenderingRule.prototype.noDataTransparent */ this.noDataTransparent = undefined; /** * @description 影像的背景值。影像为多波段时,通过逗号分隔 R,G,B 颜色通道对应波段的背景值。 * @member {string} ImageRenderingRule.prototype.backgroundValue */ this.backgroundValue = undefined; /** * @description 指定背景值的颜色。支持指定RGB颜色,例如:255,0,0(红色),那么背景值将以指定的红色显示。 * @member {string} ImageRenderingRule.prototype.backgroundColor */ this.backgroundColor = undefined; /** * @description 背景值是否透明显示,true表示透明显示背景值;否则为false。 * @member {boolean} ImageRenderingRule.prototype.backgroundTransparent */ this.backgroundTransparent = undefined; /** * @description 栅格函数选项,通过应用栅格函数,可以对影像进行快速显示处理。 * @member {Array.} ImageRenderingRule.prototype.gridFunctions */ this.gridFunctions = undefined; this.CLASS_NAME = 'SuperMap.ImageRenderingRule'; Util.extend(this, options); } /** * @function ImageRenderingRule.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.displayMode = undefined; me.displayBands = undefined; me.stretchOption = undefined; me.interpolationMode = undefined; me.colorScheme = undefined; me.colorTable = undefined; me.brightness = undefined; me.contrast = undefined; me.noData = undefined; me.noDataColor = undefined; me.noDataTransparent = undefined; me.backgroundValue = undefined; me.backgroundColor = undefined; me.backgroundTransparent = undefined; me.gridFuncOptions = undefined; } /** * @function ImageRenderingRule.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {ImageRenderingRule} obj 返回的模型。 * @return {ImageRenderingRule} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new ImageRenderingRule(); if (data.hasOwnProperty('displayMode')) { obj.displayMode = data.displayMode; } if (data.hasOwnProperty('displayBands')) { obj.displayBands = data.displayBands; } if (data.hasOwnProperty('stretchOption')) { obj.stretchOption = (ImageStretchOption.constructFromObject && ImageStretchOption.constructFromObject(data.stretchOption, {})) || data.stretchOption; } if (data.hasOwnProperty('interpolationMode')) { obj.interpolationMode = data.interpolationMode; } if (data.hasOwnProperty('colorScheme')) { obj.colorScheme = data.colorScheme; } if (data.hasOwnProperty('colorTable')) { obj.colorTable = data.colorTable; } if (data.hasOwnProperty('brightness')) { obj.brightness = data.brightness; } if (data.hasOwnProperty('contrast')) { obj.contrast = data.contrast; } if (data.hasOwnProperty('noData')) { obj.noData = data.noData; } if (data.hasOwnProperty('noDataColor')) { obj.noDataColor = data.noDataColor; } if (data.hasOwnProperty('backgroundValue')) { obj.backgroundValue = data.backgroundValue; } if (data.hasOwnProperty('noDataTransparent')) { obj.noDataTransparent = data.noDataTransparent; } if (data.hasOwnProperty('backgroundColor')) { obj.backgroundColor = data.backgroundColor; } if (data.hasOwnProperty('backgroundTransparent')) { obj.backgroundTransparent = data.backgroundTransparent; } if (data.hasOwnProperty('gridFunctions')) { obj.gridFunctions = data.gridFunctions; } } return obj; } } /** * @enum DisplayMode * @description 影像显示模式。 * @memberOf ImageRenderingRule * @readonly * @type {string} */ ImageRenderingRule.DisplayMode = { COMPOSITE: 'COMPOSITE', STRETCHED: 'Stretched' }; /** * @enum InterpolationMode * @description 影像显示时使用的插值算法枚举。 * @memberOf ImageRenderingRule * @readonly * @type {string} */ ImageRenderingRule.InterpolationMode = { /** 最邻近插值模式。 */ NEARESTNEIGHBOR: 'NEARESTNEIGHBOR', /** 高质量的双线性插值模式。 */ HIGHQUALITYBILINEAR: 'HIGHQUALITYBILINEAR', /** 默认插值模式。 */ DEFAULT: 'DEFAULT' }; ;// CONCATENATED MODULE: ./src/common/iServer/ImageGFHillShade.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageGFHillShade * @deprecatedclass SuperMap.ImageGFHillShade * @classdesc 栅格函数对象:对DEM数据生成三维晕渲图。 * @category iServer Image * @param {Object} options - 可选参数。 * @param {string} [options.girdFuncName='GFHillShade'] 栅格函数名称,参数值为:GFHillShade。 * @param {number} [options.Azimuth = 315] 光源方位角。用于确定光源的方向,是从光源所在位置的正北方向线起,依顺时针方向到光源与目标方向线的夹角,范围为 0-360 度,以正北方向为 0 度,依顺时针方向递增。默认值为:315。 * @param {number} [options.Altitude = 45] 光源高度角。用于确定光源照射的倾斜角度,是光源与目标的方向线与水平面间的夹角,范围为 0-90 度。当光源高度角为 90 度时,光源正射地表。默认值为:45。 * @param {number} [options.ZFactor = 1] 高程缩放系数。如果设置为 1.0,表示不缩放。默认值为:1。 * @usage */ class ImageGFHillShade { constructor(options) { /** * @description 栅格函数名称,参数值为:GFHillShade。 * @member {string} ImageGFHillShade.prototype.girdFuncName * @default 'GFHillShade' */ this.girdFuncName = 'GFHillShade'; /** * @description 光源方位角。用于确定光源的方向,是从光源所在位置的正北方向线起,依顺时针方向到光源与目标方向线的夹角,范围为 0-360 度,以正北方向为 0 度,依顺时针方向递增。默认值为:315。 * @member {number} ImageGFHillShade.prototype.Azimuth */ this.Azimuth = 315; /** * @description 光源高度角。用于确定光源照射的倾斜角度,是光源与目标的方向线与水平面间的夹角,范围为 0-90 度。当光源高度角为 90 度时,光源正射地表。默认值为:45。 * @member {number} ImageGFHillShade.prototype.Altitude */ this.Altitude = 45; /** * @description 高程缩放系数。如果设置为 1.0,表示不缩放。默认值为:1。 * @member {number} ImageGFHillShade.prototype.ZFactor */ this.ZFactor = 1; this.CLASS_NAME = 'SuperMap.ImageGFHillShade'; Util.extend(this, options); } /** * @function ImageGFHillShade.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.girdFuncName = 'GFHillShade'; me.Azimuth = 315; me.Altitude = 45; me.ZFactor = 1; } /** * @function ImageGFHillShade.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {ImageGFHillShade} obj 返回的模型。 * @return {ImageGFHillShade} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new ImageGFHillShade(); if (data.hasOwnProperty('girdFuncName')) { obj.girdFuncName = data.girdFuncName } if (data.hasOwnProperty('Azimuth')) { obj.Azimuth = data.Azimuth } if (data.hasOwnProperty('Altitude')) { obj.Altitude = data.Altitude } if (data.hasOwnProperty('ZFactor')) { obj.ZFactor = data.ZFactor } } return obj; } } ;// CONCATENATED MODULE: ./src/common/iServer/ImageGFAspect.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageGFAspect * @deprecatedclass SuperMap.ImageGFAspect * @classdesc 栅格函数对象:对DEM数据生成坡向渲图。 * @category iServer Image * @param {Object} options -可选参数。 * @param {string} [options.girdFuncName='GFAspect'] 栅格函数名称,参数值为:GFAspect。 * @param {number} [options.Azimuth] 光源方位角,固定为360度。 * @usage */ class ImageGFAspect { constructor(options) { /** * @description 栅格函数名称,参数值为:GFAspect。 * @member {string} ImageGFAspect.prototype.girdFuncName * @default 'GFAspect' */ this.girdFuncName = 'GFAspect'; /** * @description 光源方位角,固定为360度。 * @member {number} ImageGFAspect.prototype.Azimuth */ this.Azimuth = undefined; this.CLASS_NAME = 'SuperMap.ImageGFAspect'; Util.extend(this, options); } /** * @function ImageGFAspect.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.girdFuncName = 'GFAspect'; me.Azimuth = undefined; } /** * @function ImageGFAspect.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {ImageGFAspect} obj 返回的模型。 * @return {ImageGFAspect} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new ImageGFAspect(); if (data.hasOwnProperty('girdFuncName')) { obj.girdFuncName = data.girdFuncName } if (data.hasOwnProperty('Azimuth')) { obj.Azimuth = data.Azimuth } } return obj; } } ;// CONCATENATED MODULE: ./src/common/iServer/ImageGFOrtho.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageGFOrtho * @deprecatedclass SuperMap.ImageGFOrtho * @classdesc 栅格函数对象:对DEM数据生成三维晕渲图。该栅格函数不需要输入参数,采用系统默认设置。 * @category iServer Image * @param {Object} options - 可选参数。 * @param {string} [options.girdFuncName='GFOrtho'] 栅格函数名称,参数值为:GFOrtho。 * @usage */ class ImageGFOrtho { constructor(options) { /** * @description 栅格函数名称,参数值为:GFOrtho。 * @member {string} ImageGFOrtho.prototype.girdFuncName * @default 'GFOrtho' */ this.girdFuncName = 'GFOrtho'; this.CLASS_NAME = 'SuperMap.ImageGFOrtho'; Util.extend(this, options); } /** * @function ImageGFOrtho.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.girdFuncName = 'GFOrtho'; } /** * @function ImageGFOrtho.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {ImageGFOrtho} obj 返回的模型。 * @return {ImageGFOrtho} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new ImageGFOrtho(); if (data.hasOwnProperty('girdFuncName')) { obj.girdFuncName = data.girdFuncName } } return obj; } } ;// CONCATENATED MODULE: ./src/common/iServer/ImageGFSlope.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageGFSlope * @deprecatedclass SuperMap.ImageGFSlope * @classdesc 栅格函数对象:对DEM数据生成坡度图。 * @category iServer Image * @param {Object} options - 可选参数。 * @param {string} [options.girdFuncName='GFSlope'] 栅格函数名称,参数值为:GFSlope。 * @param {number} [options.Altitude = 45] 光源高度角。用于确定光源照射的倾斜角度,是光源与目标的方向线与水平面间的夹角,范围为 0-90 度。当光源高度角为 90 度时,光源正射地表。默认值为:45。 * @param {number} [options.ZFactor = 1] 高程缩放系数。如果设置为 1.0,表示不缩放。默认值为:1。 * @usage */ class ImageGFSlope { constructor(options) { /** * @description 栅格函数名称,参数值为:GFSlope。 * @member {string} ImageGFSlope.prototype.girdFuncName * @default 'GFSlope' */ this.girdFuncName = 'GFSlope'; /** * @description 光源高度角。用于确定光源照射的倾斜角度,是光源与目标的方向线与水平面间的夹角,范围为 0-90 度。当光源高度角为 90 度时,光源正射地表。默认值为:45。 * @member {number} ImageGFSlope.prototype.Altitude */ this.Altitude = 45; /** * @description 高程缩放系数。如果设置为 1.0,表示不缩放。默认值为:1。 * @member {number} ImageGFSlope.prototype.ZFactor */ this.ZFactor = 1; this.CLASS_NAME = 'SuperMap.ImageGFSlope'; Util.extend(this, options); } /** * @function ImageGFSlope.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { var me = this; me.girdFuncName = 'GFSlope'; me.Altitude = 45; me.ZFactor = 1; } /** * @function ImageGFSlope.prototype.constructFromObject * @description 目标对象新增该类的可选参数。 * @param {Object} data 要转换的数据。 * @param {ImageGFSlope} obj 返回的模型。 * @return {ImageGFSlope} 返回结果。 */ static constructFromObject(data, obj) { if (data) { obj = obj || new ImageGFSlope(); if (data.hasOwnProperty('girdFuncName')) { obj.girdFuncName = data.girdFuncName } if (data.hasOwnProperty('Altitude')) { obj.Altitude = data.Altitude } if (data.hasOwnProperty('ZFactor')) { obj.ZFactor = data.ZFactor } } return obj; } } ;// CONCATENATED MODULE: ./src/common/iServer/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/online/OnlineResources.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @enum ServiceStatus * @category BaseTypes Constant * @description 服务发布状态。 * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ServiceStatus } from '{npm}'; * * const result = ServiceStatus.DOES_NOT_INVOLVE; * ``` */ var ServiceStatus = { /** 不涉及,不可发布。 */ DOES_NOT_INVOLVE: "DOES_NOT_INVOLVE", /** 发布失败。 */ PUBLISH_FAILED: "PUBLISH_FAILED", /** 已发布。 */ PUBLISHED: "PUBLISHED", /** 正在发布。 */ PUBLISHING: "PUBLISHING", /** 未发布。 */ UNPUBLISHED: "UNPUBLISHED", /** 取消服务失败。 */ UNPUBLISHED_FAILED: "UNPUBLISHED_FAILED" }; /** * @enum DataItemOrderBy * @category BaseTypes Constant * @description 数据排序字段。 * @usage * ``` * // 浏览器 * * * // ES6 Import * import { DataItemOrderBy } from '{npm}'; * * const result = DataItemOrderBy.FILENAME; * ``` */ var DataItemOrderBy = { /** 文件名。 */ FILENAME: "FILENAME", /** ID。 */ ID: "ID", /** 最后修改时间。 */ LASTMODIFIEDTIME: "LASTMODIFIEDTIME", /** 作者昵称。 */ NICKNAME: "NICKNAME", /** SERVICESTATUS。 */ SERVICESTATUS: "SERVICESTATUS", /** 大小。 */ SIZE: "SIZE", /** 状态。 */ STATUS: "STATUS", /** 类型。 */ TYPE: "TYPE", /** 更新时间。 */ UPDATETIME: "UPDATETIME", /** 作者名。 */ USERNAME: "USERNAME" }; /** * @enum FilterField {number} * @category BaseTypes Constant * @description 关键字查询时的过滤字段。 * @usage * ``` * // 浏览器 * * * // ES6 Import * import { FilterField } from '{npm}'; * * const result = FilterField.LINKPAGE; * ``` */ var FilterField = { /** 服务地址。 */ LINKPAGE: "LINKPAGE", /** 服务中包含的地图的名称。 */ MAPTITLE: "MAPTITLE", /** 服务创建者昵称。 */ NICKNAME: "NICKNAME", /** 服务名称。 */ RESTITLE: "RESTITLE", /** 服务创建者用户名。 */ USERNAME: "USERNAME" }; ;// CONCATENATED MODULE: ./src/common/online/OnlineServiceBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OnlineServiceBase * @deprecatedclass SuperMap.OnlineServiceBase * @classdesc Online 服务基类(使用 key 作为权限限制的类需要实现此类)。 * @category iPortal/Online Core * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class OnlineServiceBase { constructor(options) { options = options || {}; Util.extend(this, options); this.CLASS_NAME = "SuperMap.OnlineServiceBase"; } /** * @function OnlineServiceBase.prototype.request * @description 请求 online 服务 * @param {string} [method='GET'] - 请求方式, 'GET', 'PUT', 'POST', 'DELETE'。 * @param {string} url - 服务地址。 * @param {Object} param - URL 查询参数。 * @param {Object} [requestOptions] - http 请求参数, 比如请求头,超时时间等。 * @returns {Promise} 包含请求结果的 Promise 对象。 */ request(method, url, param, requestOptions = {}) { url = SecurityManager.appendCredential(url); requestOptions['crossOrigin'] = this.options.crossOrigin; requestOptions['headers'] = this.options.headers; return FetchRequest.commit(method, url, param, requestOptions).then(function(response) { return response.json(); }); } } ;// CONCATENATED MODULE: ./src/common/online/OnlineData.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OnlineData * @deprecatedclass SuperMap.OnlineData * @classdesc Online myData 服务。 * @category iPortal/Online Resources Data * @param {string} serviceRootUrl - 服务地址。 * @param {Object} options - 可选参数。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage * @extends OnlineServiceBase */ class OnlineData extends OnlineServiceBase { //TODO 目前并没有对接服务支持的所有操作,日后需要补充完整 constructor(serviceRootUrl, options) { super(serviceRootUrl); options = options || {}; //MD5 this.MD5 = null; //文件类型。 this.type = null; //数据上传者名称。 this.userName = null; //文件名称。 this.fileName = null; //文件大小,单位为 B 。 this.size = null; //服务发布状态。 this.serviceStatus = null; //服务 id 。 this.serviceId = null; //数据项 id 。 this.id = null; //最后修改时间。 this.lastModfiedTime = null; //文件状态。 this.status = null; //数据文件存储 id 。 this.storageId = null; //数据的发布信息。 this.publishInfo = null; //数据的权限信息。 this.authorizeSetting = null; //用户的昵称。 this.nickname = null; //数据的标签。 this.tags = []; //数据的描述信息。 this.description = null; //数据发布的服务信息集合。 this.dataItemServices = null; //数据坐标类型。 this.coordType = null; //数据审核信息 this.dataCheckResult = null; //数据元数据信息 this.dataMetaInfo = null; //数据的缩略图路径。 this.thumbnail = null; Util.extend(this, options); if (this.id) { this.serviceUrl = serviceRootUrl + "/" + this.id; } this.CLASS_NAME = "SuperMap.OnlineData"; } /** * @function OnlineData.prototype.load * @description 通过 URL 请求获取该服务完整信息。 * @returns {Promise} 不包含请求结果的 Promise 对象,请求返回结果自动填充到该类属性中。 */ load() { if (!this.serviceUrl) { return; } var me = this; return me.request("GET", this.serviceUrl).then(function (result) { Util.extend(me, result); }); } /** * @function OnlineData.prototype.getPublishedServices * @description 获取数据发布的所有服务。 * @returns {Object} 数据发布的所有服务。 */ getPublishedServices() { return this.dataItemServices; } /** * @function OnlineData.prototype.getAuthorizeSetting * @description 获取数据的权限信息。 * @returns {Object} 权限信息。 */ getAuthorizeSetting() { return this.authorizeSetting; } } ;// CONCATENATED MODULE: ./src/common/online/Online.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Online * @deprecatedclass SuperMap.Online * @classdesc 对接 SuperMap Online 所有基础服务。 * @category iPortal/Online Resources * @example * var online=new Online(); * var services = online.queryDatas(param); * service.then(function(services){ * var service= services[0]; * service.updateDataInfo(); * }) * @usage */ class Online { //TODO 目前并没有对接Online的所有操作,需要补充完整 //所有查询返回的是一个Promise,在外部使用的时候通过Promise的then方法获取异步结果 constructor() { this.rootUrl = "https://www.supermapol.com"; this.webUrl = this.rootUrl + "/web"; var mContentUrl = this.webUrl + "/mycontent"; this.mDatasUrl = mContentUrl + "/datas"; this.CLASS_NAME = "SuperMap.Online"; } /** * @function Online.prototype.load * @description 加载 online,验证 online 是否可用。 * @returns {Promise} 包含网络请求结果的 Promise 对象。 */ load() { return FetchRequest.get(this.rootUrl).then(function (response) { return response; }); } /** * @function Online.prototype.login * @description 登录Online */ login() { SecurityManager.loginOnline(this.rootUrl, true); } /** * @function Online.prototype.queryDatas * @description 查询 Online “我的内容” 下 “我的数据” 服务(需要登录状态获取),并返回可操作的服务对象。 * @param {OnlineQueryDatasParameter} parameter - myDatas 服务资源查询参数。 * @returns {Promise} 包含所有数据服务信息的 Promise 对象。 */ queryDatas(parameter) { var me = this, url = me.mDatasUrl; if (parameter) { parameter = parameter.toJSON(); } return FetchRequest.get(url, parameter).then(function (json) { if (!json || !json.content || json.content.length < 1) { return; } var services = [], contents = json.content, len = contents.length; for (var i = 0; i < len; i++) { var content = contents[i]; var service = new OnlineData(me.mDatasUrl, content); services.push(service); } return services; }); } } ;// CONCATENATED MODULE: ./src/common/online/OnlineQueryDatasParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OnlineQueryDatasParameter * @deprecatedclass SuperMap.OnlineQueryDatasParameter * @classdesc myDatas 服务资源查询参数。 * @category iPortal/Online Resources Data * @param {Object} options - 参数。 * @usage */ class OnlineQueryDatasParameter { constructor(options) { options = options || {}; /** * @member {Array.} OnlineQueryDatasParameter.prototype.userNames * @description 数据作者名。可以根据数据作者名查询,默认查询全部。 */ this.userNames = null; /** * @member {Array.} OnlineQueryDatasParameter.prototype.types * @description 数据类型。 */ this.types = null; /** * @member {string} OnlineQueryDatasParameter.prototype.fileName * @description 文件名称。 */ this.fileName = null; /** * @member {string} OnlineQueryDatasParameter.prototype.serviceStatuses * @description 服务发布状态。 */ this.serviceStatuses = null; /** * @member {string} OnlineQueryDatasParameter.prototype.serviceId * @description 服务 ID。 */ this.serviceId = null; /** * @member {Array.} OnlineQueryDatasParameter.prototype.ids * @description 由数据项 ID 组成的整型数组。 */ this.ids = null; /** * @member {Array.} OnlineQueryDatasParameter.prototype.keywords * @description 关键字。 */ this.keywords = null; /** * @member {string} OnlineQueryDatasParameter.prototype.orderBy * @description 排序字段。 */ this.orderBy = null; /** * @member {Array.} OnlineQueryDatasParameter.prototype.tags * @description 数据的标签。 */ this.tags = null; /** * @member {Array.} OnlineQueryDatasParameter.prototype.filterFields * @description 用于关键字查询时的过滤字段。 */ this.filterFields = null; Util.extend(this, options) this.CLASS_NAME = "SuperMap.OnlineQueryDatasParameter"; } /** * @function OnlineQueryDatasParameter.prototype.toJSON * @description 返回对应的 JSON 对象。 * @returns {Object} 对应的 JSON 对象。 */ toJSON() { var me = this; var jsonObj = { "types": me.types, "fileName": me.fileName, "serviceStatuses": me.serviceStatuses, "serviceId": me.serviceId, "ids": me.ids, "keywords": me.keywords, "orderBy": me.orderBy, "tags": me.tags, "filterFields": me.filterFields }; for (var key in jsonObj) { if (jsonObj[key] == null) { delete jsonObj[key] } } return jsonObj; } } ;// CONCATENATED MODULE: ./src/common/online/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/security/KeyServiceParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class KeyServiceParameter * @deprecatedclass SuperMap.KeyServiceParameter * @classdesc key申请参数 * @category Security * @param {Object} options - 参数。 * @param {string} options.name - 申请服务名称。 * @param {number} options.serviceIds - 服务 ID。 * @param {ClientType} [options.clientType=ClientType.SERVER] - 服务端类型。 * @param {number} options.limitation - 有效期 * @usage */ class KeyServiceParameter { constructor(options) { this.name = null; this.serviceIds = null; this.clientType = ClientType.SERVER; this.limitation = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.KeyServiceParameter"; } /** * @function KeyServiceParameter.prototype.toJSON * @description 转换成 JSON 对象 * @returns {Object} 参数的 JSON 对象 */ toJSON() { return { name: this.name, serviceIds: this.serviceIds, clientType: this.clientType, limitation: this.limitation } } } ;// CONCATENATED MODULE: ./src/common/security/ServerInfo.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ServerInfo * @deprecatedclass SuperMap.ServerInfo * @classdesc 服务器信息(安全相关),包含服务器类型,服务地址,token服务地址等。 * @category Security * @param {string} type - 服务器类型。 * @param {Object} options - 参数。 * @param {string} options.server - 服务器地址,如:http://supermapiserver:8090/iserver。 * @param {string} [options.tokenServiceUrl] - 如:http://supermapiserver:8090/iserver/services/security/tokens.json。 * @param {string} [options.keyServiceUrl] - 如:http://supermapiserver:8092/web/mycontent/keys/register.json。 * @usage */ class ServerInfo { constructor(type, options) { /** * @member {ServerType} ServerInfo.prototype.type * @description 服务器类型。 */ this.type = type; /** * @member {string} ServerInfo.prototype.server * @description 服务器地址。 */ this.server = null; /** * @member {string} [ServerInfo.prototype.tokenServiceUrl] * @description 如:http://supermapiserver:8090/iserver/services/security/tokens.json。 */ this.tokenServiceUrl = null; /** * @member {string} [ServerInfo.prototype.keyServiceUrl] * @description 如:http://supermapiserver:8092/web/mycontent/keys/register.json。 */ this.keyServiceUrl = null; Util.extend(this, options); this.CLASS_NAME = "SuperMap.ServerInfo"; this.type = this.type || ServerType.ISERVER; if (!this.server) { console.error('server url require is not undefined') } // var patten = /http:\/\/([^\/]+)/i; //this.server = this.server.match(patten)[0]; var tokenServiceSuffix = "/services/security/tokens"; if (this.type === ServerType.ISERVER && this.server.indexOf("iserver") < 0) { tokenServiceSuffix = "/iserver" + tokenServiceSuffix; } if (!this.tokenServiceUrl) { this.tokenServiceUrl = Util.urlPathAppend(this.server, tokenServiceSuffix); } if (!this.keyServiceUrl) { if (this.type === ServerType.IPORTAL) { this.keyServiceUrl = Util.urlPathAppend(this.server, "/web/mycontent/keys/register"); } else if (this.type === ServerType.ONLINE) { this.keyServiceUrl = Util.urlPathAppend(this.server, "/web/mycontent/keys"); } } } } ;// CONCATENATED MODULE: ./src/common/security/TokenServiceParameter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TokenServiceParameter * @deprecatedclass SuperMap.TokenServiceParameter * @classdesc token 申请参数。 * @category Security * @param {Object} options - 参数。 * @param {string} options.username - 用户名。 * @param {string} options.password - 密码。 * @param {ClientType} [options.clientType='ClientType.NONE'] - token 申请的客户端标识类型。 * @param {string} [options.ip] - clientType=IP 时,此为必选参数。 * @param {string} [options.referer] -clientType=Referer 时,此为必选参数。如果按照指定 URL 的方式申请令牌,则设置相应的 URL。 * @param {number} [options.expiration=60] - 申请令牌的有效期,从发布令牌的时间开始计算,单位为分钟。 * @usage * */ class TokenServiceParameter { constructor(options) { /** * @member {string} TokenServiceParameter.prototype.userName * @description 用户名。 */ this.userName = null; /** * @member {string} TokenServiceParameter.prototype.password * @description 密码。 */ this.password = null; /** * @member {ClientType} TokenServiceParameter.prototype.clientType * @description token 申请的客户端标识类型。 */ this.clientType = ClientType.NONE; /** * @member {string} [TokenServiceParameter.prototype.ip] * @description clientType=IP 时,此为必选参数。 */ this.ip = null; /** * @member {string} [TokenServiceParameter.prototype.referer] * @description clientType=Referer 时,此为必选参数。如果按照指定 URL 的方式申请令牌,则设置相应的 URL。 */ this.referer = null; /** * @member {number} TokenServiceParameter.prototype.expiration * @description 申请令牌的有效期,从发布令牌的时间开始计算,单位为分钟。 */ this.expiration = 60; Util.extend(this, options); this.CLASS_NAME = "SuperMap.TokenServiceParameter"; } /** * @function TokenServiceParameter.prototype.toJSON * @description 将所有信息转成 JSON 字符串。 * @returns {string} 参数的 JSON 字符串。 */ toJSON() { return { userName: this.userName, password: this.password, clientType: this.clientType, ip: this.ip, referer: this.referer, expiration: this.expiration } } } ;// CONCATENATED MODULE: ./src/common/security/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: external "function(){try{return elasticsearch}catch(e){return {}}}()" const external_function_try_return_elasticsearch_catch_e_return_namespaceObject = function(){try{return elasticsearch}catch(e){return {}}}(); var external_function_try_return_elasticsearch_catch_e_return_default = /*#__PURE__*/__webpack_require__.n(external_function_try_return_elasticsearch_catch_e_return_namespaceObject); ;// CONCATENATED MODULE: ./src/common/thirdparty/elasticsearch/ElasticSearch.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ElasticSearch * @deprecatedclass SuperMap.ElasticSearch * @classdesc ElasticSearch服务类。 * @category ElasticSearch * @param {string} url - ElasticSearch服务地址。 * @param {Object} options - 参数。 * @param {function} [options.change] - 服务器返回数据后执行的函数。废弃,不建议使用。使用search或msearch方法。 * @param {boolean} [options.openGeoFence=false] - 是否开启地理围栏验证,默认为不开启。 * @param {function} [options.outOfGeoFence] - 数据超出地理围栏后执行的函数。 * @param {Object} [options.geoFence] - 地理围栏。 * @description *

11.1.0

* 该功能依赖@elastic/elasticsearch, webpack5或其他不包含Node.js Polyfills的打包工具,需要加入相关配置,以webpack为例:

首先安装相关Polyfills

npm i stream-http  https-browserify stream-browserify tty-browserify browserify-zlib os-browserify buffer url assert process -D
然后配置webpack
module.exports: {
    resolve: {
      alias: {
        process: 'process/browser',
      },
      mainFields: ['browser', 'main'],
      fallback: {
        fs: false,
        http: require.resolve('stream-http'),
        https: require.resolve('https-browserify'),
        os: require.resolve('os-browserify/browser'),
        stream: require.resolve('stream-browserify'),
        tty: require.resolve('tty-browserify'),
        zlib: require.resolve('browserify-zlib')
      }
    }
    plugins: [
      new webpack.ProvidePlugin({
        process: 'process/browser',
        Buffer: ['buffer', 'Buffer']
      }),
    ]
}
* @usage */ class ElasticSearch { constructor(url, options) { options = options || {}; /** * @member {string} ElasticSearch.prototype.url * @description ElasticSearch服务地址。 */ this.url = url; /** * @member {Object} ElasticSearch.prototype.client * @description client ES客户端。 */ try { // 老版本 this.client = new (external_function_try_return_elasticsearch_catch_e_return_default()).Client({ host: this.url }); } catch (e) { // 新版本 this.client = new (external_function_try_return_elasticsearch_catch_e_return_default()).Client({ node: { url: new URL(this.url) } }); } /** * @deprecated * @member {function} [ElasticSearch.prototype.change] * @description 服务器返回数据后执行的函数。废弃,不建议使用。使用search或msearch方法。 */ this.change = null; /** * @member {boolean} [ElasticSearch.prototype.openGeoFence=false] * @description 是否开启地理围栏验证,默认为不开启。 */ this.openGeoFence = false; /** * @member {function} [ElasticSearch.prototype.outOfGeoFence] * @description 数据超出地理围栏后执行的函数。 */ this.outOfGeoFence = null; /** * @member {Object} [ElasticSearch.prototype.geoFence] * @description 地理围栏。 * @example { * radius: 1000,//单位是m * center: [104.40, 30.43], * unit: 'meter|degree' * } */ this.geoFence = null; /* * Constant: EVENT_TYPES * {Array.} * 此类支持的事件类型。 * */ this.EVENT_TYPES = ['change', 'error', 'outOfGeoFence']; /** * @member {Events} ElasticSearch.prototype.events * @description 事件。 */ this.events = new Events(this, null, this.EVENT_TYPES); /** * @member {Object} ElasticSearch.prototype.eventListeners * @description 监听器对象,在构造函数中设置此参数(可选),对 MapService 支持的两个事件 processCompleted 、processFailed 进行监听, * 相当于调用 Events.on(eventListeners)。 */ this.eventListeners = null; Util.extend(this, options); if (this.eventListeners instanceof Object) { this.events.on(this.eventListeners); } } /** * @function ElasticSearch.prototype.setGeoFence * @description 设置地理围栏,openGeoFence参数为true的时候,设置的地理围栏才生效。 * @param {Geometry} geoFence - 地理围栏。 */ setGeoFence(geoFence) { this.geoFence = geoFence; } /** * @function ElasticSearch.prototype.bulk * @description 批量操作API,允许执行多个索引/删除操作。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-bulk}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ bulk(params, callback) { return this.client.bulk(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.clearScroll * @description 通过指定scroll参数进行查询来清除已经创建的scroll请求。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-clearscroll}
*更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ clearScroll(params, callback) { return this.client.clearScroll(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.count * @description 获取集群、索引、类型或查询的文档个数。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-count}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ count(params, callback) { return this.client.count(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.create * @description 在特定索引中添加一个类型化的JSON文档,使其可搜索。如果具有相同index,type且ID已经存在的文档将发生错误。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-create} * 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html} * @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ create(params, callback) { return this.client.create(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.delete * @description 根据其ID从特定索引中删除键入的JSON文档。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-delete}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ delete(params, callback) { return this.client.delete(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.deleteByQuery * @description 根据其ID从特定索引中删除键入的JSON文档。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-deletebyquery}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ deleteByQuery(params, callback) { return this.client.deleteByQuery(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.deleteScript * @description 根据其ID删除脚本。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-deletescript}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ deleteScript(params, callback) { return this.client.deleteScript(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.deleteTemplate * @description 根据其ID删除模板。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-deletetemplate}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ deleteTemplate(params, callback) { return this.client.deleteTemplate(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.exists * @description 检查给定文档是否存在。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-exists}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ exists(params, callback) { return this.client.exists(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.existsSource * @description 检查资源是否存在。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-existssource}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ existsSource(params, callback) { return this.client.existsSource(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.explain * @description 提供与特定查询相关的特定文档分数的详细信息。它还会告诉您文档是否与指定的查询匹配。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-explain}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ explain(params, callback) { return this.client.explain(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.fieldCaps * @description 允许检索多个索引之间的字段的功能。(实验性API,可能会在未来版本中删除)
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-fieldcaps}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ fieldCaps(params, callback) { return this.client.fieldCaps(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.get * @description 从索引获取一个基于其ID的类型的JSON文档。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-get}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ get(params, callback) { return this.client.get(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.getScript * @description 获取脚本。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-getscript}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ getScript(params, callback) { return this.client.getScript(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.getSource * @description 通过索引,类型和ID获取文档的源。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-getsource}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ getSource(params, callback) { return this.client.getSource(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.getTemplate * @description 获取模板。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-gettemplate}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ getTemplate(params, callback) { return this.client.getTemplate(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.index * @description 在索引中存储一个键入的JSON文档,使其可搜索。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-index}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ index(params, callback) { return this.client.index(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.info * @description 从当前集群获取基本信息。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-info}
* 更多信息参考 {@link https://www.elastic.co/guide/index.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ info(params, callback) { return this.client.info(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.mget * @description 根据索引,类型(可选)和ids来获取多个文档。mget所需的主体可以采用两种形式:文档位置数组或文档ID数组。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-mget}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ mget(params, callback) { return this.client.mget(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.msearch * @description 在同一请求中执行多个搜索请求。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-msearch}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html}
* @param {Object} params - 参数。 * @param {function} callback - 请求返回的回调函数。也可以使用then表达式获取返回结果。 * 回调参数:error,response,结果存储在response.responses中。 */ msearch(params, callback) { let me = this; return me.client.msearch(params) .then(function (resp) { resp = resp.body || resp; me._update(resp.responses, callback); return resp; }, function (err) { callback(err); me.events.triggerEvent('error', {error: err}); return err; }); } /** * @function ElasticSearch.prototype.msearchTemplate * @description 在同一请求中执行多个搜索模板请求。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-msearchtemplate}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ msearchTemplate(params, callback) { return this.client.msearchTemplate(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.mtermvectors * @description 多termvectors API允许一次获得多个termvectors。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-mtermvectors}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-termvectors.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ mtermvectors(params, callback) { return this.client.mtermvectors(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.ping * @description 测试连接。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-ping}
* 更多信息参考 {@link https://www.elastic.co/guide/index.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ ping(params, callback) { return this.client.ping(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.putScript * @description 添加脚本。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-putscript}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ putScript(params, callback) { return this.client.putScript(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.putTemplate * @description 添加模板。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-puttemplate}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ putTemplate(params, callback) { return this.client.putTemplate(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.reindex * @description 重新索引。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-reindex}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ reindex(params, callback) { return this.client.reindex(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.reindexRessrottle * @description 重新索引。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-reindexrethrottle}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ reindexRessrottle(params, callback) { return this.client.reindexRessrottle(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.renderSearchTemplate * @description 搜索模板。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-rendersearchtemplate}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ renderSearchTemplate(params, callback) { return this.client.renderSearchTemplate(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.scroll * @description 在search()调用中指定滚动参数之后,滚动搜索请求(检索下一组结果)。
* 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-scroll}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ scroll(params, callback) { return this.client.scroll(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.search * @description 在search()调用中指定滚动参数之后,滚动搜索请求(检索下一组结果)。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-search}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html}
* @param {Object} params - 参数。 * @param {function} callback - 请求返回的回调函数。也可以使用then表达式获取返回结果。 * 回调参数:error,response,结果存储在response.responses中。 */ search(params, callback) { let me = this; return me.client.search(params) .then(function (resp) { resp = resp.body || resp; me._update(resp, callback); return resp; }, function (err) { callback && callback(err); me.events.triggerEvent('error', {error: err}); return err; }); } /** * @function ElasticSearch.prototype.searchShards * @description 返回要执行搜索请求的索引和分片。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-searchshards}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-shards.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ searchShards(params, callback) { return this.client.searchShards(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.searchTemplate * @description 搜索模板。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-searchtemplate}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ searchTemplate(params, callback) { return this.client.searchTemplate(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.suggest * @description 该建议功能通过使用特定的建议者,基于所提供的文本来建议类似的术语。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-suggest}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ suggest(params, callback) { return this.client.suggest(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.termvectors * @description 返回有关特定文档字段中的术语的信息和统计信息。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-termvectors}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-termvectors.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ termvectors(params, callback) { return this.client.termvectors(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.update * @description 更新文档的部分。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-update}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ update(params, callback) { return this.client.update(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype.updateByQuery * @description 通过查询API来更新文档。 * 参数设置参考 {@link https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-updatebyquery}
* 更多信息参考 {@link https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html}
* @param {Object} params - 参数。 * @param {function} callback - 回调函数。 */ updateByQuery(params, callback) { return this.client.updateByQuery(params, this._handleCallback(callback)); } /** * @function ElasticSearch.prototype._handleCallback * @description 处理ElasticSearch 16.x和5.x的callback兼容。 5.x的回调参数多包了一层body * @param {function} callback - 回调函数。 * @private */ _handleCallback(callback) { return function () { let args = Array.from(arguments); const error = args.shift(); let resp = args.shift(); const body = resp && resp.body; if (body) { const { statusCode, headers } = resp; args = [statusCode, headers]; resp = body; } callback.call(this, error, resp, ...args); }; } _update(data, callback) { let me = this; if (!data) { return; } me.data = data; if (me.openGeoFence && me.geoFence) { me._validateDatas(data); } me.events.triggerEvent('change', {data: me.data}); //change方法已废弃,不建议使用。建议使用search方法的第二个参数传入请求成功的回调 if (me.change) { me.change && me.change(data); } else { //加responses是为了保持跟原来es自身的数据结构一致 callback && callback(undefined, {responses: data}); } } _validateDatas(datas) { if (!datas) { return; } if (!(datas instanceof Array)) { datas = [datas]; } var i, len = datas.length; for (i = 0; i < len; i++) { this._validateData(datas[i]); } } _validateData(data) { let me = this; data.hits.hits.map(function (source) { let content = source._source; let meterUnit = me._getMeterPerMapUnit(me.geoFence.unit); let geoFenceCX = me.geoFence.center[0] * meterUnit; let geoFenceCY = me.geoFence.center[1] * meterUnit; let contentX = content.x * meterUnit; let contentY = content.y * meterUnit; let distance = me._distance(contentX, contentY, geoFenceCX, geoFenceCY); let radius = me.geoFence.radius; if (distance > radius) { me.outOfGeoFence && me.outOfGeoFence(data); me.events.triggerEvent('outOfGeoFence', {data: data}); } return source; }); } _distance(x1, y1, x2, y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } _getMeterPerMapUnit(mapUnit) { let earchRadiusInMeters = 6378137; let meterPerMapUnit; if (mapUnit === 'meter') { meterPerMapUnit = 1; } else if (mapUnit === 'degree') { // 每度表示多少米。 meterPerMapUnit = Math.PI * 2 * earchRadiusInMeters / 360; } return meterPerMapUnit; } } ;// CONCATENATED MODULE: ./src/common/thirdparty/elasticsearch/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/thirdparty/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Util.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Tool.Util * @category Visualization Theme * LevelRenderer 基础工具类 * */ class Util_Util { constructor() { /** * @member {Object} LevelRenderer.Tool.Util.prototype.BUILTIN_OBJECT * @description 用于处理merge时无法遍历Date等对象的问题 */ this.BUILTIN_OBJECT = { '[object Function]': 1, '[object RegExp]': 1, '[object Date]': 1, '[object Error]': 1, '[object CanvasGradient]': 1 }; /** * @member {Object} LevelRenderer.Tool.Util.prototype._ctx */ this._ctx = null; /** * Property: _canvas * {Object} */ this._canvas = null; /** * Property: _pixelCtx * {Object} */ this._pixelCtx = null; /** * Property: _width * {Object} */ this._width = null; /** * Property: _height * {Object} */ this._height = null; /** * Property: _offsetX * {Object} */ this._offsetX = 0; /** * Property: _offsetY * {Object} */ this._offsetY = 0; this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Util"; } /** * @function LevelRenderer.Tool.Util.prototype.clone * @description 对一个object进行深度拷贝。 * * @param {Object} source - 需要进行拷贝的对象。 * @return {Object} 拷贝后的新对象。 */ clone(source) { var BUILTIN_OBJECT = this.BUILTIN_OBJECT; if (typeof source == 'object' && source !== null) { var result = source; if (source instanceof Array) { result = []; for (var i = 0, len = source.length; i < len; i++) { result[i] = this.clone(source[i]); } } else if (!BUILTIN_OBJECT[Object.prototype.toString.call(source)]) { result = {}; for (var key in source) { if (source.hasOwnProperty(key)) { result[key] = this.clone(source[key]); } } } return result; } return source; } /** * @function LevelRenderer.Tool.Util.prototype.mergeItem * @description 合并源对象的单个属性到目标对象。 * * @param {Object} target - 目标对象。 * @param {Object} source - 源对象。 * @param {string} key - 键。 * @param {boolean} overwrite - 是否覆盖。 * @return {Object} 目标对象 */ mergeItem(target, source, key, overwrite) { var BUILTIN_OBJECT = this.BUILTIN_OBJECT; if (source.hasOwnProperty(key)) { if (typeof target[key] == 'object' && !BUILTIN_OBJECT[Object.prototype.toString.call(target[key])] ) { // 如果需要递归覆盖,就递归调用merge this.merge( target[key], source[key], overwrite ); } else if (overwrite || !(key in target)) { // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况 target[key] = source[key]; } } } /** * @function LevelRenderer.Tool.Util.prototype.merge * @description 合并源对象的属性到目标对象。 * * @param {Object} target - 目标对象。 * @param {Object} source - 源对象。 * @param {boolean} overwrite - 是否覆盖。 * @return {Object} 目标对象。 */ merge(target, source, overwrite) { for (var i in source) { this.mergeItem(target, source, i, overwrite); } return target; } /** * @function LevelRenderer.Tool.Util.prototype.getContext * @description 获取 Canvas 上下文。 * @return {Object} 上下文。 */ getContext() { if (!this._ctx) { this._ctx = document.createElement('canvas').getContext('2d'); } return this._ctx; } /** * @function LevelRenderer.Tool.Util.prototype.getPixelContext * @description 获取像素拾取专用的上下文。 * @return {Object} 像素拾取专用的上下文。 */ getPixelContext() { if (!this._pixelCtx) { this._canvas = document.createElement('canvas'); this._width = this._canvas.width; this._height = this._canvas.height; this._pixelCtx = this._canvas.getContext('2d'); } return this._pixelCtx; } /** * @function LevelRenderer.Tool.Util.prototype.adjustCanvasSize * @description 如果坐标处在_canvas外部,改变_canvas的大小,修改canvas的大小 需要重新设置translate * * @param {number} x - 横坐标。 * @param {number} y - 纵坐标。 * */ adjustCanvasSize(x, y) { var _canvas = this._canvas; var _pixelCtx = this._pixelCtx; var _width = this._width; var _height = this._height; var _offsetX = this._offsetX; var _offsetY = this._offsetY; // 每次加的长度 var _v = 100; var _flag; if (x + _offsetX > _width) { _width = x + _offsetX + _v; _canvas.width = _width; _flag = true; } if (y + _offsetY > _height) { _height = y + _offsetY + _v; _canvas.height = _height; _flag = true; } if (x < -_offsetX) { _offsetX = Math.ceil(-x / _v) * _v; _width += _offsetX; _canvas.width = _width; _flag = true; } if (y < -_offsetY) { _offsetY = Math.ceil(-y / _v) * _v; _height += _offsetY; _canvas.height = _height; _flag = true; } if (_flag) { _pixelCtx.translate(_offsetX, _offsetY); } } /** * @function LevelRenderer.Tool.Util.prototype.getPixelOffset * @description 获取像素canvas的偏移量。 * @return {Object} 偏移量。 */ getPixelOffset() { return { x: this._offsetX, y: this._offsetY }; } /** * @function LevelRenderer.Tool.Util.prototype.indexOf * @description 查询数组中元素的index * @return {Object} 偏移量。 */ indexOf(array, value) { if (array.indexOf) { return array.indexOf(value); } for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } return -1; } /** * @function LevelRenderer.Tool.Util.prototype.inherits * @description 构造类继承关系 * * @param {function} clazz - 源类。 * @param {function} baseClazz - 基类。 * @return {Object} 偏移量。 */ inherits(clazz, baseClazz) { var clazzPrototype = clazz.prototype; function F() { } F.prototype = baseClazz.prototype; clazz.prototype = new F(); for (var prop in clazzPrototype) { clazz.prototype[prop] = clazzPrototype[prop]; } clazz.constructor = clazz; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Color.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Tool.Color * @category Visualization Theme * @classdesc LevelRenderer 工具-颜色辅助类 * @private */ class Color { constructor() { /** * @member {LevelRenderer.Tool.Util} LevelRenderer.Tool.Color.prototype.util * @description LevelRenderer 基础工具对象。 */ this.util = new Util_Util(); /** * @member {Object} LevelRenderer.Tool.Color.prototype._ctx * @description _ctx。 */ this._ctx = null; /** * @member {Array.} LevelRenderer.Tool.Color.prototype.palette * @description 默认色板。色板是一个包含图表默认颜色系列的数组,当色板中所有颜色被使用过后,又将从新回到色板中的第一个颜色。 */ this.palette = [ '#ff9277', ' #dddd00', ' #ffc877', ' #bbe3ff', ' #d5ffbb', '#bbbbff', ' #ddb000', ' #b0dd00', ' #e2bbff', ' #ffbbe3', '#ff7777', ' #ff9900', ' #83dd00', ' #77e3ff', ' #778fff', '#c877ff', ' #ff77ab', ' #ff6600', ' #aa8800', ' #77c7ff', '#ad77ff', ' #ff77ff', ' #dd0083', ' #777700', ' #00aa00', '#0088aa', ' #8400dd', ' #aa0088', ' #dd0000', ' #772e00' ]; /** * @member {Array.} LevelRenderer.Tool.Color.prototype._palette * @description 复位色板,用于复位 palette */ this._palette = this.palette; /** * @member {string} LevelRenderer.Tool.Color.prototype.highlightColor * @description 高亮色 */ this.highlightColor = 'rgba(0,0,255,1)'; /** * @member {string} LevelRenderer.Tool.Color.prototype._highlightColor * @description 复位高亮色 */ this._highlightColor = this.highlightColor; /** * @member {string} LevelRenderer.Tool.Color.prototype.colorRegExp * @description 颜色格式,正则表达式。 */ this.colorRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i; /** * @member {string} LevelRenderer.Tool.Color.prototype._nameColors * @description 颜色名。 */ this._nameColors = { aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#0ff', aquamarine: '#7fffd4', azure: '#f0ffff', beige: '#f5f5dc', bisque: '#ffe4c4', black: '#000', blanchedalmond: '#ffebcd', blue: '#00f', blueviolet: '#8a2be2', brown: '#a52a2a', burlywood: '#deb887', cadetblue: '#5f9ea0', chartreuse: '#7fff00', chocolate: '#d2691e', coral: '#ff7f50', cornflowerblue: '#6495ed', cornsilk: '#fff8dc', crimson: '#dc143c', cyan: '#0ff', darkblue: '#00008b', darkcyan: '#008b8b', darkgoldenrod: '#b8860b', darkgray: '#a9a9a9', darkgrey: '#a9a9a9', darkgreen: '#006400', darkkhaki: '#bdb76b', darkmagenta: '#8b008b', darkolivegreen: '#556b2f', darkorange: '#ff8c00', darkorchid: '#9932cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkslategrey: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0', forestgreen: '#228b22', fuchsia: '#f0f', gainsboro: '#dcdcdc', ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', grey: '#808080', green: '#008000', greenyellow: '#adff2f', honeydew: '#f0fff0', hotpink: '#ff69b4', indianred: '#cd5c5c', indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', lavender: '#e6e6fa', lavenderblush: '#fff0f5', lawngreen: '#7cfc00', lemonchiffon: '#fffacd', lightblue: '#add8e6', lightcoral: '#f08080', lightcyan: '#e0ffff', lightgoldenrodyellow: '#fafad2', lightgray: '#d3d3d3', lightgrey: '#d3d3d3', lightgreen: '#90ee90', lightpink: '#ffb6c1', lightsalmon: '#ffa07a', lightseagreen: '#20b2aa', lightskyblue: '#87cefa', lightslategray: '#789', lightslategrey: '#789', lightsteelblue: '#b0c4de', lightyellow: '#ffffe0', lime: '#0f0', limegreen: '#32cd32', linen: '#faf0e6', magenta: '#f0f', maroon: '#800000', mediumaquamarine: '#66cdaa', mediumblue: '#0000cd', mediumorchid: '#ba55d3', mediumpurple: '#9370d8', mediumseagreen: '#3cb371', mediumslateblue: '#7b68ee', mediumspringgreen: '#00fa9a', mediumturquoise: '#48d1cc', mediumvioletred: '#c71585', midnightblue: '#191970', mintcream: '#f5fffa', mistyrose: '#ffe4e1', moccasin: '#ffe4b5', navajowhite: '#ffdead', navy: '#000080', oldlace: '#fdf5e6', olive: '#808000', olivedrab: '#6b8e23', orange: '#ffa500', orangered: '#ff4500', orchid: '#da70d6', palegoldenrod: '#eee8aa', palegreen: '#98fb98', paleturquoise: '#afeeee', palevioletred: '#d87093', papayawhip: '#ffefd5', peachpuff: '#ffdab9', peru: '#cd853f', pink: '#ffc0cb', plum: '#dda0dd', powderblue: '#b0e0e6', purple: '#800080', red: '#f00', rosybrown: '#bc8f8f', royalblue: '#4169e1', saddlebrown: '#8b4513', salmon: '#fa8072', sandybrown: '#f4a460', seagreen: '#2e8b57', seashell: '#fff5ee', sienna: '#a0522d', silver: '#c0c0c0', skyblue: '#87ceeb', slateblue: '#6a5acd', slategray: '#708090', slategrey: '#708090', snow: '#fffafa', springgreen: '#00ff7f', steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8', tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee', wheat: '#f5deb3', white: '#fff', whitesmoke: '#f5f5f5', yellow: '#ff0', yellowgreen: '#9acd32' }; this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Color"; } /** * @function LevelRenderer.Tool.Color.prototype.customPalette * @description 自定义调色板。 * @param {Array.} userPalete - 颜色板。 */ customPalette(userPalete) { this.palette = userPalete; } /** * @function LevelRenderer.Tool.Color.prototype.resetPalette * @description 复位默认色板。 */ resetPalette() { this.palette = this._palette; } /** * @function LevelRenderer.Tool.Color.prototype.getColor * @description 获取色板颜色。 * @param {number} idx - 色板位置。 * @param {Array.} userPalete - 色板。 * @returns {string} 颜色值。 */ getColor(idx, userPalete) { idx = idx | 0; userPalete = userPalete || this.palette; return userPalete[idx % userPalete.length]; } /** * @function LevelRenderer.Tool.Color.prototype.customHighlight * @description 自定义默认高亮颜色。 * @param {string} userHighlightColor - 自定义高亮色。 */ customHighlight(userHighlightColor) { this.highlightColor = userHighlightColor; } /** * @function LevelRenderer.Tool.Color.prototype.resetHighlight * @description 重置默认高亮颜色。将当前的高亮色作为默认高亮颜色 */ resetHighlight() { this.highlightColor = this._highlightColor; } /** * @function LevelRenderer.Tool.Color.prototype.getHighlightColor * @description 获取默认高亮颜色 * @returns {string} 颜色值。 */ getHighlightColor() { return this.highlightColor; } /** * @function LevelRenderer.Tool.Color.prototype.getRadialGradient * @description 径向渐变。 * @param {number} x0 - 渐变起点横坐标。 * @param {number} y0 - 渐变起点纵坐标。 * @param {number} r0 - 半径 * @param {number} x1 - 渐变终点横坐标。 * @param {number} y1 - 渐变终点纵坐标。 * @param {number} r1 - 半径 * @param {Array} colorList - 颜色列表。 * @returns {CanvasGradient} Cavans 渐变颜色。 */ getRadialGradient(x0, y0, r0, x1, y1, r1, colorList) { var util = this.util; if (!this._ctx) { this._ctx = util.getContext(); } var gradient = this._ctx.createRadialGradient(x0, y0, r0, x1, y1, r1); for (var i = 0, l = colorList.length; i < l; i++) { gradient.addColorStop(colorList[i][0], colorList[i][1]); } gradient.__nonRecursion = true; return gradient; } /** * @function LevelRenderer.Tool.Color.prototype.getLinearGradient * @description 线性渐变。 * @param {number} x0 - 渐变起点横坐标。 * @param {number} y0 - 渐变起点纵坐标。 * @param {number} x1 - 渐变终点横坐标。 * @param {number} y1 - 渐变终点纵坐标。 * @param {Array} colorList - 颜色列表。 * @returns {CanvasGradient} Cavans 渐变颜色。 */ getLinearGradient(x0, y0, x1, y1, colorList) { var util = this.util; if (!this._ctx) { this._ctx = util.getContext(); } var gradient = this._ctx.createLinearGradient(x0, y0, x1, y1); for (var i = 0, l = colorList.length; i < l; i++) { gradient.addColorStop(colorList[i][0], colorList[i][1]); } gradient.__nonRecursion = true; return gradient; } /** * @function LevelRenderer.Tool.Color.prototype.getStepColors * @description 获取两种颜色之间渐变颜色数组。 * @param {Object} start - 起始颜色对象。 * @param {Object} end - 结束颜色对象。 * @param {number} step - 渐变级数。 * @returns {Array} 颜色数组。 */ getStepColors(start, end, step) { start = this.toRGBA(start); end = this.toRGBA(end); start = this.getData(start); end = this.getData(end); var colors = []; var stepR = (end[0] - start[0]) / step; var stepG = (end[1] - start[1]) / step; var stepB = (end[2] - start[2]) / step; var stepA = (end[3] - start[3]) / step; // 生成颜色集合 // fix by linfeng 颜色堆积 for (var i = 0, r = start[0], g = start[1], b = start[2], a = start[3]; i < step; i++) { colors[i] = this.toColor([ this.adjust(Math.floor(r), [0, 255]), this.adjust(Math.floor(g), [0, 255]), this.adjust(Math.floor(b), [0, 255]), a.toFixed(4) - 0 ], 'rgba'); r += stepR; g += stepG; b += stepB; a += stepA; } r = end[0]; g = end[1]; b = end[2]; a = end[3]; colors[i] = this.toColor([r, g, b, a], 'rgba'); return colors; } /** * @function LevelRenderer.Tool.Color.prototype.getGradientColors * @description 获取指定级数的渐变颜色数组。 * @param {Array.} colors - 颜色数组。 * @param {number} [step=20] - 渐变级数。 * @returns {Array.} 颜色数组。 */ getGradientColors(colors, step) { var ret = []; var len = colors.length; if (step === undefined) { step = 20; } if (len === 1) { ret = this.getStepColors(colors[0], colors[0], step); } else if (len > 1) { for (var i = 0, n = len - 1; i < n; i++) { var steps = this.getStepColors(colors[i], colors[i + 1], step); if (i < n - 1) { steps.pop(); } ret = ret.concat(steps); } } return ret; } /** * @function LevelRenderer.Tool.Color.prototype.toColor * @description 颜色值数组转为指定格式颜色。 * @param {Array} data - 颜色值数组。 * @param {string} format - 格式,默认'rgb' * @returns {string} 颜色。 */ toColor(data, format) { format = format || 'rgb'; if (data && (data.length === 3 || data.length === 4)) { data = this.map(data, function (c) { return c > 1 ? Math.ceil(c) : c; } ); if (format.indexOf('hex') > -1) { return '#' + ((1 << 24) + (data[0] << 16) + (data[1] << 8) + (+data[2])).toString(16).slice(1); } else if (format.indexOf('hs') > -1) { var sx = this.map(data.slice(1, 3), function (c) { return c + '%'; } ); data[1] = sx[0]; data[2] = sx[1]; } if (format.indexOf('a') > -1) { if (data.length === 3) { data.push(1); } data[3] = this.adjust(data[3], [0, 1]); return format + '(' + data.slice(0, 4).join(',') + ')'; } return format + '(' + data.slice(0, 3).join(',') + ')'; } } /** * @function LevelRenderer.Tool.Color.prototype.toArray * @description 颜色字符串转换为rgba数组。 * @param {string} color - 颜色。 * @returns {Array.} 颜色值数组。 */ toArray(color) { color = this.trim(color); if (color.indexOf('rgba') < 0) { color = this.toRGBA(color); } var data = []; var i = 0; color.replace(/[\d.]+/g, function (n) { if (i < 3) { n = n | 0; } else { // Alpha n = +n; } data[i++] = n; }); return data; } /** * @function LevelRenderer.Tool.Color.prototype.convert * @description 颜色格式转化。 * @param {Array} data - 颜色值数组。 * @param {string} format - 格式,默认'rgb' * @returns {string} 颜色。 */ convert(color, format) { if (!this.isCalculableColor(color)) { return color; } var data = this.getData(color); var alpha = data[3]; if (typeof alpha === 'undefined') { alpha = 1; } if (color.indexOf('hsb') > -1) { data = this._HSV_2_RGB(data); } else if (color.indexOf('hsl') > -1) { data = this._HSL_2_RGB(data); } if (format.indexOf('hsb') > -1 || format.indexOf('hsv') > -1) { data = this._RGB_2_HSB(data); } else if (format.indexOf('hsl') > -1) { data = this._RGB_2_HSL(data); } data[3] = alpha; return this.toColor(data, format); } /** * @function LevelRenderer.Tool.Color.prototype.toRGBA * @description 转换为rgba格式的颜色。 * @param {string} color - 颜色。 * @returns {string} 颜色。 */ toRGBA(color) { return this.convert(color, 'rgba'); } /** * @function LevelRenderer.Tool.Color.prototype.toRGB * @description 转换为rgb数字格式的颜色。 * @param {string} color - 颜色。 * @returns {string} 颜色。 */ toRGB(color) { return this.convert(color, 'rgb'); } /** * @function LevelRenderer.Tool.Color.prototype.toHex * @description 转换为16进制颜色。 * @param {string} color - 颜色。 * @returns {string} 16进制颜色,#rrggbb格式 */ toHex(color) { return this.convert(color, 'hex'); } /** * @function LevelRenderer.Tool.Color.prototype.toHSVA * @description 转换为HSV颜色。 * @param {string} color - 颜色。 * @returns {string} HSVA颜色,hsva(h,s,v,a) */ toHSVA(color) { return this.convert(color, 'hsva'); } /** * @function LevelRenderer.Tool.Color.prototype.toHSV * @description 转换为HSV颜色。 * @param {string} color - 颜色。 * @returns {string} HSV颜色,hsv(h,s,v) */ toHSV(color) { return this.convert(color, 'hsv'); } /** * @function LevelRenderer.Tool.Color.prototype.toHSBA * @description 转换为HSBA颜色。 * @param {string} color - 颜色。 * @returns {string} HSBA颜色,hsba(h,s,b,a) */ toHSBA(color) { return this.convert(color, 'hsba'); } /** * @function LevelRenderer.Tool.Color.prototype.toHSB * @description 转换为HSB颜色。 * @param {string} color - 颜色。 * @returns {string} HSB颜色,hsb(h,s,b) */ toHSB(color) { return this.convert(color, 'hsb'); } /** * @function LevelRenderer.Tool.Color.prototype.toHSLA * @description 转换为HSLA颜色。 * @param {string} color - 颜色。 * @returns {string} HSLA颜色,hsla(h,s,l,a) */ toHSLA(color) { return this.convert(color, 'hsla'); } /** * @function LevelRenderer.Tool.Color.prototype.toHSL * @description 转换为HSL颜色。 * @param {string} color - 颜色。 * @returns {string} HSL颜色,hsl(h,s,l) */ toHSL(color) { return this.convert(color, 'hsl'); } /** * @function LevelRenderer.Tool.Color.prototype.toName * @description 转换颜色名。 * @param {string} color - 颜色。 * @returns {string} 颜色名 */ toName(color) { for (var key in this._nameColors) { if (this.toHex(this._nameColors[key]) === this.toHex(color)) { return key; } } return null; } /** * @function LevelRenderer.Tool.Color.prototype.trim * @description 移除颜色中多余空格。 * @param {string} color - 颜色。 * @returns {string} 无空格颜色 */ trim(color) { return String(color).replace(/\s+/g, ''); } /** * @function LevelRenderer.Tool.Color.prototype.normalize * @description 颜色规范化。 * @param {string} color - 颜色。 * @returns {string} 规范化后的颜色 */ normalize(color) { // 颜色名 if (this._nameColors[color]) { color = this._nameColors[color]; } // 去掉空格 color = this.trim(color); // hsv与hsb等价 color = color.replace(/hsv/i, 'hsb'); // rgb转为rrggbb if (/^#[\da-f]{3}$/i.test(color)) { color = parseInt(color.slice(1), 16); var r = (color & 0xf00) << 8; var g = (color & 0xf0) << 4; var b = color & 0xf; color = '#' + ((1 << 24) + (r << 4) + r + (g << 4) + g + (b << 4) + b).toString(16).slice(1); } // 或者使用以下正则替换,不过 chrome 下性能相对差点 // color = color.replace(/^#([\da-f])([\da-f])([\da-f])$/i, '#$1$1$2$2$3$3'); return color; } /** * @function LevelRenderer.Tool.Color.prototype.lift * @description 颜色加深或减淡,当level>0加深,当level<0减淡。 * @param {string} color - 颜色。 * @param {number} level - 升降程度,取值区间[-1,1]。 * @returns {string} 加深或减淡后颜色值 */ lift(color, level) { if (!this.isCalculableColor(color)) { return color; } var direct = level > 0 ? 1 : -1; if (typeof level === 'undefined') { level = 0; } level = Math.abs(level) > 1 ? 1 : Math.abs(level); color = this.toRGB(color); var data = this.getData(color); for (var i = 0; i < 3; i++) { if (direct === 1) { data[i] = data[i] * (1 - level) | 0; } else { data[i] = ((255 - data[i]) * level + data[i]) | 0; } } return 'rgb(' + data.join(',') + ')'; } /** * @function LevelRenderer.Tool.Color.prototype.reverse * @description 颜色翻转。[255-r,255-g,255-b,1-a] * @param {string} color - 颜色。 * @returns {string} 翻转颜色 */ reverse(color) { if (!this.isCalculableColor(color)) { return color; } var data = this.getData(this.toRGBA(color)); data = this.map(data, function (c) { return 255 - c; } ); return this.toColor(data, 'rgb'); } /** * @function LevelRenderer.Tool.Color.prototype.mix * @description 简单两种颜色混合 * @param {string} color1 - 第一种颜色。 * @param {string} color2 - 第二种颜色。 * @param {number} weight - 混合权重[0-1]。 * @returns {string} 结果色。rgb(r,g,b)或rgba(r,g,b,a) */ mix(color1, color2, weight) { if (!this.isCalculableColor(color1) || !this.isCalculableColor(color2)) { return color1; } if (typeof weight === 'undefined') { weight = 0.5; } weight = 1 - this.adjust(weight, [0, 1]); var w = weight * 2 - 1; var data1 = this.getData(this.toRGBA(color1)); var data2 = this.getData(this.toRGBA(color2)); var d = data1[3] - data2[3]; var weight1 = (((w * d === -1) ? w : (w + d) / (1 + w * d)) + 1) / 2; var weight2 = 1 - weight1; var data = []; for (var i = 0; i < 3; i++) { data[i] = data1[i] * weight1 + data2[i] * weight2; } var alpha = data1[3] * weight + data2[3] * (1 - weight); alpha = Math.max(0, Math.min(1, alpha)); if (data1[3] === 1 && data2[3] === 1) {// 不考虑透明度 return this.toColor(data, 'rgb'); } data[3] = alpha; return this.toColor(data, 'rgba'); } /** * @function LevelRenderer.Tool.Color.prototype.random * @description 随机颜色 * @returns {string} 颜色值,#rrggbb格式 */ random() { return '#' + Math.random().toString(16).slice(2, 8); } /** * @function LevelRenderer.Tool.Color.prototype.getData * @description 获取颜色值数组,返回值范围。 * RGB 范围[0-255] * HSL/HSV/HSB 范围[0-1] * A透明度范围[0-1] * 支持格式: * #rgb * #rrggbb * rgb(r,g,b) * rgb(r%,g%,b%) * rgba(r,g,b,a) * hsb(h,s,b) // hsv与hsb等价 * hsb(h%,s%,b%) * hsba(h,s,b,a) * hsl(h,s,l) * hsl(h%,s%,l%) * hsla(h,s,l,a) * @param {string} color - 颜色。 * @returns {Array.} 颜色值数组或null */ getData(color) { color = this.normalize(color); var r = color.match(this.colorRegExp); if (r === null) { throw new Error('The color format error'); // 颜色格式错误 } var d; var a; var data = []; var rgb; if (r[2]) { // #rrggbb d = r[2].replace('#', '').split(''); rgb = [d[0] + d[1], d[2] + d[3], d[4] + d[5]]; data = this.map(rgb, function (c) { return Color.prototype.adjust.call(this, parseInt(c, 16), [0, 255]); } ); } else if (r[4]) { // rgb rgba var rgba = (r[4]).split(','); a = rgba[3]; rgb = rgba.slice(0, 3); data = this.map( rgb, function (c) { c = Math.floor( c.indexOf('%') > 0 ? parseInt(c, 0) * 2.55 : c ); return Color.prototype.adjust.call(this, c, [0, 255]); } ); if (typeof a !== 'undefined') { data.push(this.adjust(parseFloat(a), [0, 1])); } } else if (r[5] || r[6]) { // hsb hsba hsl hsla var hsxa = (r[5] || r[6]).split(','); var h = parseInt(hsxa[0], 0) / 360; var s = hsxa[1]; var x = hsxa[2]; a = hsxa[3]; data = this.map([s, x], function (c) { return Color.prototype.adjust.call(this, parseFloat(c) / 100, [0, 1]); } ); data.unshift(h); if (typeof a !== 'undefined') { data.push(this.adjust(parseFloat(a), [0, 1])); } } return data; } /** * @function LevelRenderer.Tool.Color.prototype.alpha * @description 设置颜色透明度 * @param {string} color - 颜色。 * @param {number} a - 透明度,区间[0,1]。 * @returns {string} rgba颜色值 */ alpha(color, a) { if (!this.isCalculableColor(color)) { return color; } if (a === null) { a = 1; } var data = this.getData(this.toRGBA(color)); data[3] = this.adjust(Number(a).toFixed(4), [0, 1]); return this.toColor(data, 'rgba'); } /** * @function LevelRenderer.Tool.Color.prototype.map * @description 数组映射 * @param {Array} array - 数组。 * @param {function} fun - 函数。 * @returns {string} 数组映射结果 */ map(array, fun) { if (typeof fun !== 'function') { throw new TypeError(); } var len = array ? array.length : 0; for (var i = 0; i < len; i++) { array[i] = fun(array[i]); } return array; } /** * @function LevelRenderer.Tool.Color.prototype.adjust * @description 调整值区间 * @param {Array.} value - 数组。 * @param {Array.} region - 区间。 * @returns {number} 调整后的值 */ adjust(value, region) { // < to <= & > to >= // modify by linzhifeng 2014-05-25 because -0 == 0 if (value <= region[0]) { value = region[0]; } else if (value >= region[1]) { value = region[1]; } return value; } /** * @function LevelRenderer.Tool.Color.prototype.isCalculableColor * @description 判断是否是可计算的颜色 * @param {string} color - 颜色。 * @returns {boolean} 是否是可计算的颜色 */ isCalculableColor(color) { return color instanceof Array || typeof color === 'string'; } /** * @function LevelRenderer.Tool.Color.prototype._HSV_2_RGB。参见{@link http://www.easyrgb.com/index.php?X=MATH} */ _HSV_2_RGB(data) { var H = data[0]; var S = data[1]; var V = data[2]; // HSV from 0 to 1 var R; var G; var B; if (S === 0) { R = V * 255; G = V * 255; B = V * 255; } else { var h = H * 6; if (h === 6) { h = 0; } var i = h | 0; var v1 = V * (1 - S); var v2 = V * (1 - S * (h - i)); var v3 = V * (1 - S * (1 - (h - i))); var r = 0; var g = 0; var b = 0; if (i === 0) { r = V; g = v3; b = v1; } else if (i === 1) { r = v2; g = V; b = v1; } else if (i === 2) { r = v1; g = V; b = v3; } else if (i === 3) { r = v1; g = v2; b = V; } else if (i === 4) { r = v3; g = v1; b = V; } else { r = V; g = v1; b = v2; } // RGB results from 0 to 255 R = r * 255; G = g * 255; B = b * 255; } return [R, G, B]; } /** * @function LevelRenderer.Tool.Color.prototype._HSL_2_RGB。参见{@link http://www.easyrgb.com/index.php?X=MATH} */ _HSL_2_RGB(data) { var H = data[0]; var S = data[1]; var L = data[2]; // HSL from 0 to 1 var R; var G; var B; if (S === 0) { R = L * 255; G = L * 255; B = L * 255; } else { var v2; if (L < 0.5) { v2 = L * (1 + S); } else { v2 = (L + S) - (S * L); } var v1 = 2 * L - v2; R = 255 * this._HUE_2_RGB(v1, v2, H + (1 / 3)); G = 255 * this._HUE_2_RGB(v1, v2, H); B = 255 * this._HUE_2_RGB(v1, v2, H - (1 / 3)); } return [R, G, B]; } /** * @function LevelRenderer.Tool.Color.prototype._HUE_2_RGB。参见{@link http://www.easyrgb.com/index.php?X=MATH} */ _HUE_2_RGB(v1, v2, vH) { if (vH < 0) { vH += 1; } if (vH > 1) { vH -= 1; } if ((6 * vH) < 1) { return (v1 + (v2 - v1) * 6 * vH); } if ((2 * vH) < 1) { return (v2); } if ((3 * vH) < 2) { return (v1 + (v2 - v1) * ((2 / 3) - vH) * 6); } return v1; } /** * @function LevelRenderer.Tool.Color.prototype._RGB_2_HSB。参见{@link http://www.easyrgb.com/index.php?X=MATH} */ _RGB_2_HSB(data) { // RGB from 0 to 255 var R = (data[0] / 255); var G = (data[1] / 255); var B = (data[2] / 255); var vMin = Math.min(R, G, B); // Min. value of RGB var vMax = Math.max(R, G, B); // Max. value of RGB var delta = vMax - vMin; // Delta RGB value var V = vMax; var H; var S; // HSV results from 0 to 1 if (delta === 0) { H = 0; S = 0; } else { S = delta / vMax; var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta; var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta; var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta; if (R === vMax) { H = deltaB - deltaG; } else if (G === vMax) { H = (1 / 3) + deltaR - deltaB; } else if (B === vMax) { H = (2 / 3) + deltaG - deltaR; } if (H < 0) { H += 1; } if (H > 1) { H -= 1; } } H = H * 360; S = S * 100; V = V * 100; return [H, S, V]; } /** * @function LevelRenderer.Tool.Color.prototype._RGB_2_HSL。参见{@link http://www.easyrgb.com/index.php?X=MATH} */ _RGB_2_HSL(data) { // RGB from 0 to 255 var R = (data[0] / 255); var G = (data[1] / 255); var B = (data[2] / 255); var vMin = Math.min(R, G, B); // Min. value of RGB var vMax = Math.max(R, G, B); // Max. value of RGB var delta = vMax - vMin; // Delta RGB value var L = (vMax + vMin) / 2; var H; var S; // HSL results from 0 to 1 if (delta === 0) { H = 0; S = 0; } else { if (L < 0.5) { S = delta / (vMax + vMin); } else { S = delta / (2 - vMax - vMin); } var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta; var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta; var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta; if (R === vMax) { H = deltaB - deltaG; } else if (G === vMax) { H = (1 / 3) + deltaR - deltaB; } else if (B === vMax) { H = (2 / 3) + deltaG - deltaR; } if (H < 0) { H += 1; } if (H > 1) { H -= 1; } } H = H * 360; S = S * 100; L = L * 100; return [H, S, L]; } } ;// CONCATENATED MODULE: ./src/common/util/ColorsPickerUtil.js var ColorRender = new Color(); // let "http://www.qzu.zj.cn": "#bd10e0" // "www.qzct.net": "#7ed321" = new LevelRenderer.Tool.Color(); /** * @name ColorsPickerUtil * @namespace * @category BaseTypes Util * @classdesc 色带选择器工具类。用于1、创建canvas对象,2、从几种颜色中获取一定数量的渐变色。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { ColorsPickerUtil } from '{npm}'; * * const result = ColorsPickerUtil.createCanvas(); * ``` */ class ColorsPickerUtil { /** * @function ColorsPickerUtil.createCanvas * @description 创建DOM canvas。 * @param {number} height - canvas 高度。 * @param {number} width - canvas 宽度。 */ static createCanvas (height, width){ var canvas = document.createElement("canvas"); canvas.height = height; canvas.width = width; return canvas.getContext("2d"); } /** * @function ColorsPickerUtil.getLinearGradient * @description 线性渐变。 * @param {number} x0 - 渐变起点 x 坐标。 * @param {number} y0 - 渐变起点 y 坐标。 * @param {number} x1 - 渐变终点 x 坐标。 * @param {number} y1 - 渐变终点 y 坐标。 * @param {Array} colorList 颜色列表。 * @returns {CanvasGradient} Cavans 渐变颜色。 */ static getLinearGradient (x0, y0, x1, y1, colorList){ if (!this._ctx) { this._ctx = this.getContext(); } var gradient = this._ctx.createLinearGradient(x0, y0, x1, y1); var leng = colorList.length; var add = 1/(leng -1); var offset = 0; for (var i = 0; i < leng; i++) { gradient.addColorStop(offset, colorList[i]); offset += add; } gradient.__nonRecursion = true; return gradient; } /** * @function ColorsPickerUtil.getContext * @description 获取 Cavans 上下文。 * @returns {Object} Cavans 上下文。 */ static getContext () { if (!this._ctx) { this._ctx = document.createElement('canvas').getContext('2d'); } return this._ctx; } /** * @function ColorsPickerUtil.getStepColors * @description 获取两种颜色之间渐变颜色数组。 * @param {string} start - 起始颜色。 * @param {string} end - 结束颜色。 * @param {number} step - 渐变级数。 * @returns {Array} 颜色数组。 */ static getStepColors (start, end, step){ start = ColorRender.toRGBA(start); end = ColorRender.toRGBA(end); start = ColorRender.getData(start); end = ColorRender.getData(end); var colors = []; var stepR = (end[0] - start[0]) / step; var stepG = (end[1] - start[1]) / step; var stepB = (end[2] - start[2]) / step; var stepA = (end[3] - start[3]) / step; // 生成颜色集合 // fix by linfeng 颜色堆积 for (var i = 0, r = start[0], g = start[1], b = start[2], a = start[3]; i < step; i++) { colors[i] = ColorRender.toColor([ ColorRender.adjust(Math.floor(r), [ 0, 255 ]), ColorRender.adjust(Math.floor(g), [ 0, 255 ]), ColorRender.adjust(Math.floor(b), [ 0, 255 ]), a.toFixed(4) - 0 ],'hex'); r += stepR; g += stepG; b += stepB; a += stepA; } r = end[0]; g = end[1]; b = end[2]; a = end[3]; colors[i] = ColorRender.toColor([r, g, b, a], 'hex'); return colors; } /** * @function ColorsPickerUtil.getGradientColors * @description 获取指定级数的渐变颜色数组。 * @param {Array.} colors - 颜色组。 * @param {number} total - 颜色总数。 * @param {string} themeType - 专题类型。 * @returns {Array.} 颜色数组。 */ static getGradientColors (colors, total, themeType){ var ret = [], step; var i, n, len = colors.length; if (total === undefined) { return; } if(len >= total){ if(themeType === 'RANGE'){ for(i = 0; i * * * // ES6 Import * import { ArrayStatistic } from '{npm}'; * * const result = ArrayStatistic.newInstance(); * ``` */ class ArrayStatistic { // geostatsInstance: null, /** * @function ArrayStatistic.newInstance * @description 初始化插件实例。 */ static newInstance() { // if(!this.geostatsInstance) { // // this.geostatsInstance = new geostats(); // // } // window.dataList = []; if(!this.geostatsInstance) { this.geostatsInstance = new window.geostats(); } return this.geostatsInstance; } /** * @function ArrayStatistic.getInstance * @description 设置需要被处理的数组。 * @param {Array} array - 数组。 */ static getInstance(array) { let instance = this.newInstance(); instance.setSerie(array); return instance; } /** * @function ArrayStatistic.getArrayStatistic * @description 获取数组统计的值。 * @param {Array.} array - 需要统计的数组。 * @param {string} type - 统计方法。 */ static getArrayStatistic(array, type){ if(!array.length) { return 0; } if(type === "Sum" || type === "求和"){ return this.getSum(array); } else if(type === "Maximum" || type === "最大值"){ return this.getMax(array); } else if(type === "Minimum" || type === "最小值"){ return this.getMin(array); } else if(type === "Average" || type === "平均值"){ return this.getMean(array); } else if(type === "Median" || type === "中位数"){ return this.getMedian(array); } else if(type === "times" || type === "计数"){ return this.getTimes(array); } } /** * @function ArrayStatistic.getArraySegments * @description 获取数组分段后的数值。 * @param {Array.} array - 需要分段的数组。 * @param {string} type - 分段方法。 * @param {number} segNum - 分段个数。 */ static getArraySegments(array, type, segNum) { if(type === "offset") { return this.getEqInterval(array, segNum); } else if(type === "jenks") { return this.getJenks(array, segNum); } else if(type === "square") { // 数据都必须 >= 0 let minValue = this.getMin(array); if(minValue >= 0){ return this.getSqrtInterval(array, segNum); }else { //console.log('数据都必须 >= 0'); // Util.showMessage(Language.hasNegValue + Language.noSupportRange, 'ERROR'); return false; } } else if(type === "logarithm") { // 数据都必须 > 0 let minValue = this.getMin(array); if(minValue > 0){ return this.getGeometricProgression(array, segNum); }else { //console.log('数据都必须 > 0'); // Util.showMessage(Language.hasZeroNegValue + Language.noSupportRange, 'ERROR'); return false; } } } /** * @function ArrayStatistic.getSum * @description 求和。 * @param {Array.} array 需要求和的参数。 * @returns {number} 返回求和结果。 */ static getSum(array){ return this.getInstance(array).sum(); } /** * @function ArrayStatistic.getMax * @description 最大值。 * @param {Array.} array 需要求最大值的参数。 * @returns {number} 返回最大值。 */ static getMax(array){ return this.getInstance(array).max(); } /** * @function ArrayStatistic.getMin * @description 最小值。 * @param {Array.} array 需要求最小值的参数。 * @returns {number} 返回最小值。 */ static getMin(array){ return this.getInstance(array).min(); } /** * @function ArrayStatistic.getMean * @description 求平均数。 * @param {Array.} array 需要求平均数的参数。 * @returns {number} 返回平均数。 */ static getMean(array){ return this.getInstance(array).mean(); } /** * @function ArrayStatistic.getMedian * @description 求中位数。 * @param {Array.} array 需要求中位数的参数。 * @returns {number} 返回中位数。 */ static getMedian(array) { return this.getInstance(array).median(); } /** * @function ArrayStatistic.getTimes * @description 计数。 * @param {Array.} array 需要计数的参数。 * @returns {number} 返回计数结果。 */ static getTimes(array) { return array.length; } /** * @function ArrayStatistic.getEqInterval * @description 等距分段法。 * @param {Array} array 需要进行等距分段的数组。 * @param {number} segNum 分段个数。 */ static getEqInterval(array, segNum) { return this.getInstance(array).getClassEqInterval(segNum); } /** * @function ArrayStatistic.getJenks * @description 自然断裂法。 * @param {Array} array 需要进行自然断裂的参数。 * @param {number} segNum 分段个数。 */ static getJenks(array, segNum) { return this.getInstance(array).getClassJenks(segNum); } /** * @function ArrayStatistic.getSqrtInterval * @description 平方根分段法。 * @param {Array} array 需要进行平方根分段的参数。 * @param {number} segNum 分段个数。 */ static getSqrtInterval(array, segNum) { array = array.map(function(value) { return Math.sqrt(value); }); let breaks = this.getInstance(array).getClassEqInterval(segNum); return ( breaks.map(function(value) { return value * value; }) ) } /** * @function ArrayStatistic.getGeometricProgression * @description 对数分段法。 * @param {Array} array 需要进行对数分段的参数。 * @param {number} segNum 分段个数。 */ static getGeometricProgression(array, segNum) { return this.getInstance(array).getClassGeometricProgression(segNum); } } ;// CONCATENATED MODULE: ./src/common/util/MapCalculateUtil.js /** * @function getMeterPerMapUnit * @description 单位换算,把米|度|千米|英寸|英尺换成米。 * @category BaseTypes Util * @param {string} mapUnit 地图单位。 * @returns {number} 返回地图的距离单位。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { getMeterPerMapUnit } from '{npm}'; * * const result = getMeterPerMapUnit(mapUnit); * ``` */ var getMeterPerMapUnit = function(mapUnit) { var earchRadiusInMeters = 6378137; var meterPerMapUnit; if (mapUnit === Unit.METER) { meterPerMapUnit = 1; } else if (mapUnit === Unit.DEGREE) { // 每度表示多少米。 meterPerMapUnit = (Math.PI * 2 * earchRadiusInMeters) / 360; } else if (mapUnit === Unit.KILOMETER) { meterPerMapUnit = 1.0e-3; } else if (mapUnit === Unit.INCH) { meterPerMapUnit = 1 / 2.5399999918e-2; } else if (mapUnit === Unit.FOOT) { meterPerMapUnit = 0.3048; } else { return meterPerMapUnit; } return meterPerMapUnit; }; /** * @function getWrapNum * @description 获取该坐标系的经纬度范围的经度或纬度。 * @category BaseTypes Util * @param {number} x 经度或纬度。 * @param {boolean} includeMax 是否获取经度或纬度的最大值。 * @param {boolean} includeMin 是否获取经度或纬度的最小值。 * @param {number} range 坐标系的经纬度范围。 * @returns {number} 返回经度或纬度的值。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { getWrapNum } from '{npm}'; * * const result = getWrapNum(x, includeMax, includeMin, range); * ``` */ function getWrapNum(x, includeMax = true, includeMin = true, range = [-180, 180]) { var max = range[1], min = range[0], d = max - min; if (x === max && includeMax) { return x; } if (x === min && includeMin) { return x; } var tmp = (((x - min) % d) + d) % d; if (tmp === 0 && includeMax) { return max; } return ((((x - min) % d) + d) % d) + min; } /** * @function conversionDegree * @description 转换经纬度。 * @category BaseTypes Util * @param {number} degrees 经度或纬度。 * @returns {string} 返回度分秒。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { conversionDegree } from '{npm}'; * * const result = conversionDegree(degrees); * ``` */ function conversionDegree(degrees) { const degree = parseInt(degrees); let fraction = parseInt((degrees - degree) * 60); let second = parseInt(((degrees - degree) * 60 - fraction) * 60); fraction = parseInt(fraction / 10) === 0 ? `0${fraction}` : fraction; second = parseInt(second / 10) === 0 ? `0${second}` : second; return `${degree}°${fraction}'${second}`; } /** * @function scalesToResolutions * @description 通过比例尺数组计算分辨率数组,没有传入比例尺数组时通过地图范围与地图最大级别进行计算。 * @version 11.0.1 * @param {Array} scales - 比例尺数组。 * @param {Object} bounds - 地图范围。 * @param {number} dpi - 屏幕分辨率。 * @param {string} mapUnit - 地图单位。 * @param {number} [level=22] - 地图最大级别。 * @returns {number} 分辨率。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { scalesToResolutions } from '{npm}'; * * const result = scalesToResolutions(scales, bounds, dpi, mapUnit); * ``` */ function scalesToResolutions(scales, bounds, dpi, mapUnit, level = 22) { var resolutions = []; if (scales && scales.length > 0) { for (let i = 0; i < scales.length; i++) { resolutions.push(scaleToResolution(scales[i], dpi, mapUnit)); } } else { const maxReolution = Math.abs(bounds.left - bounds.right) / 256; for (let i = 0; i < level; i++) { resolutions.push(maxReolution / Math.pow(2, i)); } } return resolutions.sort(function (a, b) { return b - a; }); } /** * @function getZoomByResolution * @description 通过分辨率获取地图级别。 * @version 11.0.1 * @param {number} resolution - 分辨率。 * @param {Array} resolutions - 分辨率数组。 * @returns {number} 地图级别。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { getZoomByResolution } from '{npm}'; * * const result = getZoomByResolution(resolution, resolutions); * ``` */ function getZoomByResolution(resolution, resolutions) { let zoom = 0; let minDistance; for (let i = 0; i < resolutions.length; i++) { if (i === 0) { minDistance = Math.abs(resolution - resolutions[i]); } if (minDistance > Math.abs(resolution - resolutions[i])) { minDistance = Math.abs(resolution - resolutions[i]); zoom = i; } } return zoom; } /** * @function scaleToResolution * @description 通过比例尺计算分辨率。 * @version 11.0.1 * @param {number} scale - 比例尺。 * @param {number} dpi - 屏幕分辨率。 * @param {string} mapUnit - 地图单位。 * @returns {number} 分辨率。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { scaleToResolution } from '{npm}'; * * const result = scaleToResolution(scale, dpi, mapUnit); * ``` */ function scaleToResolution(scale, dpi, mapUnit) { const inchPerMeter = 1 / 0.0254; const meterPerMapUnitValue = getMeterPerMapUnit(mapUnit); const resolution = 1 / (scale * dpi * inchPerMeter * meterPerMapUnitValue); return resolution; } /** * 范围是否相交 * @param {Extent} extent1 范围1 * @param {Extent} extent2 范围2 * @return {boolean} 范围是否相交。 */ function intersects(extent1, extent2) { return ( extent1[0] <= extent2[2] && extent1[2] >= extent2[0] && extent1[1] <= extent2[3] && extent1[3] >= extent2[1] ); } /** * 获取两个范围的交集 * @param {Array} extent1 Extent 1 * @param {Array} extent2 Extent 2 * @return {Array} 相交范围数组. * @api */ function getIntersection(extent1, extent2) { const intersection = []; if (intersects(extent1, extent2)) { if (extent1[0] > extent2[0]) { intersection[0] = extent1[0]; } else { intersection[0] = extent2[0]; } if (extent1[1] > extent2[1]) { intersection[1] = extent1[1]; } else { intersection[1] = extent2[1]; } if (extent1[2] < extent2[2]) { intersection[2] = extent1[2]; } else { intersection[2] = extent2[2]; } if (extent1[3] < extent2[3]) { intersection[3] = extent1[3]; } else { intersection[3] = extent2[3]; } } return intersection; } ;// CONCATENATED MODULE: ./src/common/util/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ // EXTERNAL MODULE: ./node_modules/lodash.topairs/index.js var lodash_topairs = __webpack_require__(52); var lodash_topairs_default = /*#__PURE__*/__webpack_require__.n(lodash_topairs); ;// CONCATENATED MODULE: ./src/common/style/CartoCSS.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class CartoCSS * @deprecatedclass SuperMap.CartoCSS * @classdesc CartoCSS 解析类,其主要功能为将 CartoCSS 字符串解析为 CartoCSS 的 shader 属性风格对象。 * @category BaseTypes Style * @param {string} cartoStr - 样式表字符串。 * @example * var cartocss = "@provinceLineColor:#ddd; * #China_Provinces_L___China400{ * line-dasharray:10,10; * line-color:@provinceLineColor; * line-width:1; * }"; * new CartoCSS(cartocss); * @usage */ /*eslint no-useless-escape: "off"*/ class CartoCSS { constructor(cartoStr) { this.env = null; /** * @member CartoCSS.prototype.parser * @description 解析器。 */ this.parser = null; /** * @member CartoCSS.prototype.ruleSet * @description CartoCSS 规则对象。 */ this.ruleSet = null; /** * @member CartoCSS.prototype.cartoStr * @description CartoCSS 样式表字符串。 */ this.cartoStr = ""; /** * @member CartoCSS.prototype.shaders * @description Carto 着色器集。 */ this.shaders = null; if (typeof cartoStr === "string") { this.cartoStr = cartoStr; this.env = { frames: [], errors: [], error: function (obj) { this.errors.push(obj); } }; this.parser = this.getParser(this.env); this.parse(cartoStr); this.shaders = this.toShaders(); } } /** * @function CartoCSS.prototype.getParser * @description 获取 CartoCSS 解析器。 */ getParser(env) { var input, // LeSS input string i, // current index in `input` j, // current chunk temp, // temporarily holds a chunk's state, for backtracking memo, // temporarily holds `i`, when backtracking furthest, // furthest index the parser has gone to chunks, // chunkified input current, // index of current chunk, in `input` parser; var that = this; // This function is called after all files // have been imported through `@import`. var finish = function () {//NOSONAR //所有文件导入完成之后调用 }; function save() { temp = chunks[j]; memo = i; current = i; } function restore() { chunks[j] = temp; i = memo; current = i; } function sync() { if (i > current) { chunks[j] = chunks[j].slice(i - current); current = i; } } // // Parse from a token, regexp or string, and move forward if match // function _match(tok) { var match, length, c, endIndex; // Non-terminal if (tok instanceof Function) { return tok.call(parser.parsers); // Terminal // Either match a single character in the input, // or match a regexp in the current chunk (chunk[j]). } else if (typeof(tok) === 'string') { match = input.charAt(i) === tok ? tok : null; length = 1; sync(); } else { sync(); match = tok.exec(chunks[j]); if (match) { length = match[0].length; } else { return null; } } // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. if (match) { var mem = i += length; endIndex = i + chunks[j].length - length; while (i < endIndex) { c = input.charCodeAt(i); if (!(c === 32 || c === 10 || c === 9)) { break; } i++; } chunks[j] = chunks[j].slice(length + (i - mem)); current = i; if (chunks[j].length === 0 && j < chunks.length - 1) { j++; } if (typeof(match) === 'string') { return match; } else { return match.length === 1 ? match[0] : match; } } } // Same as _match(), but don't change the state of the parser, // just return the match. function peek(tok) { if (typeof(tok) === 'string') { return input.charAt(i) === tok; } else { return !!tok.test(chunks[j]); } } // Make an error object from a passed set of properties. // Accepted properties: // - `message`: Text of the error message. // - `filename`: Filename where the error occurred. // - `index`: Char. index where the error occurred. function makeError(err) { var einput; var defautls = { index: furthest, filename: env.filename, message: 'Parse error.', line: 0, column: -1 }; for (var prop in defautls) { if (err[prop] === 0) { err[prop] = defautls[prop]; } } if (err.filename && that.env.inputs && that.env.inputs[err.filename]) { einput = that.env.inputs[err.filename]; } else { einput = input; } err.line = (einput.slice(0, err.index).match(/\n/g) || '').length + 1; for (var n = err.index; n >= 0 && einput.charAt(n) !== '\n'; n--) { err.column++; } return new Error([err.filename, err.line, err.column, err.message].join(";")); } this.env = env = env || {}; this.env.filename = this.env.filename || null; this.env.inputs = this.env.inputs || {}; // The Parser parser = { // Parse an input string into an abstract syntax tree. // Throws an error on parse errors. parse: function (str) { var root, error = null; i = j = current = furthest = 0; chunks = []; input = str.replace(/\r\n/g, '\n'); if (env.filename) { that.env.inputs[env.filename] = input; } // Split the input into chunks. chunks = (function (chunks) { var j = 0, skip = /(?:@\{[\w-]+\}|[^"'`\{\}\/\(\)\\])+/g, comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g, string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`]|\\.)*)`/g, level = 0, match, chunk = chunks[0], inParam; for (var i = 0, c, cc; i < input.length;) { skip.lastIndex = i; if (match = skip.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); } } c = input.charAt(i); comment.lastIndex = string.lastIndex = i; if (match = string.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); continue; } } if (!inParam && c === '/') { cc = input.charAt(i + 1); if (cc === '/' || cc === '*') { if (match = comment.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); continue; } } } } switch (c) { case '{'://NOSONAR if (!inParam) { level++; chunk.push(c); break; } case '}'://NOSONAR if (!inParam) { level--; chunk.push(c); chunks[++j] = chunk = []; break; } case '('://NOSONAR if (!inParam) { inParam = true; chunk.push(c); break; } case ')'://NOSONAR if (inParam) { inParam = false; chunk.push(c); break; } default: chunk.push(c); break; } i++; } if (level !== 0) { error = { index: i - 1, type: 'Parse', message: (level > 0) ? "missing closing `}`" : "missing opening `{`" }; } return chunks.map(function (c) { return c.join(''); }); })([[]]); if (error) { throw makeError(error); } // Sort rules by specificity: this function expects selectors to be // split already. // // Written to be used as a .sort(Function); // argument. // // [1, 0, 0, 467] > [0, 0, 1, 520] var specificitySort = function (a, b) { var as = a.specificity; var bs = b.specificity; if (as[0] != bs[0]) {return bs[0] - as[0];} if (as[1] != bs[1]) {return bs[1] - as[1];} if (as[2] != bs[2]) {return bs[2] - as[2];} return bs[3] - as[3]; }; // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. root = new CartoCSS.Tree.Ruleset([], _match(this.parsers.primary)); root.root = true; // Get an array of Ruleset objects, flattened // and sorted according to specificitySort root.toList = (function () { return function (env) { env.error = function (e) { if (!env.errors) {env.errors = new Error('');} if (env.errors.message) { env.errors.message += '\n' + makeError(e).message; } else { env.errors.message = makeError(e).message; } }; env.frames = env.frames || []; // call populates Invalid-caused errors var definitions = this.flatten([], [], env); definitions.sort(specificitySort); return definitions; }; })(); return root; }, // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Rule -> Value -> Expression -> Entity // // In general, most rules will try to parse a token with the `_match()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. parsers: { // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | rule)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. primary: function () { var node, root = []; while ((node = _match(this.rule) || _match(this.ruleset) || _match(this.comment)) || _match(/^[\s\n]+/) || (node = _match(this.invalid))) { if (node) {root.push(node);} } return root; }, invalid: function () { var chunk = _match(/^[^;\n]*[;\n]/); // To fail gracefully, match everything until a semicolon or linebreak. if (chunk) { return new CartoCSS.Tree.Invalid(chunk, memo); } }, // We create a Comment node for CSS comments `/* */`, // but keep the LeSS comments `//` silent, by just skipping // over them. comment: function () { var comment; if (input.charAt(i) !== '/') {return;} if (input.charAt(i + 1) === '/') { return new CartoCSS.Tree.Comment(_match(/^\/\/.*/), true); } else if (comment = _match(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/)) { return new CartoCSS.Tree.Comment(comment); } }, // Entities are tokens which can be found inside an Expression entities: { // A string, which supports escaping " and ' "milky way" 'he\'s the one!' quoted: function () { if (input.charAt(i) !== '"' && input.charAt(i) !== "'") {return;} var str = _match(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/); if (str) { return new CartoCSS.Tree.Quoted(str[1] || str[2]); } }, // A reference to a Mapnik field, like [NAME] // Behind the scenes, this has the same representation, but Carto // needs to be careful to warn when unsupported operations are used. field: function () { var l = '[', r = ']'; if (!_match(l)) {return;} var field_name = _match(/(^[^\]]+)/); if (!_match(r)) {return;} if (field_name) {return new CartoCSS.Tree.Field(field_name[1]);} }, // This is a comparison operator comparison: function () { var str = _match(/^=~|=|!=|<=|>=|<|>/); if (str) { return str; } }, // A catch-all word, such as: hard-light // These can start with either a letter or a dash (-), // and then contain numbers, underscores, and letters. keyword: function () { var k = _match(/^[A-Za-z\u4e00-\u9fa5-]+[A-Za-z-0-9\u4e00-\u9fa5_]*/); if (k) { return new CartoCSS.Tree.Keyword(k); } }, // A function call like rgb(255, 0, 255) // The arguments are parsed with the `entities.arguments` parser. call: function () { var name, args; if (!(name = /^([\w\-]+|%)\(/.exec(chunks[j]))) {return;} name = name[1]; if (name === 'url') { // url() is handled by the url parser instead return null; } else { i += name.length; } var l = '(', r = ')'; _match(l); // Parse the '(' and consume whitespace. args = _match(this.entities['arguments']); if (!_match(r)) {return;} if (name) { return new CartoCSS.Tree.Call(name, args, i); } }, // Arguments are comma-separated expressions 'arguments': function () { var args = [], arg; while (arg = _match(this.expression)) { args.push(arg); var q = ','; if (!_match(q)) { break; } } return args; }, literal: function () { return _match(this.entities.dimension) || _match(this.entities.keywordcolor) || _match(this.entities.hexcolor) || _match(this.entities.quoted); }, // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. url: function () { var value; if (input.charAt(i) !== 'u' || !_match(/^url\(/)) {return;} value = _match(this.entities.quoted) || _match(this.entities.variable) || _match(/^[\-\w%@_match\/.&=:;#+?~]+/) || ''; var r = ')'; if (!_match(r)) { return new CartoCSS.Tree.Invalid(value, memo, 'Missing closing ) in URL.'); } else { return new CartoCSS.Tree.URL((typeof value.value !== 'undefined' || value instanceof CartoCSS.Tree.Variable) ? value : new CartoCSS.Tree.Quoted(value)); } }, // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. variable: function () { var name, index = i; if (input.charAt(i) === '@' && (name = _match(/^@[\w-]+/))) { return new CartoCSS.Tree.Variable(name, index, env.filename); } }, hexcolor: function () { var rgb; if (input.charAt(i) === '#' && (rgb = _match(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/))) { return new CartoCSS.Tree.Color(rgb[1]); } }, keywordcolor: function () { var rgb = chunks[j].match(/^[a-z]+/); if (rgb && rgb[0] in CartoCSS.Tree.Reference.data.colors) { return new CartoCSS.Tree.Color(CartoCSS.Tree.Reference.data.colors[_match(/^[a-z]+/)]); } }, // A Dimension, that is, a number and a unit. The only // unit that has an effect is % dimension: function () { var c = input.charCodeAt(i); if ((c > 57 || c < 45) || c === 47) {return;} var value = _match(/^(-?\d*\.?\d+(?:[eE][-+]?\d+)?)(\%|\w+)?/); if (value) { return new CartoCSS.Tree.Dimension(value[1], value[2], memo); } } }, // The variable part of a variable definition. // Used in the `rule` parser. Like @fink: variable: function () { var name; if (input.charAt(i) === '@' && (name = _match(/^(@[\w-]+)\s*:/))) { return name[1]; } }, // Entities are the smallest recognized token, // and can be found inside a rule's value. entity: function () { var property1 = _match(this.entities.call) || _match(this.entities.literal); var property2 = _match(this.entities.field) || _match(this.entities.variable); var property3 = _match(this.entities.url) || _match(this.entities.keyword); return property1 || property2 || property3; }, // A Rule terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was ommitted. end: function () { var q = ';'; return _match(q) || peek('}'); }, // Elements are the building blocks for Selectors. They consist of // an element name, such as a tag a class, or `*`. //增加对中文的支持,[\u4e00-\u9fa5] element: function () { var e = _match(/^(?:[.#][\w\u4e00-\u9fa5\-]+|\*|Map)/); if (e) {return new CartoCSS.Tree.Element(e);} }, // Attachments allow adding multiple lines, polygons etc. to an // object. There can only be one attachment per selector. attachment: function () { var s = _match(/^::([\w\-]+(?:\/[\w\-]+)*)/); if (s) {return s[1];} }, // Selectors are made out of one or more Elements, see above. selector: function () { var a, attachment, e, elements = [], f, filters = new CartoCSS.Tree.Filterset(), z, zooms = [], segments = 0, conditions = 0; while ( (e = _match(this.element)) || (z = _match(this.zoom)) || (f = _match(this.filter)) || (a = _match(this.attachment)) ) { segments++; if (e) { elements.push(e); } else if (z) { zooms.push(z); conditions++; } else if (f) { var err = filters.add(f); if (err) { throw makeError({ message: err, index: i - 1 }); } conditions++; } else if (attachment) { throw makeError({ message: 'Encountered second attachment name.', index: i - 1 }); } else { attachment = a; } var c = input.charAt(i); if (c === '{' || c === '}' || c === ';' || c === ',') { break; } } if (segments) { return new CartoCSS.Tree.Selector(filters, zooms, elements, attachment, conditions, memo); } }, filter: function () { save(); var key, op, val, l = '[', r = ']'; if (!_match(l)) {return;} if (key = _match(/^[a-zA-Z0-9\-_]+/) || _match(this.entities.quoted) || _match(this.entities.variable) || _match(this.entities.keyword) || _match(this.entities.field)) { if (key instanceof CartoCSS.Tree.Quoted) { key = new CartoCSS.Tree.Field(key.toString()); } if ((op = _match(this.entities.comparison)) && (val = _match(this.entities.quoted) || _match(this.entities.variable) || _match(this.entities.dimension) || _match(this.entities.keyword) || _match(this.entities.field))) { if (!_match(r)) { throw makeError({ message: 'Missing closing ] of filter.', index: memo - 1 }); } if (!key.is) {key = new CartoCSS.Tree.Field(key);} return new CartoCSS.Tree.Filter(key, op, val, memo, env.filename); } } }, zoom: function () { save(); var op, val, r = ']'; if (_match(/^\[\s*zoom/g) && (op = _match(this.entities.comparison)) && (val = _match(this.entities.variable) || _match(this.entities.dimension)) && _match(r)) { return new CartoCSS.Tree.Zoom(op, val, memo); } else { // backtrack restore(); } }, // The `block` rule is used by `ruleset` // It's a wrapper around the `primary` rule, with added `{}`. block: function () { var content, l = '{', r = '}'; if (_match(l) && (content = _match(this.primary)) && _match(r)) { return content; } }, // div, .class, body > p {...} ruleset: function () { var selectors = [], s, rules, q = ','; save(); while (s = _match(this.selector)) { selectors.push(s); while (_match(this.comment)) {//NOSONAR } if (!_match(q)) { break; } while (_match(this.comment)) {//NOSONAR } } if (s) { while (_match(this.comment)) {//NOSONAR } } if (selectors.length > 0 && (rules = _match(this.block))) { if (selectors.length === 1 && selectors[0].elements.length && selectors[0].elements[0].value === 'Map') { var rs = new CartoCSS.Tree.Ruleset(selectors, rules); rs.isMap = true; return rs; } return new CartoCSS.Tree.Ruleset(selectors, rules); } else { // Backtrack restore(); } }, rule: function () { var name, value, c = input.charAt(i); save(); if (c === '.' || c === '#') { return; } if (name = _match(this.variable) || _match(this.property)) { value = _match(this.value); if (value && _match(this.end)) { return new CartoCSS.Tree.Rule(name, value, memo, env.filename); } else { furthest = i; restore(); } } }, font: function () { var value = [], expression = [], e, q = ','; while (e = _match(this.entity)) { expression.push(e); } value.push(new CartoCSS.Tree.Expression(expression)); if (_match(q)) { while (e = _match(this.expression)) { value.push(e); if (!_match(q)) { break; } } } return new CartoCSS.Tree.Value(value); }, // A Value is a comma-delimited list of Expressions // In a Rule, a Value represents everything after the `:`, // and before the `;`. value: function () { var e, expressions = [], q = ','; while (e = _match(this.expression)) { expressions.push(e); if (!_match(q)) { break; } } if (expressions.length > 1) { return new CartoCSS.Tree.Value(expressions.map(function (e) { return e.value[0]; })); } else if (expressions.length === 1) { return new CartoCSS.Tree.Value(expressions); } }, // A sub-expression, contained by parenthensis sub: function () { var e, l = '(', r = ")"; if (_match(l) && (e = _match(this.expression)) && _match(r)) { return e; } }, // This is a misnomer because it actually handles multiplication // and division. multiplication: function () { var m, a, op, operation, q = '/'; if (m = _match(this.operand)) { while ((op = (_match(q) || _match('*') || _match('%'))) && (a = _match(this.operand))) { operation = new CartoCSS.Tree.Operation(op, [operation || m, a], memo); } return operation || m; } }, addition: function () { var m, a, op, operation, plus = '+'; if (m = _match(this.multiplication)) { while ((op = _match(/^[-+]\s+/) || (input.charAt(i - 1) != ' ' && (_match(plus) || _match('-')))) && (a = _match(this.multiplication))) { operation = new CartoCSS.Tree.Operation(op, [operation || m, a], memo); } return operation || m; } }, // An operand is anything that can be part of an operation, // such as a Color, or a Variable operand: function () { return _match(this.sub) || _match(this.entity); }, // Expressions either represent mathematical operations, // or white-space delimited Entities. @var * 2 expression: function () { var e, entities = []; while (e = _match(this.addition) || _match(this.entity)) { entities.push(e); } if (entities.length > 0) { return new CartoCSS.Tree.Expression(entities); } }, property: function () { var name = _match(/^(([a-z][-a-z_0-9]*\/)?\*?-?[-a-z_0-9]+)\s*:/); if (name) {return name[1];} } } }; return parser; } /** * @function CartoCSS.prototype.parse * @description 利用CartoCSS解析器里面的parse方法,将CartoCSS样式表字符串转化为CartoCSS规则集。 * @returns {Object} CartoCSS规则集。 */ parse(str) { var parser = this.parser; var ruleSet = this.ruleSet = parser.parse(str); return ruleSet; } /** * @function CartoCSS.prototype.toShaders * @description 将CartoCSS规则集转化为着色器。 * @returns {Array} CartoCSS着色器集。 */ toShaders() { if (this.ruleSet) { var ruleset = this.ruleSet; if (ruleset) { var defs = ruleset.toList(this.env); defs.reverse(); var shaders = {}; var keys = []; this._toShaders(shaders,keys,defs); var ordered_shaders = []; var done = {}; for (var i = 0, len0 = defs.length; i < len0; ++i) { var def = defs[i]; var k = def.attachment; var shader = shaders[keys[i]]; var shaderArray = []; if (!done[k]) { var j = 0; for (var prop in shader) { if (prop !== 'zoom' && prop !== 'frames' && prop !== "attachment" && prop != "elements") { //对layer-index作特殊处理以实现图层的控制 if (prop === "layer-index") { /*var getLayerIndex = Function("attributes", "zoom", "var _value = null;" + shader[prop].join('\n') + "; return _value; ");*/ var getLayerIndex = function (attributes, zoom) {//NOSONAR var _value = null; shader[prop].join('\n'); return _value; }; var layerIndex = getLayerIndex(); Object.defineProperty(shaderArray, "layerIndex", { configurable: true, enumerable: false, value: layerIndex }); } else { shaderArray[j++] = function (ops, shaderArray) {//NOSONAR if (!Array.isArray(ops)) { return ops; } var body = ops.join('\n'); var myKeyword = 'attributes["FEATUREID"]&&attributes["FEATUREID"]'; var index = body.indexOf(myKeyword); if (index >= 0) { //对featureID作一些特殊处理,以将featureID提取出来 if (!shaderArray.featureFilter) { var featureFilterStart = index + myKeyword.length; var featureFilterEnd = body.indexOf(")", featureFilterStart + 1); var featureFilterStr = "featureId&&(featureId" + body.substring(featureFilterStart, featureFilterEnd) + ")"; /*var featureFilter = Function("featureId", "if(" + featureFilterStr + "){return true;}return false;");*/ var featureFilter = function (featureId) { if (featureFilterStr) { return true; } return false; } Object.defineProperty(shaderArray, "featureFilter", { configurable: true, enumerable: false, value: featureFilter }); } return { "property": prop, "getValue": Function("attributes", "zoom", "seftFilter", "var _value = null; var isExcute=typeof seftFilter=='function'?sefgFilter():seftFilter;if(isExcute){" + body + ";} return _value; ")//NOSONAR }; } else { return { "property": prop, "getValue": Function("attributes", "zoom", "var _value = null;" + body + "; return _value; ")//NOSONAR }; } }(shader[prop], shaderArray); } } } Object.defineProperty(shaderArray, "attachment", { configurable: true, enumerable: false, value: k }); Object.defineProperty(shaderArray, "elements", { configurable: true, enumerable: false, value: def.elements }); ordered_shaders.push(shaderArray); done[keys[i]] = true; } Object.defineProperty(shaderArray, "zoom", { configurable: true, enumerable: false, value: def.zoom }); //shader.frames.push(def.frame_offset); } return ordered_shaders; } } return null; } _toShaders(shaders, keys,defs) { for (let i = 0, len0 = defs.length; i < len0; ++i) { let def = defs[i]; let element_str = []; for (let j = 0, len1 = def.elements.length; j < len1; j++) { element_str.push(def.elements[j]); } let filters = def.filters.filters; let filterStr = []; for (let attr in filters) { filterStr.push(filters[attr].id); } let key = element_str.join("/") + "::" + def.attachment + "_" + filterStr.join("_"); keys.push(key); let shader = shaders[key] = (shaders[key] || {}); //shader.frames = []; shader.zoom = CartoCSS.Tree.Zoom.all; let props = def.toJS(this.env); for (let v in props) { (shader[v] = (shader[v] || [])).push(props[v].join('\n')) } } } /** * @function CartoCSS.prototype.getShaders * @description 获取CartoCSS着色器。 * @returns {Array} 着色器集。 * @example * //shaders的结构大概如下: * var shaders=[ * { * attachment:"one", * elements:[], * zoom:23, * length:2, * 0:{property:"line-color",value:function(attribute,zoom){var _value=null;if(zoom){_value="#123456"}return _vlaue;}}, * 1:{preoperty:"line-width",value:function(attribute,zoom){var _value=null;if(zoom){_value=3}return _vlaue;}} * }, * { * attachment:"two", * elements:[], * zoom:23, * length:2, * 0:{property:"polygon-color",value:function(attribute,zoom){var _value=null;if(zoom){_value="#123456"}return _vlaue;}}, * 1:{property:"line-width",value:function(attribute,zoom){var _value=null;if(zoom){_value=3}return _vlaue;}} * } * ]; */ getShaders() { return this.shaders; } /** * @function CartoCSS.prototype.destroy * @description CartoCSS解析对象的析构函数,用于销毁CartoCSS解析对象。 */ destroy() { this.cartoStr = null; this.env = null; this.ruleSet = null; this.parser = null; this.shaders = null; } } var _mapnik_reference_latest = { "version": "2.1.1", "style": { "filter-mode": { "type": [ "all", "first" ], "doc": "Control the processing behavior of Rule filters within a Style. If 'all' is used then all Rules are processed sequentially independent of whether any previous filters matched. If 'first' is used then it means processing ends after the first match (a positive filter evaluation) and no further Rules in the Style are processed ('first' is usually the default for CSS implementations on top of Mapnik to simplify translation from CSS to Mapnik XML)", "default-value": "all", "default-meaning": "All Rules in a Style are processed whether they have filters or not and whether or not the filter conditions evaluate to true." }, "image-filters": { "css": "image-filters", "default-value": "none", "default-meaning": "no filters", "type": "functions", "functions": [ ["agg-stack-blur", 2], ["emboss", 0], ["blur", 0], ["gray", 0], ["sobel", 0], ["edge-detect", 0], ["x-gradient", 0], ["y-gradient", 0], ["invert", 0], ["sharpen", 0] ], "doc": "A list of image filters." }, "comp-op": { "css": "comp-op", "default-value": "src-over", "default-meaning": "add the current layer on top of other layers", "doc": "Composite operation. This defines how this layer should behave relative to layers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] }, "opacity": { "css": "opacity", "type": "float", "doc": "An alpha value for the style (which means an alpha applied to all features in separate buffer and then composited back to main buffer)", "default-value": 1, "default-meaning": "no separate buffer will be used and no alpha will be applied to the style after rendering" } }, "layer": { "name": { "default-value": "", "type": "string", "required": true, "default-meaning": "No layer name has been provided", "doc": "The name of a layer. Can be anything you wish and is not strictly validated, but ideally unique in the map" }, "srs": { "default-value": "", "type": "string", "default-meaning": "No srs value is provided and the value will be inherited from the Map's srs", "doc": "The spatial reference system definition for the layer, aka the projection. Can either be a proj4 literal string like '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' or, if the proper proj4 epsg/nad/etc identifier files are installed, a string that uses an id like: '+init=epsg:4326'" }, "status": { "default-value": true, "type": "boolean", "default-meaning": "This layer will be marked as active and available for processing", "doc": "A property that can be set to false to disable this layer from being processed" }, "minzoom": { "default-value": "0", "type": "float", "default-meaning": "The layer will be visible at the minimum possible scale", "doc": "The minimum scale denominator that this layer will be visible at. A layer's visibility is determined by whether its status is true and if the Map scale >= minzoom - 1e-6 and scale < maxzoom + 1e-6" }, "maxzoom": { "default-value": "1.79769e+308", "type": "float", "default-meaning": "The layer will be visible at the maximum possible scale", "doc": "The maximum scale denominator that this layer will be visible at. The default is the numeric limit of the C++ double type, which may vary slightly by system, but is likely a massive number like 1.79769e+308 and ensures that this layer will always be visible unless the value is reduced. A layer's visibility is determined by whether its status is true and if the Map scale >= minzoom - 1e-6 and scale < maxzoom + 1e-6" }, "queryable": { "default-value": false, "type": "boolean", "default-meaning": "The layer will not be available for the direct querying of data values", "doc": "This property was added for GetFeatureInfo/WMS compatibility and is rarely used. It is off by default meaning that in a WMS context the layer will not be able to be queried unless the property is explicitly set to true" }, "clear-label-cache": { "default-value": false, "type": "boolean", "default-meaning": "The renderer's collision detector cache (used for avoiding duplicate labels and overlapping markers) will not be cleared immediately before processing this layer", "doc": "This property, by default off, can be enabled to allow a user to clear the collision detector cache before a given layer is processed. This may be desirable to ensure that a given layers data shows up on the map even if it normally would not because of collisions with previously rendered labels or markers" }, "group-by": { "default-value": "", "type": "string", "default-meaning": "No special layer grouping will be used during rendering", "doc": "https://github.com/mapnik/mapnik/wiki/Grouped-rendering" }, "buffer-size": { "default-value": "0", "type": "float", "default-meaning": "No buffer will be used", "doc": "Extra tolerance around the Layer extent (in pixels) used to when querying and (potentially) clipping the layer data during rendering" }, "maximum-extent": { "default-value": "none", "type": "bbox", "default-meaning": "No clipping extent will be used", "doc": "An extent to be used to limit the bounds used to query this specific layer data during rendering. Should be minx, miny, maxx, maxy in the coordinates of the Layer." } }, "symbolizers": { "*": { "image-filters": { "css": "image-filters", "default-value": "none", "default-meaning": "no filters", "type": "functions", "functions": [ ["agg-stack-blur", 2], ["emboss", 0], ["blur", 0], ["gray", 0], ["sobel", 0], ["edge-detect", 0], ["x-gradient", 0], ["y-gradient", 0], ["invert", 0], ["sharpen", 0] ], "doc": "A list of image filters." }, "comp-op": { "css": "comp-op", "default-value": "src-over", "default-meaning": "add the current layer on top of other layers", "doc": "Composite operation. This defines how this layer should behave relative to layers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] }, "opacity": { "css": "opacity", "type": "float", "doc": "An alpha value for the style (which means an alpha applied to all features in separate buffer and then composited back to main buffer)", "default-value": 1, "default-meaning": "no separate buffer will be used and no alpha will be applied to the style after rendering" } }, "map": { "background-color": { "css": "background-color", "default-value": "none", "default-meaning": "transparent", "type": "color", "doc": "Map Background color" }, "background-image": { "css": "background-image", "type": "uri", "default-value": "", "default-meaning": "transparent", "doc": "An image that is repeated below all features on a map as a background.", "description": "Map Background image" }, "srs": { "css": "srs", "type": "string", "default-value": "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs", "default-meaning": "The proj4 literal of EPSG:4326 is assumed to be the Map's spatial reference and all data from layers within this map will be plotted using this coordinate system. If any layers do not declare an srs value then they will be assumed to be in the same srs as the Map and not transformations will be needed to plot them in the Map's coordinate space", "doc": "Map spatial reference (proj4 string)" }, "buffer-size": { "css": "buffer-size", "default-value": "0", "type": "float", "default-meaning": "No buffer will be used", "doc": "Extra tolerance around the map (in pixels) used to ensure labels crossing tile boundaries are equally rendered in each tile (e.g. cut in each tile). Not intended to be used in combination with \"avoid-edges\"." }, "maximum-extent": { "css": "", "default-value": "none", "type": "bbox", "default-meaning": "No clipping extent will be used", "doc": "An extent to be used to limit the bounds used to query all layers during rendering. Should be minx, miny, maxx, maxy in the coordinates of the Map." }, "base": { "css": "base", "default-value": "", "default-meaning": "This base path defaults to an empty string meaning that any relative paths to files referenced in styles or layers will be interpreted relative to the application process.", "type": "string", "doc": "Any relative paths used to reference files will be understood as relative to this directory path if the map is loaded from an in memory object rather than from the filesystem. If the map is loaded from the filesystem and this option is not provided it will be set to the directory of the stylesheet." }, "paths-from-xml": { "css": "", "default-value": true, "default-meaning": "Paths read from XML will be interpreted from the location of the XML", "type": "boolean", "doc": "value to control whether paths in the XML will be interpreted from the location of the XML or from the working directory of the program that calls load_map()" }, "minimum-version": { "css": "", "default-value": "none", "default-meaning": "Mapnik version will not be detected and no error will be thrown about compatibility", "type": "string", "doc": "The minumum Mapnik version (e.g. 0.7.2) needed to use certain functionality in the stylesheet" }, "font-directory": { "css": "font-directory", "type": "uri", "default-value": "none", "default-meaning": "No map-specific fonts will be registered", "doc": "Path to a directory which holds fonts which should be registered when the Map is loaded (in addition to any fonts that may be automatically registered)." } }, "polygon": { "fill": { "css": "polygon-fill", "type": "color", "default-value": "rgba(128,128,128,1)", "default-meaning": "gray and fully opaque (alpha = 1), same as rgb(128,128,128)", "doc": "Fill color to assign to a polygon" }, "fill-opacity": { "css": "polygon-opacity", "type": "float", "doc": "The opacity of the polygon", "default-value": 1, "default-meaning": "opaque" }, "gamma": { "css": "polygon-gamma", "type": "float", "default-value": 1, "default-meaning": "fully antialiased", "range": "0-1", "doc": "Level of antialiasing of polygon edges" }, "gamma-method": { "css": "polygon-gamma-method", "type": [ "power", "linear", "none", "threshold", "multiply" ], "default-value": "power", "default-meaning": "pow(x,gamma) is used to calculate pixel gamma, which produces slightly smoother line and polygon antialiasing than the 'linear' method, while other methods are usually only used to disable AA", "doc": "An Antigrain Geometry specific rendering hint to control the quality of antialiasing. Under the hood in Mapnik this method is used in combination with the 'gamma' value (which defaults to 1). The methods are in the AGG source at https://github.com/mapnik/mapnik/blob/master/deps/agg/include/agg_gamma_functions.h" }, "clip": { "css": "polygon-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "polygon-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "geometry-transform": { "css": "polygon-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "polygon-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "line": { "stroke": { "css": "line-color", "default-value": "rgba(0,0,0,1)", "type": "color", "default-meaning": "black and fully opaque (alpha = 1), same as rgb(0,0,0)", "doc": "The color of a drawn line" }, "stroke-width": { "css": "line-width", "default-value": 1, "type": "float", "doc": "The width of a line in pixels" }, "stroke-opacity": { "css": "line-opacity", "default-value": 1, "type": "float", "default-meaning": "opaque", "doc": "The opacity of a line" }, "stroke-linejoin": { "css": "line-join", "default-value": "miter", "type": [ "miter", "round", "bevel" ], "doc": "The behavior of lines when joining" }, "stroke-linecap": { "css": "line-cap", "default-value": "butt", "type": [ "butt", "round", "square" ], "doc": "The display of line endings" }, "stroke-gamma": { "css": "line-gamma", "type": "float", "default-value": 1, "default-meaning": "fully antialiased", "range": "0-1", "doc": "Level of antialiasing of stroke line" }, "stroke-gamma-method": { "css": "line-gamma-method", "type": [ "power", "linear", "none", "threshold", "multiply" ], "default-value": "power", "default-meaning": "pow(x,gamma) is used to calculate pixel gamma, which produces slightly smoother line and polygon antialiasing than the 'linear' method, while other methods are usually only used to disable AA", "doc": "An Antigrain Geometry specific rendering hint to control the quality of antialiasing. Under the hood in Mapnik this method is used in combination with the 'gamma' value (which defaults to 1). The methods are in the AGG source at https://github.com/mapnik/mapnik/blob/master/deps/agg/include/agg_gamma_functions.h" }, "stroke-dasharray": { "css": "line-dasharray", "type": "numbers", "doc": "A pair of length values [a,b], where (a) is the dash length and (b) is the gap length respectively. More than two values are supported for more complex patterns.", "default-value": "none", "default-meaning": "solid line" }, "stroke-dashoffset": { "css": "line-dash-offset", "type": "numbers", "doc": "valid parameter but not currently used in renderers (only exists for experimental svg support in Mapnik which is not yet enabled)", "default-value": "none", "default-meaning": "solid line" }, "stroke-miterlimit": { "css": "line-miterlimit", "type": "float", "doc": "The limit on the ratio of the miter length to the stroke-width. Used to automatically convert miter joins to bevel joins for sharp angles to avoid the miter extending beyond the thickness of the stroking path. Normally will not need to be set, but a larger value can sometimes help avoid jaggy artifacts.", "default-value": 4.0, "default-meaning": "Will auto-convert miters to bevel line joins when theta is less than 29 degrees as per the SVG spec: 'miterLength / stroke-width = 1 / sin ( theta / 2 )'" }, "clip": { "css": "line-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "line-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "offset": { "css": "line-offset", "type": "float", "default-value": 0, "default-meaning": "no offset", "doc": "Offsets a line a number of pixels parallel to its actual path. Postive values move the line left, negative values move it right (relative to the directionality of the line)." }, "rasterizer": { "css": "line-rasterizer", "type": [ "full", "fast" ], "default-value": "full", "doc": "Exposes an alternate AGG rendering method that sacrifices some accuracy for speed." }, "geometry-transform": { "css": "line-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "line-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "markers": { "file": { "css": "marker-file", "doc": "An SVG file that this marker shows at each placement. If no file is given, the marker will show an ellipse.", "default-value": "", "default-meaning": "An ellipse or circle, if width equals height", "type": "uri" }, "opacity": { "css": "marker-opacity", "doc": "The overall opacity of the marker, if set, overrides both the opacity of both the fill and stroke", "default-value": 1, "default-meaning": "The stroke-opacity and fill-opacity will be used", "type": "float" }, "fill-opacity": { "css": "marker-fill-opacity", "doc": "The fill opacity of the marker", "default-value": 1, "default-meaning": "opaque", "type": "float" }, "stroke": { "css": "marker-line-color", "doc": "The color of the stroke around a marker shape.", "default-value": "black", "type": "color" }, "stroke-width": { "css": "marker-line-width", "doc": "The width of the stroke around a marker shape, in pixels. This is positioned on the boundary, so high values can cover the area itself.", "type": "float" }, "stroke-opacity": { "css": "marker-line-opacity", "default-value": 1, "default-meaning": "opaque", "doc": "The opacity of a line", "type": "float" }, "placement": { "css": "marker-placement", "type": [ "point", "line", "interior" ], "default-value": "point", "default-meaning": "Place markers at the center point (centroid) of the geometry", "doc": "Attempt to place markers on a point, in the center of a polygon, or if markers-placement:line, then multiple times along a line. 'interior' placement can be used to ensure that points placed on polygons are forced to be inside the polygon interior" }, "multi-policy": { "css": "marker-multi-policy", "type": [ "each", "whole", "largest" ], "default-value": "each", "default-meaning": "If a feature contains multiple geometries and the placement type is either point or interior then a marker will be rendered for each", "doc": "A special setting to allow the user to control rendering behavior for 'multi-geometries' (when a feature contains multiple geometries). This setting does not apply to markers placed along lines. The 'each' policy is default and means all geometries will get a marker. The 'whole' policy means that the aggregate centroid between all geometries will be used. The 'largest' policy means that only the largest (by bounding box areas) feature will get a rendered marker (this is how text labeling behaves by default)." }, "marker-type": { "css": "marker-type", "type": [ "arrow", "ellipse" ], "default-value": "ellipse", "doc": "The default marker-type. If a SVG file is not given as the marker-file parameter, the renderer provides either an arrow or an ellipse (a circle if height is equal to width)" }, "width": { "css": "marker-width", "default-value": 10, "doc": "The width of the marker, if using one of the default types.", "type": "expression" }, "height": { "css": "marker-height", "default-value": 10, "doc": "The height of the marker, if using one of the default types.", "type": "expression" }, "fill": { "css": "marker-fill", "default-value": "blue", "doc": "The color of the area of the marker.", "type": "color" }, "allow-overlap": { "css": "marker-allow-overlap", "type": "boolean", "default-value": false, "doc": "Control whether overlapping markers are shown or hidden.", "default-meaning": "Do not allow makers to overlap with each other - overlapping markers will not be shown." }, "ignore-placement": { "css": "marker-ignore-placement", "type": "boolean", "default-value": false, "default-meaning": "do not store the bbox of this geometry in the collision detector cache", "doc": "value to control whether the placement of the feature will prevent the placement of other features" }, "spacing": { "css": "marker-spacing", "doc": "Space between repeated labels", "default-value": 100, "type": "float" }, "max-error": { "css": "marker-max-error", "type": "float", "default-value": 0.2, "doc": "The maximum difference between actual marker placement and the marker-spacing parameter. Setting a high value can allow the renderer to try to resolve placement conflicts with other symbolizers." }, "transform": { "css": "marker-transform", "type": "functions", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ], "default-value": "", "default-meaning": "No transformation", "doc": "SVG transformation definition" }, "clip": { "css": "marker-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "marker-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "geometry-transform": { "css": "marker-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "marker-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "shield": { "name": { "css": "shield-name", "type": "expression", "serialization": "content", "doc": "Value to use for a shield\"s text label. Data columns are specified using brackets like [column_name]" }, "file": { "css": "shield-file", "required": true, "type": "uri", "default-value": "none", "doc": "Image file to render behind the shield text" }, "face-name": { "css": "shield-face-name", "type": "string", "validate": "font", "doc": "Font name and style to use for the shield text", "default-value": "", "required": true }, "unlock-image": { "css": "shield-unlock-image", "type": "boolean", "doc": "This parameter should be set to true if you are trying to position text beside rather than on top of the shield image", "default-value": false, "default-meaning": "text alignment relative to the shield image uses the center of the image as the anchor for text positioning." }, "size": { "css": "shield-size", "type": "float", "doc": "The size of the shield text in pixels" }, "fill": { "css": "shield-fill", "type": "color", "doc": "The color of the shield text" }, "placement": { "css": "shield-placement", "type": [ "point", "line", "vertex", "interior" ], "default-value": "point", "doc": "How this shield should be placed. Point placement attempts to place it on top of points, line places along lines multiple times per feature, vertex places on the vertexes of polygons, and interior attempts to place inside of polygons." }, "avoid-edges": { "css": "shield-avoid-edges", "doc": "Tell positioning algorithm to avoid labeling near intersection edges.", "type": "boolean", "default-value": false }, "allow-overlap": { "css": "shield-allow-overlap", "type": "boolean", "default-value": false, "doc": "Control whether overlapping shields are shown or hidden.", "default-meaning": "Do not allow shields to overlap with other map elements already placed." }, "minimum-distance": { "css": "shield-min-distance", "type": "float", "default-value": 0, "doc": "Minimum distance to the next shield symbol, not necessarily the same shield." }, "spacing": { "css": "shield-spacing", "type": "float", "default-value": 0, "doc": "The spacing between repeated occurrences of the same shield on a line" }, "minimum-padding": { "css": "shield-min-padding", "default-value": 0, "doc": "Determines the minimum amount of padding that a shield gets relative to other shields", "type": "float" }, "wrap-width": { "css": "shield-wrap-width", "type": "unsigned", "default-value": 0, "doc": "Length of a chunk of text in characters before wrapping text" }, "wrap-before": { "css": "shield-wrap-before", "type": "boolean", "default-value": false, "doc": "Wrap text before wrap-width is reached. If false, wrapped lines will be a bit longer than wrap-width." }, "wrap-character": { "css": "shield-wrap-character", "type": "string", "default-value": " ", "doc": "Use this character instead of a space to wrap long names." }, "halo-fill": { "css": "shield-halo-fill", "type": "color", "default-value": "#FFFFFF", "default-meaning": "white", "doc": "Specifies the color of the halo around the text." }, "halo-radius": { "css": "shield-halo-radius", "doc": "Specify the radius of the halo in pixels", "default-value": 0, "default-meaning": "no halo", "type": "float" }, "character-spacing": { "css": "shield-character-spacing", "type": "unsigned", "default-value": 0, "doc": "Horizontal spacing between characters (in pixels). Currently works for point placement only, not line placement." }, "line-spacing": { "css": "shield-line-spacing", "doc": "Vertical spacing between lines of multiline labels (in pixels)", "type": "unsigned" }, "dx": { "css": "shield-text-dx", "type": "float", "doc": "Displace text within shield by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", "default-value": 0 }, "dy": { "css": "shield-text-dy", "type": "float", "doc": "Displace text within shield by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", "default-value": 0 }, "shield-dx": { "css": "shield-dx", "type": "float", "doc": "Displace shield by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", "default-value": 0 }, "shield-dy": { "css": "shield-dy", "type": "float", "doc": "Displace shield by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", "default-value": 0 }, "opacity": { "css": "shield-opacity", "type": "float", "doc": "(Default 1.0) - opacity of the image used for the shield", "default-value": 1 }, "text-opacity": { "css": "shield-text-opacity", "type": "float", "doc": "(Default 1.0) - opacity of the text placed on top of the shield", "default-value": 1 }, "horizontal-alignment": { "css": "shield-horizontal-alignment", "type": [ "left", "middle", "right", "auto" ], "doc": "The shield's horizontal alignment from its centerpoint", "default-value": "auto" }, "vertical-alignment": { "css": "shield-vertical-alignment", "type": [ "top", "middle", "bottom", "auto" ], "doc": "The shield's vertical alignment from its centerpoint", "default-value": "middle" }, "text-transform": { "css": "shield-text-transform", "type": [ "none", "uppercase", "lowercase", "capitalize" ], "doc": "Transform the case of the characters", "default-value": "none" }, "justify-alignment": { "css": "shield-justify-alignment", "type": [ "left", "center", "right", "auto" ], "doc": "Define how text in a shield's label is justified", "default-value": "auto" }, "clip": { "css": "shield-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "comp-op": { "css": "shield-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "line-pattern": { "file": { "css": "line-pattern-file", "type": "uri", "default-value": "none", "required": true, "doc": "An image file to be repeated and warped along a line" }, "clip": { "css": "line-pattern-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "line-pattern-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "geometry-transform": { "css": "line-pattern-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "line-pattern-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "polygon-pattern": { "file": { "css": "polygon-pattern-file", "type": "uri", "default-value": "none", "required": true, "doc": "Image to use as a repeated pattern fill within a polygon" }, "alignment": { "css": "polygon-pattern-alignment", "type": [ "local", "global" ], "default-value": "local", "doc": "Specify whether to align pattern fills to the layer or to the map." }, "gamma": { "css": "polygon-pattern-gamma", "type": "float", "default-value": 1, "default-meaning": "fully antialiased", "range": "0-1", "doc": "Level of antialiasing of polygon pattern edges" }, "opacity": { "css": "polygon-pattern-opacity", "type": "float", "doc": "(Default 1.0) - Apply an opacity level to the image used for the pattern", "default-value": 1, "default-meaning": "The image is rendered without modifications" }, "clip": { "css": "polygon-pattern-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "smooth": { "css": "polygon-pattern-smooth", "type": "float", "default-value": 0, "default-meaning": "no smoothing", "range": "0-1", "doc": "Smooths out geometry angles. 0 is no smoothing, 1 is fully smoothed. Values greater than 1 will produce wild, looping geometries." }, "geometry-transform": { "css": "polygon-pattern-geometry-transform", "type": "functions", "default-value": "none", "default-meaning": "geometry will not be transformed", "doc": "Allows transformation functions to be applied to the geometry.", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ] }, "comp-op": { "css": "polygon-pattern-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "raster": { "opacity": { "css": "raster-opacity", "default-value": 1, "default-meaning": "opaque", "type": "float", "doc": "The opacity of the raster symbolizer on top of other symbolizers." }, "filter-factor": { "css": "raster-filter-factor", "default-value": -1, "default-meaning": "Allow the datasource to choose appropriate downscaling.", "type": "float", "doc": "This is used by the Raster or Gdal datasources to pre-downscale images using overviews. Higher numbers can sometimes cause much better scaled image output, at the cost of speed." }, "scaling": { "css": "raster-scaling", "type": [ "near", "fast", "bilinear", "bilinear8", "bicubic", "spline16", "spline36", "hanning", "hamming", "hermite", "kaiser", "quadric", "catrom", "gaussian", "bessel", "mitchell", "sinc", "lanczos", "blackman" ], "default-value": "near", "doc": "The scaling algorithm used to making different resolution versions of this raster layer. Bilinear is a good compromise between speed and accuracy, while lanczos gives the highest quality." }, "mesh-size": { "css": "raster-mesh-size", "default-value": 16, "default-meaning": "Reprojection mesh will be 1/16 of the resolution of the source image", "type": "unsigned", "doc": "A reduced resolution mesh is used for raster reprojection, and the total image size is divided by the mesh-size to determine the quality of that mesh. Values for mesh-size larger than the default will result in faster reprojection but might lead to distortion." }, "comp-op": { "css": "raster-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "point": { "file": { "css": "point-file", "type": "uri", "required": false, "default-value": "none", "doc": "Image file to represent a point" }, "allow-overlap": { "css": "point-allow-overlap", "type": "boolean", "default-value": false, "doc": "Control whether overlapping points are shown or hidden.", "default-meaning": "Do not allow points to overlap with each other - overlapping markers will not be shown." }, "ignore-placement": { "css": "point-ignore-placement", "type": "boolean", "default-value": false, "default-meaning": "do not store the bbox of this geometry in the collision detector cache", "doc": "value to control whether the placement of the feature will prevent the placement of other features" }, "opacity": { "css": "point-opacity", "type": "float", "default-value": 1.0, "default-meaning": "Fully opaque", "doc": "A value from 0 to 1 to control the opacity of the point" }, "placement": { "css": "point-placement", "type": [ "centroid", "interior" ], "doc": "How this point should be placed. Centroid calculates the geometric center of a polygon, which can be outside of it, while interior always places inside of a polygon.", "default-value": "centroid" }, "transform": { "css": "point-transform", "type": "functions", "functions": [ ["matrix", 6], ["translate", 2], ["scale", 2], ["rotate", 3], ["skewX", 1], ["skewY", 1] ], "default-value": "", "default-meaning": "No transformation", "doc": "SVG transformation definition" }, "comp-op": { "css": "point-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "text": { "name": { "css": "text-name", "type": "expression", "required": true, "default-value": "", "serialization": "content", "doc": "Value to use for a text label. Data columns are specified using brackets like [column_name]" }, "face-name": { "css": "text-face-name", "type": "string", "validate": "font", "doc": "Font name and style to render a label in", "required": true }, "size": { "css": "text-size", "type": "float", "default-value": 10, "doc": "Text size in pixels" }, "text-ratio": { "css": "text-ratio", "doc": "Define the amount of text (of the total) present on successive lines when wrapping occurs", "default-value": 0, "type": "unsigned" }, "wrap-width": { "css": "text-wrap-width", "doc": "Length of a chunk of text in characters before wrapping text", "default-value": 0, "type": "unsigned" }, "wrap-before": { "css": "text-wrap-before", "type": "boolean", "default-value": false, "doc": "Wrap text before wrap-width is reached. If false, wrapped lines will be a bit longer than wrap-width." }, "wrap-character": { "css": "text-wrap-character", "type": "string", "default-value": " ", "doc": "Use this character instead of a space to wrap long text." }, "spacing": { "css": "text-spacing", "type": "unsigned", "doc": "Distance between repeated text labels on a line (aka. label-spacing)" }, "character-spacing": { "css": "text-character-spacing", "type": "float", "default-value": 0, "doc": "Horizontal spacing adjustment between characters in pixels" }, "line-spacing": { "css": "text-line-spacing", "default-value": 0, "type": "unsigned", "doc": "Vertical spacing adjustment between lines in pixels" }, "label-position-tolerance": { "css": "text-label-position-tolerance", "default-value": 0, "type": "unsigned", "doc": "Allows the label to be displaced from its ideal position by a number of pixels (only works with placement:line)" }, "max-char-angle-delta": { "css": "text-max-char-angle-delta", "type": "float", "default-value": "22.5", "doc": "The maximum angle change, in degrees, allowed between adjacent characters in a label. This value internally is converted to radians to the default is 22.5*math.pi/180.0. The higher the value the fewer labels will be placed around around sharp corners." }, "fill": { "css": "text-fill", "doc": "Specifies the color for the text", "default-value": "#000000", "type": "color" }, "opacity": { "css": "text-opacity", "doc": "A number from 0 to 1 specifying the opacity for the text", "default-value": 1.0, "default-meaning": "Fully opaque", "type": "float" }, "halo-fill": { "css": "text-halo-fill", "type": "color", "default-value": "#FFFFFF", "default-meaning": "white", "doc": "Specifies the color of the halo around the text." }, "halo-radius": { "css": "text-halo-radius", "doc": "Specify the radius of the halo in pixels", "default-value": 0, "default-meaning": "no halo", "type": "float" }, "dx": { "css": "text-dx", "type": "float", "doc": "Displace text by fixed amount, in pixels, +/- along the X axis. A positive value will shift the text right", "default-value": 0 }, "dy": { "css": "text-dy", "type": "float", "doc": "Displace text by fixed amount, in pixels, +/- along the Y axis. A positive value will shift the text down", "default-value": 0 }, "vertical-alignment": { "css": "text-vertical-alignment", "type": [ "top", "middle", "bottom", "auto" ], "doc": "Position of label relative to point position.", "default-value": "auto", "default-meaning": "Default affected by value of dy; \"bottom\" for dy>0, \"top\" for dy<0." }, "avoid-edges": { "css": "text-avoid-edges", "doc": "Tell positioning algorithm to avoid labeling near intersection edges.", "default-value": false, "type": "boolean" }, "minimum-distance": { "css": "text-min-distance", "doc": "Minimum permitted distance to the next text symbolizer.", "type": "float" }, "minimum-padding": { "css": "text-min-padding", "doc": "Determines the minimum amount of padding that a text symbolizer gets relative to other text", "type": "float" }, "minimum-path-length": { "css": "text-min-path-length", "type": "float", "default-value": 0, "default-meaning": "place labels on all paths", "doc": "Place labels only on paths longer than this value." }, "allow-overlap": { "css": "text-allow-overlap", "type": "boolean", "default-value": false, "doc": "Control whether overlapping text is shown or hidden.", "default-meaning": "Do not allow text to overlap with other text - overlapping markers will not be shown." }, "orientation": { "css": "text-orientation", "type": "expression", "doc": "Rotate the text." }, "placement": { "css": "text-placement", "type": [ "point", "line", "vertex", "interior" ], "default-value": "point", "doc": "Control the style of placement of a point versus the geometry it is attached to." }, "placement-type": { "css": "text-placement-type", "doc": "Re-position and/or re-size text to avoid overlaps. \"simple\" for basic algorithm (using text-placements string,) \"dummy\" to turn this feature off.", "type": [ "dummy", "simple" ], "default-value": "dummy" }, "placements": { "css": "text-placements", "type": "string", "default-value": "", "doc": "If \"placement-type\" is set to \"simple\", use this \"POSITIONS,[SIZES]\" string. An example is `text-placements: \"E,NE,SE,W,NW,SW\";` " }, "text-transform": { "css": "text-transform", "type": [ "none", "uppercase", "lowercase", "capitalize" ], "doc": "Transform the case of the characters", "default-value": "none" }, "horizontal-alignment": { "css": "text-horizontal-alignment", "type": [ "left", "middle", "right", "auto" ], "doc": "The text's horizontal alignment from its centerpoint", "default-value": "auto" }, "justify-alignment": { "css": "text-align", "type": [ "left", "right", "center", "auto" ], "doc": "Define how text is justified", "default-value": "auto", "default-meaning": "Auto alignment means that text will be centered by default except when using the `placement-type` parameter - in that case either right or left justification will be used automatically depending on where the text could be fit given the `text-placements` directives" }, "clip": { "css": "text-clip", "type": "boolean", "default-value": true, "default-meaning": "geometry will be clipped to map bounds before rendering", "doc": "geometries are clipped to map bounds by default for best rendering performance. In some cases users may wish to disable this to avoid rendering artifacts." }, "comp-op": { "css": "text-comp-op", "default-value": "src-over", "default-meaning": "add the current symbolizer on top of other symbolizer", "doc": "Composite operation. This defines how this symbolizer should behave relative to symbolizers atop or below it.", "type": ["clear", "src", "dst", "src-over", "dst-over", "src-in", "dst-in", "src-out", "dst-out", "src-atop", "dst-atop", "xor", "plus", "minus", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "contrast", "invert", "invert-rgb", "grain-merge", "grain-extract", "hue", "saturation", "color", "value" ] } }, "building": { "fill": { "css": "building-fill", "default-value": "#FFFFFF", "doc": "The color of the buildings walls.", "type": "color" }, "fill-opacity": { "css": "building-fill-opacity", "type": "float", "doc": "The opacity of the building as a whole, including all walls.", "default-value": 1 }, "height": { "css": "building-height", "doc": "The height of the building in pixels.", "type": "expression", "default-value": "0" } } }, "colors": { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "grey": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50], "transparent": [0, 0, 0, 0] }, "filter": { "value": [ "true", "false", "null", "point", "linestring", "polygon", "collection" ] } }; CartoCSS['mapnik_reference'] = { version: { latest: _mapnik_reference_latest, '2.1.1': _mapnik_reference_latest } }; CartoCSS.Tree = {}; CartoCSS.Tree.operate = function(op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '%': return a % b; case '/': return a / b; } }; CartoCSS.Tree.functions = { rgb: function (r, g, b) { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { var me = this; var rgb = [r, g, b].map(function (c) { return me.number(c); }); a = me.number(a); if (rgb.some(isNaN) || isNaN(a)) {return null;} return new CartoCSS.Tree.Color(rgb, a); }, // Only require val stop: function (val) { var color, mode; if (arguments.length > 1) {color = arguments[1];} if (arguments.length > 2) {mode = arguments[2];} return { is: 'tag', val: val, color: color, mode: mode, toString(env) { return '\n\t'; } }; }, hsl: function (h, s, l) { return this.hsla(h, s, l, 1.0); }, hsla: function (h, s, l, a) { h = (this.number(h) % 360) / 360; s = this.number(s); l = this.number(l); a = this.number(a); if ([h, s, l, a].some(isNaN)) {return null;} var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s, m1 = l * 2 - m2; return this.rgba(hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255, a); function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) {return m1 + (m2 - m1) * h * 6;} else if (h * 2 < 1) {return m2;} else if (h * 3 < 2) {return m1 + (m2 - m1) * (2 / 3 - h) * 6;} else {return m1;} } }, hue: function (color) { if (!('toHSL' in color)) {return null;} return new CartoCSS.Tree.Dimension(Math.round(color.toHSL().h)); }, saturation: function (color) { if (!('toHSL' in color)) {return null;} return new CartoCSS.Tree.Dimension(Math.round(color.toHSL().s * 100), '%'); }, lightness: function (color) { if (!('toHSL' in color)) {return null;} return new CartoCSS.Tree.Dimension(Math.round(color.toHSL().l * 100), '%'); }, alpha: function (color) { if (!('toHSL' in color)) {return null;} return new CartoCSS.Tree.Dimension(color.toHSL().a); }, saturate: function (color, amount) { if (!('toHSL' in color)) {return null;} var hsl = color.toHSL(); hsl.s += amount.value / 100; hsl.s = this.clamp(hsl.s); return this.hsla_simple(hsl); }, desaturate: function (color, amount) { if (!('toHSL' in color)) {return null;} var hsl = color.toHSL(); hsl.s -= amount.value / 100; hsl.s = this.clamp(hsl.s); return this.hsla_simple(hsl); }, lighten: function (color, amount) { if (!('toHSL' in color)) {return null;} var hsl = color.toHSL(); hsl.l += amount.value / 100; hsl.l = this.clamp(hsl.l); return this.hsla_simple(hsl); }, darken: function (color, amount) { if (!('toHSL' in color)) {return null;} var hsl = color.toHSL(); hsl.l -= amount.value / 100; hsl.l = this.clamp(hsl.l); return this.hsla_simple(hsl); }, fadein: function (color, amount) { if (!('toHSL' in color)) {return null;} var hsl = color.toHSL(); hsl.a += amount.value / 100; hsl.a = this.clamp(hsl.a); return this.hsla_simple(hsl); }, fadeout: function (color, amount) { if (!('toHSL' in color)) {return null;} var hsl = color.toHSL(); hsl.a -= amount.value / 100; hsl.a = this.clamp(hsl.a); return this.hsla_simple(hsl); }, spin: function (color, amount) { if (!('toHSL' in color)) {return null;} var hsl = color.toHSL(); var hue = (hsl.h + amount.value) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return this.hsla_simple(hsl); }, replace: function (entity, a, b) { if (entity.is === 'field') { return entity.toString + '.replace(' + a.toString() + ', ' + b.toString() + ')'; } else { return entity.replace(a, b); } }, // // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein // http://sass-lang.com // mix: function (color1, color2, weight) { var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2]; var alpha = color1.alpha * p + color2.alpha * (1 - p); return new CartoCSS.Tree.Color(rgb, alpha); }, greyscale: function (color) { return this.desaturate(color, new CartoCSS.Tree.Dimension(100)); }, '%': function (quoted /* arg, arg, ...*/) { var args = Array.prototype.slice.call(arguments, 1), str = quoted.value; for (var i = 0; i < args.length; i++) { str = str.replace(/%s/, args[i].value) .replace(/%[da]/, args[i].toString()); } str = str.replace(/%%/g, '%'); return new CartoCSS.Tree.Quoted(str); }, hsla_simple: function (h) { return this.hsla(h.h, h.s, h.l, h.a); }, number: function (n) { if (n instanceof CartoCSS.Tree.Dimension) { return parseFloat(n.unit === '%' ? n.value / 100 : n.value); } else if (typeof(n) === 'number') { return n; } else { return NaN; } }, clamp: function (val) { return Math.min(1, Math.max(0, val)); } }; CartoCSS.Tree.Call = class Call { constructor(name, args, index) { this.is = 'call'; this.name = name; this.args = args; this.index = index; } // When evuating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, // or we simply print it out as it appeared originally [2]. // The *functions.js* file contains the built-in functions. // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. 'ev'(env) { var args = this.args.map(function (a) { return a.ev(env); }); for (var i = 0; i < args.length; i++) { if (args[i].is === 'undefined') { return { is: 'undefined', value: 'undefined' }; } } if (this.name in CartoCSS.Tree.functions) { if (CartoCSS.Tree.functions[this.name].length <= args.length) { var val = CartoCSS.Tree.functions[this.name].apply(CartoCSS.Tree.functions, args); if (val === null) { env.error({ message: 'incorrect arguments given to ' + this.name + '()', index: this.index, type: 'runtime', filename: this.filename }); return {is: 'undefined', value: 'undefined'}; } return val; } else { env.error({ message: 'incorrect number of arguments for ' + this.name + '(). ' + CartoCSS.Tree.functions[this.name].length + ' expected.', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } } else { var fn = CartoCSS.Tree.Reference.mapnikFunctions[this.name]; if (fn === undefined) { var functions = lodash_topairs_default()(CartoCSS.Tree.Reference.mapnikFunctions); // cheap closest, needs improvement. var name = this.name; var mean = functions.map(function (f) { return [f[0], CartoCSS.Tree.Reference.editDistance(name, f[0]), f[1]]; }).sort(function (a, b) { return a[1] - b[1]; }); env.error({ message: 'unknown function ' + this.name + '(), did you mean ' + mean[0][0] + '(' + mean[0][2] + ')', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } if (fn !== args.length && // support variable-arg functions like `colorize-alpha` fn !== -1) { env.error({ message: 'function ' + this.name + '() takes ' + fn + ' arguments and was given ' + args.length, index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } else { // Save the evaluated versions of arguments this.args = args; return this; } } } toString(env, format) { if (this.args.length) { return this.name + '(' + this.args.join(',') + ')'; } else { return this.name; } } }; CartoCSS.Tree.Color = class Color { constructor(rgb, a) { this.is = 'color'; // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. if (Array.isArray(rgb)) { this.rgb = rgb.slice(0, 3); } else if (rgb.length == 6) { this.rgb = rgb.match(/.{2}/g).map(function (c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function (c) { return parseInt(c + c, 16); }); } if (typeof(a) === 'number') { this.alpha = a; } else if (rgb.length === 4) { this.alpha = rgb[3]; } else { this.alpha = 1; } } 'ev'() { return this; } // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. toString() { /* if (this.alpha < 1.0) {*/ return 'rgba(' + this.rgb.map(function (c) { return Math.round(c); }).concat(this.alpha).join(', ') + ')'; /*} else { return '#' + this.rgb.map(function(i) { i = Math.round(i); i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); }*/ } // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. operate(env, op, other) { var result = []; if (!(other instanceof CartoCSS.Tree.Color)) { other = other.toColor(); } for (var c = 0; c < 3; c++) { result[c] = CartoCSS.Tree.operate(op, this.rgb[c], other.rgb[c]); } return new CartoCSS.Tree.Color(result); } toHSL() { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; default: break; } h /= 6; } return {h: h * 360, s: s, l: l, a: a}; } }; CartoCSS.Tree.Comment = class Comment { constructor(value, silent) { this.value = value; this.silent = !!silent; } toString(env) { return ''; } 'ev'() { return this; } }; CartoCSS.Tree.Definition = class Definition { constructor(selector, rules) { this.elements = selector.elements; //assert.ok(selector.filters instanceof CartoCSS.Tree.Filterset); this.rules = rules; this.ruleIndex = {}; for (var i = 0; i < this.rules.length; i++) { if ('zoom' in this.rules[i]) {this.rules[i] = this.rules[i].clone();} this.rules[i].zoom = selector.zoom; this.ruleIndex[this.rules[i].updateID()] = true; } this.filters = selector.filters; this.zoom = selector.zoom; this.attachment = selector.attachment || '__default__'; this.specificity = selector.specificity(); } toString() { var str = this.filters.toString(); for (var i = 0; i < this.rules.length; i++) { str += '\n ' + this.rules[i]; } return str; } toJS(env) { var shaderAttrs = {}; // merge conditions from filters with zoom condition of the // definition var zoom = this.zoom; //var frame_offset = this.frame_offset; var _if = this.filters.toJS(env); var filters = [zoom]; if (_if) {filters.push(_if);} //if(frame_offset) filters.push('ctx["frame-offset"] === ' + frame_offset); _if = filters.join(" && "); function eachRule(rule) { if (rule instanceof CartoCSS.Tree.Rule) { shaderAttrs[rule.name] = shaderAttrs[rule.name] || []; if (_if) { shaderAttrs[rule.name].push( "if(" + _if + "){" + rule.value.toJS(env) + "}" ); } else { shaderAttrs[rule.name].push(rule.value.toJS(env)); } } else { if (rule instanceof CartoCSS.Tree.Ruleset) { var sh = rule.toJS(env); for (var v in sh) { shaderAttrs[v] = shaderAttrs[v] || []; for (var attr in sh[v]) { shaderAttrs[v].push(sh[v][attr]); } } } } } for (var id in this.rules) { eachRule(this.rules[id]); } return shaderAttrs; } }; CartoCSS.Tree.Dimension = class Dimension { constructor(value, unit, index) { this.is = 'float'; this.physical_units = ['m', 'cm', 'in', 'mm', 'pt', 'pc']; this.screen_units = ['px', '%']; this.all_units = ['m', 'cm', 'in', 'mm', 'pt', 'pc', 'px', '%']; this.densities = { m: 0.0254, mm: 25.4, cm: 2.54, pt: 72, pc: 6 }; this.value = parseFloat(value); this.unit = unit || null; this.index = index; } ev(env) { if (this.unit && this.all_units.indexOf(this.unit)<0) { env.error({ message: "Invalid unit: '" + this.unit + "'", index: this.index }); return {is: 'undefined', value: 'undefined'}; } // normalize units which are not px or % if (this.unit && this.physical_units.indexOf(this.unit)>=0) { if (!env.ppi) { env.error({ message: "ppi is not set, so metric units can't be used", index: this.index }); return {is: 'undefined', value: 'undefined'}; } // convert all units to inch // convert inch to px using ppi this.value = (this.value / this.densities[this.unit]) * env.ppi; this.unit = 'px'; } return this; } toColor() { return new CartoCSS.Tree.Color([this.value, this.value, this.value]); } round() { this.value = Math.round(this.value); return this; } toString() { return this.value.toString(); } operate(env, op, other) { if (this.unit === '%' && other.unit !== '%') { env.error({ message: 'If two operands differ, the first must not be %', index: this.index }); return { is: 'undefined', value: 'undefined' }; } if (this.unit !== '%' && other.unit === '%') { if (op === '*' || op === '/' || op === '%') { env.error({ message: 'Percent values can only be added or subtracted from other values', index: this.index }); return { is: 'undefined', value: 'undefined' }; } return new CartoCSS.Tree.Dimension(CartoCSS.Tree.operate(op, this.value, this.value * other.value * 0.01), this.unit); } //here the operands are either the same (% or undefined or px), or one is undefined and the other is px return new CartoCSS.Tree.Dimension(CartoCSS.Tree.operate(op, this.value, other.value), this.unit || other.unit); } }; CartoCSS.Tree.Element = class Element { constructor(value) { this.value = value.trim(); if (this.value[0] === '#') { this.type = 'id'; this.clean = this.value.replace(/^#/, ''); } if (this.value[0] === '.') { this.type = 'class'; this.clean = this.value.replace(/^\./, ''); } if (this.value.indexOf('*') !== -1) { this.type = 'wildcard'; } } specificity() { return [ (this.type === 'id') ? 1 : 0, // a (this.type === 'class') ? 1 : 0 // b ]; } toString() { return this.value; } }; CartoCSS.Tree.Expression = class Expression { constructor(value) { this.is = 'expression'; this.value = value; } ev(env) { if (this.value.length > 1) { return new CartoCSS.Tree.Expression(this.value.map(function (e) { return e.ev(env); })); } else { return this.value[0].ev(env); } } toString(env) { return this.value.map(function (e) { return e.toString(env); }).join(' '); } }; CartoCSS.Tree.Field = class Field { constructor(content) { this.is = 'field'; this.value = content || ''; } toString() { return '["' + this.value.toUpperCase() + '"]'; } 'ev'() { return this; } }; CartoCSS.Tree.Filter = class Filter { constructor(key, op, val, index, filename) { this.ops = { '<': [' < ', 'numeric'], '>': [' > ', 'numeric'], '=': [' = ', 'both'], '!=': [' != ', 'both'], '<=': [' <= ', 'numeric'], '>=': [' >= ', 'numeric'], '=~': ['.match(', 'string', ')'] }; this.key = key; this.op = op; this.val = val; this.index = index; this.filename = filename; this.id = this.key + this.op + this.val; } ev(env) { this.key = this.key.ev(env); this.val = this.val.ev(env); return this; } toString() { return '[' + this.id + ']'; } }; CartoCSS.Tree.Filterset = class Filterset { constructor() { this.filters = {}; } toJS(env) { function eachFilter(filter) { var op = filter.op; if (op === "=") { op = "=="; } var val = filter.val; if (filter._val !== undefined) { val = filter._val.toString(true); } //对scale进行特殊处理,将值转换成数值 if (filter.key && filter.key.value === 'scale') { val = +val; } else if (typeof val === 'string' || typeof val === 'object') { val = "'" + val + "'"; } var attrs = "attributes"; return attrs + "&&" + attrs + filter.key + "&&" + attrs + filter.key + " " + op + val; } var results = []; for (var id in this.filters) { results.push(eachFilter(this.filters[id])); } return results.join(' && '); } toString() { var arr = []; for (var id in this.filters) {arr.push(this.filters[id].id);} return arr.sort().join('\t'); } ev(env) { for (var i in this.filters) { this.filters[i].ev(env); } return this; } clone() { var clone = new CartoCSS.Tree.Filterset(); for (var id in this.filters) { clone.filters[id] = this.filters[id]; } return clone; } cloneWith(other) { var additions = []; for (var id in other.filters) { var status = this.addable(other.filters[id]); // status is true, false or null. if it's null we don't fail this // clone nor do we add the filter. if (status === false) { return false; } if (status === true) { // Adding the filter will override another value. additions.push(other.filters[id]); } } // Adding the other filters doesn't make this filterset invalid, but it // doesn't add anything to it either. if (!additions.length) { return null; } // We can successfully add all filters. Now clone the filterset and add the // new rules. var clone = new CartoCSS.Tree.Filterset(); // We can add the rules that are already present without going through the // add function as a Filterset is always in it's simplest canonical form. for (id in this.filters) { clone.filters[id] = this.filters[id]; } // Only add new filters that actually change the filter. while (id = additions.shift()) { clone.add(id); } return clone; } addable(filter) { var key = filter.key.toString(), value = filter.val.toString(); if (value.match(/^[0-9]+(\.[0-9]*)?_match/)) {value = parseFloat(value);} switch (filter.op) { case '=': // if there is already foo= and we're adding foo= if (this.filters[key + '='] !== undefined) { if (this.filters[key + '='].val.toString() != value) { return false; } else { return null; } } if (this.filters[key + '!=' + value] !== undefined) {return false;} if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) {return false;} if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) {return false;} if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) {return false;} if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) {return false;} return true; case '=~': return true; case '!=': if (this.filters[key + '='] !== undefined) {return (this.filters[key + '='].val === value) ? false : null;} if (this.filters[key + '!=' + value] !== undefined) {return null;} if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) {return null;} if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) {return null;} if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) {return null;} if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) {return null;} return true; case '>': if (key + '=' in this.filters) { if (this.filters[key + '='].val <= value) { return false; } else { return null; } } if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) {return false;} if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val <= value) {return false;} if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) {return null;} if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) {return null;} return true; case '>=': if (this.filters[key + '='] !== undefined) {return (this.filters[key + '='].val < value) ? false : null;} if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) {return false;} if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) {return false;} if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) {return null;} if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val >= value) {return null;} return true; case '<': if (this.filters[key + '='] !== undefined) {return (this.filters[key + '='].val >= value) ? false : null;} if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) {return false;} if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val >= value) {return false;} if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) {return null;} if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val < value) {return null;} return true; case '<=': if (this.filters[key + '='] !== undefined) {return (this.filters[key + '='].val > value) ? false : null;} if (this.filters[key + '>'] !== undefined && this.filters[key + '>'].val >= value) {return false;} if (this.filters[key + '>='] !== undefined && this.filters[key + '>='].val > value) {return false;} if (this.filters[key + '<'] !== undefined && this.filters[key + '<'].val <= value) {return null;} if (this.filters[key + '<='] !== undefined && this.filters[key + '<='].val <= value) {return null;} return true; default: break; } } conflict(filter) { var key = filter.key.toString(), value = filter.val.toString(); if (!isNaN(parseFloat(value))) {value = parseFloat(value);} // if (a=b) && (a=c) // if (a=b) && (a!=b) // or (a!=b) && (a=b) if ((filter.op === '=' && this.filters[key + '='] !== undefined && value != this.filters[key + '='].val.toString()) || (filter.op === '!=' && this.filters[key + '='] !== undefined && value == this.filters[key + '='].val.toString()) || (filter.op === '=' && this.filters[key + '!='] !== undefined && value === this.filters[key + '!='].val.toString())) { return filter.toString() + ' added to ' + this.toString() + ' produces an invalid filter'; } return false; } add(filter, env) { var key = filter.key.toString(), op = filter.op, conflict = this.conflict(filter), numval; if (conflict) {return conflict;} if (op === '=') { for (var i in this.filters) { if (this.filters[i].key === key) {delete this.filters[i];} } this.filters[key + '='] = filter; } else if (op === '!=') { this.filters[key + '!=' + filter.val] = filter; } else if (op === '=~') { this.filters[key + '=~' + filter.val] = filter; } else if (op === '>') { // If there are other filters that are also > // but are less than this one, they don't matter, so // remove them. for (var j in this.filters) { if (this.filters[j].key === key && this.filters[j].val <= filter.val) { delete this.filters[j]; } } this.filters[key + '>'] = filter; } else if (op === '>=') { for (var k in this.filters) { numval = (+this.filters[k].val.toString()); if (this.filters[k].key === key && numval < filter.val) { delete this.filters[k]; } } if (this.filters[key + '!=' + filter.val] !== undefined) { delete this.filters[key + '!=' + filter.val]; filter.op = '>'; this.filters[key + '>'] = filter; } else { this.filters[key + '>='] = filter; } } else if (op === '<') { for (var l in this.filters) { numval = (+this.filters[l].val.toString()); if (this.filters[l].key === key && numval >= filter.val) { delete this.filters[l]; } } this.filters[key + '<'] = filter; } else if (op === '<=') { for (var m in this.filters) { numval = (+this.filters[m].val.toString()); if (this.filters[m].key === key && numval > filter.val) { delete this.filters[m]; } } if (this.filters[key + '!=' + filter.val] !== undefined) { delete this.filters[key + '!=' + filter.val]; filter.op = '<'; this.filters[key + '<'] = filter; } else { this.filters[key + '<='] = filter; } } } }; CartoCSS.Tree.Fontset = class Fontset { constructor(env, fonts) { this.fonts = fonts; this.name = 'fontset-' + env.effects.length; } }; CartoCSS.Tree.Invalid = class Invalid { constructor(chunk, index, message) { this.is = 'invalid'; this.chunk = chunk; this.index = index; this.type = 'syntax'; this.message = message || "Invalid code: " + this.chunk; } ev(env) { env.error({ chunk: this.chunk, index: this.index, type: 'syntax', message: this.message || "Invalid code: " + this.chunk }); return { is: 'undefined' }; } }; CartoCSS.Tree.Keyword = class Keyword { ev() { return this; } constructor(value) { this.value = value; var special = { 'transparent': 'color', 'true': 'boolean', 'false': 'boolean' }; this.is = special[value] ? special[value] : 'keyword'; } toString() { return this.value; } }; /*Layer:class Invalid ),*/ CartoCSS.Tree.Literal = class Literal { constructor(content) { this.value = content || ''; this.is = 'field'; } toString() { return this.value; } 'ev'() { return this; } }; CartoCSS.Tree.Operation = class Operation { constructor(op, operands, index) { this.is = 'operation'; this.op = op.trim(); this.operands = operands; this.index = index; } ev(env) { var a = this.operands[0].ev(env), b = this.operands[1].ev(env), temp; if (a.is === 'undefined' || b.is === 'undefined') { return { is: 'undefined', value: 'undefined' }; } if (a instanceof CartoCSS.Tree.Dimension && b instanceof CartoCSS.Tree.Color) { if (this.op === '*' || this.op === '+') { temp = b; b = a; a = temp; } else { env.error({ name: "OperationError", message: "Can't substract or divide a color from a number", index: this.index }); } } // Only concatenate plain strings, because this is easily // pre-processed if (a instanceof CartoCSS.Tree.Quoted && b instanceof CartoCSS.Tree.Quoted && this.op !== '+') { env.error({ message: "Can't subtract, divide, or multiply strings.", index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } // Fields, literals, dimensions, and quoted strings can be combined. if (a instanceof CartoCSS.Tree.Field || b instanceof CartoCSS.Tree.Field || a instanceof CartoCSS.Tree.Literal || b instanceof CartoCSS.Tree.Literal) { if (a.is === 'color' || b.is === 'color') { env.error({ message: "Can't subtract, divide, or multiply colors in expressions.", index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } else { return new CartoCSS.Tree.Literal(a.ev(env).toString(true) + this.op + b.ev(env).toString(true)); } } if (a.operate === undefined) { env.error({ message: 'Cannot do math with type ' + a.is + '.', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } return a.operate(env, this.op, b); } }; CartoCSS.Tree.Quoted = class Quoted { constructor(content) { this.is = 'string'; this.value = content || ''; } toString(quotes) { var escapedValue = this.value .replace(/&/g, '&') var xmlvalue = escapedValue .replace(/\'/g, '\\\'') .replace(/\"/g, '"') .replace(//g, '>'); return (quotes === true) ? "'" + xmlvalue + "'" : escapedValue; } ev() { return this; } operate(env, op, other) { return new CartoCSS.Tree.Quoted(CartoCSS.Tree.operate(op, this.toString(), other.toString(this.contains_field))); } }; CartoCSS.Tree.Reference = { _validateValue: { 'font': function (env, value) { if (env.validation_data && env.validation_data.fonts) { return env.validation_data.fonts.indexOf(value) != -1; } else { return true; } } }, setData: function (data) { this.data = data; this.selector_cache = generateSelectorCache(data); this.mapnikFunctions = generateMapnikFunctions(data); this.required_cache = generateRequiredProperties(data); function generateSelectorCache(data) { var index = {}; for (var i in data.symbolizers) { for (var j in data.symbolizers[i]) { if (data.symbolizers[i][j].hasOwnProperty('css')) { index[data.symbolizers[i][j].css] = [data.symbolizers[i][j], i, j]; } } } return index; } function generateMapnikFunctions(data) { var functions = {}; for (var i in data.symbolizers) { for (var j in data.symbolizers[i]) { if (data.symbolizers[i][j].type === 'functions') { for (var k = 0; k < data.symbolizers[i][j].functions.length; k++) { var fn = data.symbolizers[i][j].functions[k]; functions[fn[0]] = fn[1]; } } } } return functions; } function generateRequiredProperties(data) { var cache = {}; for (var symbolizer_name in data.symbolizers) { cache[symbolizer_name] = []; for (var j in data.symbolizers[symbolizer_name]) { if (data.symbolizers[symbolizer_name][j].required) { cache[symbolizer_name].push(data.symbolizers[symbolizer_name][j].css); } } } return cache; } }, setVersion: function (version) { if (CartoCSS.mapnik_reference.version.hasOwnProperty(version)) { this.setData(CartoCSS.mapnik_reference.version[version]); return true; } return false; }, selectorData: function (selector, i) { if (this.selector_cache && this.selector_cache[selector]) {return this.selector_cache[selector][i];} }, validSelector: function (selector) { return !!this.selector_cache[selector]; }, selectorName: function (selector) { return this.selectorData(selector, 2); }, selector: function (selector) { return this.selectorData(selector, 0); }, symbolizer: function (selector) { return this.selectorData(selector, 1); }, requiredProperties: function (symbolizer_name, rules) { var req = this.required_cache[symbolizer_name]; for (var i in req) { if (!(req[i] in rules)) { return 'Property ' + req[i] + ' required for defining ' + symbolizer_name + ' styles.'; } } }, isFont: function (selector) { return this.selector(selector).validate === 'font'; }, editDistance: function (a, b) { if (a.length === 0) {return b.length;} if (b.length === 0) {return a.length;} var matrix = []; for (var i = 0; i <= b.length; i++) { matrix[i] = [i]; } for (var j = 0; j <= a.length; j++) { matrix[0][j] = j; } for (i = 1; i <= b.length; i++) { for (j = 1; j <= a.length; j++) { if (b.charAt(i - 1) === a.charAt(j - 1)) { matrix[i][j] = matrix[i - 1][j - 1]; } else { matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution Math.min(matrix[i][j - 1] + 1, // insertion matrix[i - 1][j] + 1)); // deletion } } } return matrix[b.length][a.length]; }, validValue: function (env, selector, value) { function validateFunctions(value, selector) { if (value.value[0].is === 'string') {return true;} for (var i in value.value) { for (var j in value.value[i].value) { if (value.value[i].value[j].is !== 'call') {return false;} var f = find(this.selector(selector).functions, function (x) {//NOSONAR return x[0] === value.value[i].value[j].name; }); if (!(f && f[1] === -1)) { // This filter is unknown or given an incorrect number of arguments if (!f || f[1] !== value.value[i].value[j].args.length) {return false;} } } } return true; } function validateKeyword(value, selector) { if (typeof this.selector(selector).type === 'object') { return this.selector(selector).type .indexOf(value.value[0].value) !== -1; } else { // allow unquoted keywords as strings return this.selector(selector).type === 'string'; } } var i; if (!this.selector(selector)) { return false; } else if (value.value[0].is === 'keyword') { return validateKeyword(value, selector); } else if (value.value[0].is === 'undefined') { // caught earlier in the chain - ignore here so that // error is not overridden return true; } else if (this.selector(selector).type === 'numbers') { for (i in value.value) { if (value.value[i].is !== 'float') { return false; } } return true; } else if (this.selector(selector).type === 'tags') { if (!value.value) {return false;} if (!value.value[0].value) { return value.value[0].is === 'tag'; } for (i = 0; i < value.value[0].value.length; i++) { if (value.value[0].value[i].is !== 'tag') {return false;} } return true; } else if (this.selector(selector).type == 'functions') { // For backwards compatibility, you can specify a string for `functions`-compatible // values, though they will not be validated. return validateFunctions(value, selector); } else if (this.selector(selector).type === 'expression') { return true; } else if (this.selector(selector).type === 'unsigned') { if (value.value[0].is === 'float') { value.value[0].round(); return true; } else { return false; } } else { if (this.selector(selector).validate) { var valid = false; for (i = 0; i < value.value.length; i++) { if (this.selector(selector).type === value.value[i].is && this._validateValue[this.selector(selector).validate](env, value.value[i].value)) { return true; } } return valid; } else { return this.selector(selector).type === value.value[0].is; } } } }; CartoCSS.Tree.Reference.setVersion("latest"); CartoCSS.Tree.Rule = class Rule { constructor(name, value, index, filename) { this.is = 'rule'; var parts = name.split('/'); this.name = parts.pop(); this.instance = parts.length ? parts[0] : '__default__'; this.value = (value instanceof CartoCSS.Tree.Value) ? value : new CartoCSS.Tree.Value([value]); this.index = index; this.symbolizer = CartoCSS.Tree.Reference.symbolizer(this.name); this.filename = filename; this.variable = (name.charAt(0) === '@'); } clone() { var clone = Object.create(CartoCSS.Tree.Rule.prototype); clone.name = this.name; clone.value = this.value; clone.index = this.index; clone.instance = this.instance; clone.symbolizer = this.symbolizer; clone.filename = this.filename; clone.variable = this.variable; return clone; } updateID() { return this.id = this.zoom + '#' + this.instance + '#' + this.name; } toString() { return '[' + CartoCSS.Tree.Zoom.toString(this.zoom) + '] ' + this.name + ': ' + this.value; } ev(context) { return new CartoCSS.Tree.Rule(this.name, this.value.ev(context), this.index, this.filename); } }; CartoCSS.Tree.Ruleset = class Ruleset { constructor(selectors, rules) { this.is = 'ruleset'; this.selectors = selectors; this.rules = rules; // static cache of find() function this._lookups = {}; } ev(env) { var i, rule, ruleset = new CartoCSS.Tree.Ruleset(this.selectors, this.rules.slice(0)); ruleset.root = this.root; // push the current ruleset to the frames stack env.frames.unshift(ruleset); // Evaluate everything else for (i = 0, rule; i < ruleset.rules.length; i++) { rule = ruleset.rules[i]; ruleset.rules[i] = rule.ev ? rule.ev(env) : rule; } // Pop the stack env.frames.shift(); return ruleset; } match(args) { return !args || args.length === 0; } variables() { if (this._variables) { return this._variables; } else { return this._variables = this.rules.reduce(function (hash, r) { if (r instanceof CartoCSS.Tree.Rule && r.variable === true) { hash[r.name] = r; } return hash; }, {}); } } variable(name) { return this.variables()[name]; } rulesets() { if (this._rulesets) { return this._rulesets; } else { return this._rulesets = this.rules.filter(function (r) { return (r instanceof CartoCSS.Tree.Ruleset); }); } } find(selector, self) { self = self || this; var rules = [], match, key = selector.toString(); if (key in this._lookups) { return this._lookups[key]; } this.rulesets().forEach(function (rule) { if (rule !== self) { for (var j = 0; j < rule.selectors.length; j++) { match = selector.match(rule.selectors[j]); if (match) { if (selector.elements.length > 1) { Array.prototype.push.apply(rules, rule.find( new CartoCSS.Tree.Selector(null, null, selector.elements.slice(1)), self)); } else { rules.push(rule); } break; } } } }); return this._lookups[key] = rules; } // Zooms can use variables. This replaces CartoCSS.Tree.Zoom objects on selectors // with simple bit-arrays that we can compare easily. evZooms(env) { for (var i = 0; i < this.selectors.length; i++) { var zval = CartoCSS.Tree.Zoom.all; for (var z = 0; z < this.selectors[i].zoom.length; z++) { zval = this.selectors[i].zoom[z].ev(env).zoom; } this.selectors[i].zoom = zval; } } flatten(result, parents, env) { var selectors = [], i, j; if (this.selectors.length === 0) { env.frames = env.frames.concat(this.rules); } // evaluate zoom variables on this object. this.evZooms(env); for (i = 0; i < this.selectors.length; i++) { var child = this.selectors[i]; if (!child.filters) { // This is an invalid filterset. continue; } if (parents.length) { for (j = 0; j < parents.length; j++) { var parent = parents[j]; var mergedFilters = parent.filters.cloneWith(child.filters); if (mergedFilters === null) { // Filters could be added, but they didn't change the // filters. This means that we only have to clone when // the zoom levels or the attachment is different too. if (parent.zoom === child.zoom && parent.attachment === child.attachment && parent.elements.join() === child.elements.join()) { selectors.push(parent); continue; } else { mergedFilters = parent.filters; } } else if (!mergedFilters) { // The merged filters are invalid, that means we don't // have to clone. continue; } var clone = Object.create(CartoCSS.Tree.Selector.prototype); clone.filters = mergedFilters; clone.zoom = child.zoom; clone.elements = parent.elements.concat(child.elements); if (parent.attachment && child.attachment) { clone.attachment = parent.attachment + '/' + child.attachment; } else {clone.attachment = child.attachment || parent.attachment;} clone.conditions = parent.conditions + child.conditions; clone.index = child.index; selectors.push(clone); } } else { selectors.push(child); } } var rules = []; for (i = 0; i < this.rules.length; i++) { var rule = this.rules[i]; // Recursively flatten any nested rulesets if (rule instanceof CartoCSS.Tree.Ruleset) { rule.flatten(result, selectors, env); } else if (rule instanceof CartoCSS.Tree.Rule) { rules.push(rule); } else if (rule instanceof CartoCSS.Tree.Invalid) { env.error(rule); } } var index = rules.length ? rules[0].index : false; for (i = 0; i < selectors.length; i++) { // For specificity sort, use the position of the first rule to allow // defining attachments that are under current element as a descendant // selector. if (index !== false) { selectors[i].index = index; } result.push(new CartoCSS.Tree.Definition(selectors[i], rules.slice())); } return result; } }; CartoCSS.Tree.Selector = class Selector { constructor(filters, zoom, elements, attachment, conditions, index) { this.elements = elements || []; this.attachment = attachment; this.filters = filters || {}; this.zoom = typeof zoom !== 'undefined' ? zoom : CartoCSS.Tree.Zoom.all; this.conditions = conditions; this.index = index; } specificity() { return this.elements.reduce(function (memo, e) { var spec = e.specificity(); memo[0] += spec[0]; memo[1] += spec[1]; return memo; }, [0, 0, this.conditions, this.index]); } }; /*style:class Invalid ),*/ CartoCSS.Tree.URL = class URL { constructor(val, paths) { this.is = 'uri'; this.value = val; this.paths = paths; } toString() { return this.value.toString(); } ev(ctx) { return new CartoCSS.Tree.URL(this.value.ev(ctx), this.paths); } }; CartoCSS.Tree.Value = class Value { constructor(value) { this.is = 'value'; this.value = value; } ev(env) { if (this.value.length === 1) { return this.value[0].ev(env); } else { return new CartoCSS.Tree.Value(this.value.map(function (v) { return v.ev(env); })); } } toJS(env) { //var v = this.value[0].value[0]; var val = this.ev(env); var v = val.toString(); if (val.is === "color" || val.is === 'uri' || val.is === 'string' || val.is === 'keyword') { v = "'" + v + "'"; } else if (val.is === 'field') { // replace [varuable] by ctx['variable'] v = v.replace(/\[(.*)\]/g, "attributes['\_match1']") } else if (val.value && typeof val.value === "object") { v = "[" + v + "]"; } return "_value = " + v + ";"; } toString(env, selector, sep, format) { return this.value.map(function (e) { return e.toString(env, format); }).join(sep || ', '); } clone() { var obj = Object.create(CartoCSS.Tree.Value.prototype); if (Array.isArray(obj)) {obj.value = this.value.slice();} else {obj.value = this.value;} obj.is = this.is; return obj; } }; CartoCSS.Tree.Variable = class Variable { constructor(name, index, filename) { this.is = 'variable'; this.name = name; this.index = index; this.filename = filename; } toString() { return this.name; } ev(env) { if (this._css) {return this._css;} var thisframe = env.frames.filter(function (f) { return f.name === this.name; }.bind(this)); if (thisframe.length) { return thisframe[0].value.ev(env); } else { env.error({ message: 'variable ' + this.name + ' is undefined', index: this.index, type: 'runtime', filename: this.filename }); return { is: 'undefined', value: 'undefined' }; } } }; CartoCSS.Tree.Zoom = class Zoom { constructor(op, value, index) { this.op = op; this.value = value; this.index = index; } setZoom(zoom) { this.zoom = zoom; return this; } ev(env) { var value = parseInt(this.value.ev(env).toString(), 10); if (value > CartoCSS.Tree.Zoom.maxZoom || value < 0) { env.error({ message: 'Only zoom levels between 0 and ' + CartoCSS.Tree.Zoom.maxZoom + ' supported.', index: this.index }); } switch (this.op) { case '=': this.zoom = "zoom && zoom === " + value; return this; case '>': this.zoom = "zoom && zoom > " + value; break; case '>=': this.zoom = "zoom && zoom >= " + value; break; case '<': this.zoom = "zoom && zoom < " + value; break; case '<=': this.zoom = "zoom && zoom <= " + value; break; default: break; } /* for (var i = 0; i <= CartoCSS.Tree.Zoom.maxZoom; i++) { if (i >= start && i <= end) { zoom |= (1 << i); } } this.zoom = zoom; this.zoom=value+this.op+"zoom";*/ return this; } toString() { var str = ''; for (var i = 0; i <= CartoCSS.Tree.Zoom.maxZoom; i++) { str += (this.zoom & (1 << i)) ? 'X' : '.'; } return str; } }; // Covers all zoomlevels from 0 to 22 CartoCSS.Tree.Zoom.all = 23; CartoCSS.Tree.Zoom.maxZoom = 22; CartoCSS.Tree.Zoom.ranges = { 0: 1000000000, 1: 500000000, 2: 200000000, 3: 100000000, 4: 50000000, 5: 25000000, 6: 12500000, 7: 6500000, 8: 3000000, 9: 1500000, 10: 750000, 11: 400000, 12: 200000, 13: 100000, 14: 50000, 15: 25000, 16: 12500, 17: 5000, 18: 2500, 19: 1500, 20: 750, 21: 500, 22: 250, 23: 100 }; ;// CONCATENATED MODULE: ./src/common/style/ThemeStyle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeStyle * @deprecatedclass SuperMap.ThemeStyle * @classdesc 客户端专题图风格类。 * @category Visualization Theme * @param {Object} options - 可选参数。 * @param {boolean} [options.fill=true] - 是否填充,不需要填充则设置为 false。如果 fill 与 stroke 同时为 false,将按 fill 与 stroke 的默认值渲染图层。 * @param {string} [options.fillColor='#000000'] - 十六进制填充颜色。 * @param {number} [options.fillOpacity=1] - 填充不透明度。取值范围[0, 1]。 * @param {boolean} [options.stroke=false] - 是否描边,不需要描边则设置为false。如果 fill 与 stroke 同时为 false,将按 fill 与 stroke 的默认值渲染图层。 * @param {string} [options.strokeColor='#000000'] - 十六进制描边颜色。 * @param {number} [options.strokeOpacity=1] - 描边的不透明度。取值范围[0, 1]。 * @param {number} [options.strokeWidth=1] - 线宽度/描边宽度。 * @param {string} [options.strokeLinecap='butt'] - 线帽样式。strokeLinecap 有三种类型 “butt", "round", "square"。 * @param {string} [options.strokeLineJoin='iter'] - 线段连接样式。strokeLineJoin 有三种类型 “miter", "round", "bevel"。 * @param {string} [options.strokeDashstyle='solid'] - 虚线类型。strokeDashstyle 有八种类型 “dot",“dash",“dashdot",“longdash",“longdashdot",“solid", "dashed", "dotted"。solid 表示实线。 * @param {number} [options.pointRadius=6] - 点半径,单位为像素。 * @param {number} [options.shadowBlur=0] - 阴影模糊度,(大于 0 有效)。注:请将 shadowColor 属性与 shadowBlur 属性一起使用,来创建阴影。 * @param {string} [options.shadowColor='#000000'] - 阴影颜色。注:请将 shadowColor 属性与 shadowBlur 属性一起使用,来创建阴影。 * @param {number} [options.shadowOffsetX=0] - 阴影 X 方向偏移值。 * @param {number} [options.shadowOffsetY=0] - 阴影 Y 方向偏移值。 * @param {string} options.label - 专题要素附加文本标签内容。 * @param {string} [options.fontColor] - 附加文本字体颜色。 * @param {number} [options.fontSize=12] - 附加文本字体大小,单位是像素。 * @param {string} [options.fontStyle='normal'] - 附加文本字体样式。可设值:"normal", "italic", "oblique"。 * @param {string} [options.fontVariant='normal'] - 附加文本字体变体。可设值:"normal", "small-caps"。 * @param {string} [options.fontWeight='normal'] - 附加文本字体粗细。可设值:"normal", "bold", "bolder", "lighter"。 * @param {string} [options.fontFamily='arial,sans-serif'] - 附加文本字体系列。fontFamily 值是字体族名称或/及类族名称的一个优先表,每个值逗号分割, * 浏览器会使用它可识别的第一个可以使用具体的字体名称("times"、"courier"、"arial")或字体系列名称 * ("serif"、"sans-serif"、"cursive"、"fantasy"、"monospace")。 * @param {string} [options.labelPosition='top'] - 附加文本位置,可以是 'inside', 'left', 'right', 'top', 'bottom'。 * @param {string} [options.labelAlign='center'] - 附加文本水平对齐。可以是 'left', 'right', 'center'。 * @param {string} [options.labelBaseline='middle'] - 附加文本垂直对齐。可以是 'top', 'bottom', 'middle' 。 * @param {number} [options.labelXOffset=0] - 附加文本在x轴方向的偏移量。 * @param {number} [options.labelYOffset=0] - 附加文本在y轴方向的偏移量。 * @usage */ class ThemeStyle { constructor(options) { options = options || {}; /** * @member {boolean} [ThemeStyle.prototype.fill=true] * @description 是否填充,不需要填充则设置为 false。如果 fill 与 stroke 同时为 false,将按 fill 与 stroke 的默认值渲染图层。 */ this.fill = true; /** * @member {string} [ThemeStyle.prototype.fillColor="#000000"] * @description 十六进制填充颜色。 */ this.fillColor = "#000000"; /** * @member {number} [ThemeStyle.prototype.fillOpacity=1] * @description 填充不透明度。取值范围[0, 1]。 */ this.fillOpacity = 1; /** * @member {boolean} [ThemeStyle.prototype.stroke=false] * @description 是否描边,不需要描边则设置为false。如果 fill 与 stroke 同时为 false,将按 fill 与 stroke 的默认值渲染图层。 */ this.stroke = false; /** * @member {string} [ThemeStyle.prototype.strokeColor="#000000"] * @description 十六进制描边颜色。 */ this.strokeColor = "#000000"; /** * @member {number} [ThemeStyle.prototype.strokeOpacity=1] * @description 描边的不透明度。取值范围[0, 1]。 */ this.strokeOpacity = 1; /** * @member {number} [ThemeStyle.prototype.strokeWidth=1] * @description 线宽度/描边宽度。 */ this.strokeWidth = 1; /** * @member {string} [ThemeStyle.prototype.strokeLinecap="butt"] * @description 线帽样式;strokeLinecap 有三种类型 “butt", "round", "square" 。 */ this.strokeLinecap = "butt"; /** * @member {string} [ThemeStyle.prototype.strokeLineJoin="miter"] * @description 线段连接样式;strokeLineJoin 有三种类型 “miter", "round", "bevel"。 */ this.strokeLineJoin = "miter"; /** * @member {string} [ThemeStyle.prototype.strokeDashstyle="solid"] * @description 虚线类型;strokeDashstyle 有八种类型 “dot",“dash",“dashdot",“longdash",“longdashdot",“solid", "dashed", "dotted"; * solid 表示实线。 */ this.strokeDashstyle = "solid"; /** * @member {number} [ThemeStyle.prototype.pointRadius=6] * @description 点半径。单位为像素。 */ this.pointRadius = 6; /** * @member {number} [ThemeStyle.prototype.shadowBlur=0] * @description 阴影模糊度,(大于 0 有效)。注:请将 shadowColor 属性与 shadowBlur 属性一起使用,来创建阴影。 */ this.shadowBlur = 0; /** * @member {string} [ThemeStyle.prototype.shadowColor='#000000'] * @description 阴影颜色。注:请将 shadowColor 属性与 shadowBlur 属性一起使用,来创建阴影。 */ this.shadowColor = "#000000"; /** * @member {number} [ThemeStyle.prototype.shadowOffsetX=0] * @description 阴影 X 方向偏移值。 */ this.shadowOffsetX = 0; /** * @member {number} ThemeStyle.prototype.shadowOffsetY * @description Y 方向偏移值。 */ this.shadowOffsetY = 0; /** * @member {string} [ThemeStyle.prototype.label] * @description 专题要素附加文本标签内容。 */ this.label = ""; /** * @member {boolean} [ThemeStyle.prototype.labelRect=false] * @description 是否显示文本标签矩形背景。 */ this.labelRect = false; /** * @member {string} [ThemeStyle.prototype.fontColor] * @description 附加文本字体颜色。 */ this.fontColor = ""; /** * @member {number} [ThemeStyle.prototype.fontSize=12] * @description 附加文本字体大小,单位是像素。 */ this.fontSize = 12; /** * @member {string} [ThemeStyle.prototype.fontStyle="normal"] * @description 附加文本字体样式。可设值:"normal", "italic", "oblique"。 */ this.fontStyle = "normal"; /** * @member {string} [ThemeStyle.prototype.fontVariant="normal"] * @description 附加文本字体变体。可设值:"normal", "small-caps"。 */ this.fontVariant = "normal"; /** * @member {string} [ThemeStyle.prototype.fontWeight="normal"] * @description 附加文本字体粗细。可设值:"normal", "bold", "bolder", "lighter"。 */ this.fontWeight = "normal"; /** * @member {string} [ThemeStyle.prototype.fontFamily="arial,sans-serif"] * @description 附加文本字体系列。fontFamily 值是字体族名称或/及类族名称的一个优先表,每个值逗号分割,浏览器会使用它可识别的第一个 * 可以使用具体的字体名称("times"、"courier"、"arial")或字体系列名称("serif"、"sans-serif"、"cursive"、"fantasy"、"monospace")。 */ this.fontFamily = "arial,sans-serif"; /** * @member {string} [ThemeStyle.prototype.labelPosition='top'] * @description 附加文本位置,可以是 'inside', 'left', 'right', 'top', 'bottom'。 */ this.labelPosition = "top"; /** * @member {string} [ThemeStyle.prototype.labelAlign='center'] * @description 附加文本水平对齐。可以是 'left', 'right', 'center'。 */ this.labelAlign = "center"; /** * @member {string} [ThemeStyle.prototype.labelBaseline='middle'] * @description 附加文本垂直对齐。可以是 'top', 'bottom', 'middle'。 */ this.labelBaseline = "middle"; /** * @member {number} [ThemeStyle.prototype.labelXOffset=0] * @description 附加文本在 X 轴方向的偏移量。 */ this.labelXOffset = 0; /** * @member {number} [ThemeStyle.prototype.labelYOffset=0] * @description 附加文本在 Y 轴方向的偏移量。 */ this.labelYOffset = 0; Util.extend(this, options); } } ;// CONCATENATED MODULE: ./src/common/style/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/overlay/feature/ShapeParameters.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParameters * @aliasclass Feature.ShapeParameters * @deprecatedclass SuperMap.Feature.ShapeParameters * @category Visualization Theme * @classdesc 图形参数基类 * @usage */ class ShapeParameters { constructor() { /** * @member {Array.} [ShapeParameters.prototype.refOriginalPosition=[0,0]] * @description 图形参考原点位置,图形的参考中心位置。 * refOriginalPosition 是长度为 2 的数组,第一个元素表示 x 坐标,第二个元素表示 y 坐标。 * refOriginalPosition 表示图形的参考中心,通常情况下,图形是使用 canvas 的原点位置作为位置参考, * 但 refOriginalPosition 可以改变图形的参考位置,例如: refOriginalPosition = [80, 80], * 图形圆的 style.x = 20, style.y = 20,那么圆在 canvas 中的实际位置是 [100, 100]。 * 图形(Shape)的所有位置相关属性都是以 refOriginalPosition 为参考中心, * 也就是说图形的所有位置信息在 canvas 中都是以 refOriginalPosition 为参考的相对位置,只有 * refOriginalPosition 的值为 [0, 0] 时,图形的位置信息才是 canvas 绝对位置。 * 图形的位置信息通常有:style.pointList,style.x,style.y。 */ this.refOriginalPosition = [0, 0]; /** * @member {string} ShapeParameters.prototype.refDataID * @description 图形所关联数据的 ID(<{@link FeatureVector}> 的 ID)。 */ this.refDataID = null; /** * @member {boolean} ShapeParameters.prototype.isHoverByRefDataID * @description 是否根据 refDataID 进行高亮。用于同时高亮所有 refDataID 相同的图形。 */ this.isHoverByRefDataID = false; /** * @member {string} ShapeParameters.prototype.refDataHoverGroup * @description 高亮图形组的组名。此属性在 refDataID 有效且 isHoverByRefDataID 为 true 时生效。 * 一旦设置此属性,且属性值有效,只有关联同一个数据的图形且此属性相同的图形才会高亮。 */ this.refDataHoverGroup = null; /** * @member {Object} ShapeParameters.prototype.dataInfo * @description 图形携带的附加数据。 */ this.dataInfo = null; /** * @member {boolean} ShapeParameters.prototype.clickable * @description 是否可点击。 */ this.clickable = true; /** * @member {boolean} ShapeParameters.prototype.hoverable * @description 是否可点击。 */ this.hoverable = true; /** * @member {Object} ShapeParameters.prototype.style * @description 图形样式对象,可设样式属性在子类中确定。 */ this.style = null; /** * @member {Object} ShapeParameters.prototype.highlightStyle * @description 高亮样式对象,可设样式属性与 style 的可设样式属性相同。 */ this.highlightStyle = {}; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters"; } /** * @function ShapeParameters.prototype.destroy * @description 销毁对象。 */ destroy() { this.refOriginalPosition = null; this.refDataID = null; this.isHoverByRefDataID = null; this.refDataHoverGroup = null; this.dataInfo = null; this.clickable = null; this.hoverable = null; this.style = null; this.highlightStyle = null; } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Point.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParametersPoint * @aliasclass Feature.ShapeParameters.Point * @deprecatedclass SuperMap.Feature.ShapeParameters.Point * @category Visualization Theme * @classdesc 点参数对象。 * @extends {ShapeParameters} * @param {number} x - 点 x 坐标。 * @param {number} y - 点 y 坐标。 * @usage */ class Point_Point extends ShapeParameters { constructor(x, y) { super(x, y); /** * @member {number} ShapeParametersPoint.prototype.x * @description 点 x 坐标。 */ this.x = !isNaN(x) ? x : 0; /** * @member {number} ShapeParametersPoint.prototype.y * @description 点 y 坐标。 */ this.y = !isNaN(y) ? y : 0; /** * @member {number} ShapeParametersPoint.prototype.r * @description 点的半径。 */ this.r = 6; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters.Point"; } /** * @function ShapeParametersPoint.prototype.destroy * @description 销毁对象。 */ destroy() { this.x = null; this.y = null; this.r = null; super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Line.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParametersLine * @aliasclass Feature.ShapeParameters.Line * @deprecatedclass SuperMap.Feature.ShapeParameters.Line * @category Visualization Theme * @classdesc 线参数对象。 * @extends {ShapeParameters} * @param {Array} pointList - 线要素节点数组,二维数组。 * @usage */ class Line_Line extends ShapeParameters { constructor(pointList) { super(pointList); /** * @member {Array} ShapeParametersLine.prototype.pointList * @description 线要素节点数组,二维数组。 * 数组形如: * (start code) * [ * [10, 20], //节点 * [30, 40], * [25, 30] //最后一个节点和第一个节点不必相同,绘制时自动封闭 * ] * (end) */ this.pointList = pointList; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters.Line"; } /** * @function ShapeParametersLine.prototype.destroy * @description 销毁对象。 */ destroy() { this.pointList = null; super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Polygon.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParametersPolygon * @aliasclass Feature.ShapeParameters.Polygon * @deprecatedclass SuperMap.Feature.ShapeParameters.Polygon * @category Visualization Theme * @classdesc 面参数对象。 * @extends {ShapeParameters} * @param {Array} pointList - 横坐标。 * @usage */ class Polygon_Polygon extends ShapeParameters { constructor(pointList) { super(pointList); /** * @member {Array} ShapeParametersPolygon.prototype.pointList * @description 面要素节点数组,二维数组。 * 数组形如: * (start code) * [ * [10, 20], //节点 * [30, 40], * [25, 30] //最后一个节点和第一个节点不必相同,绘制时自动封闭 * ] * (end) */ this.pointList = pointList; /** * @member {Array} ShapeParametersPolygon.prototype.holePolygonPointLists * @description 岛洞面多边形顶点数组(三维数组) */ this.holePolygonPointLists = null; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters.Polygon"; } /** * @function ShapeParametersPolygon.prototype.destroy * @description 销毁对象。 */ destroy() { this.pointList = null; this.holePolygonPointLists = null; super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Rectangle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParametersRectangle * @aliasclass Feature.ShapeParameters.Rectangle * @deprecatedclass SuperMap.Feature.ShapeParameters.Rectangle * @category Visualization Theme * @classdesc 矩形参数对象。 * @extends {ShapeParameters} * @param {number} x - 矩形 x 坐标。 * @param {number} y - 矩形 y 坐标。 * @param {number} width - 矩形 width 宽度。 * @param {number} height - 矩形 height 高度。 * @usage */ class Rectangle_Rectangle extends ShapeParameters { constructor(x, y, width, height) { super(x, y, width, height); /** * @member {number} ShapeParametersRectangle.prototype.x * @description 左上角 x 坐标。 */ this.x = !isNaN(x) ? x : 0; /** * @member {number} ShapeParametersRectangle.prototype.y * @description 左上角 y 坐标。 */ this.y = !isNaN(x) ? y : 0; /** * @member {number} ShapeParametersRectangle.prototype.width * @description 宽度。 */ this.width = !isNaN(width) ? width : 0; /** * @member {number} ShapeParametersRectangle.prototype.height * @description 高度。 */ this.height = !isNaN(height) ? height : 0; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters.Rectangle"; } /** * @function ShapeParametersRectangle.prototype.destroy * @description 销毁对象。 */ destroy() { this.x = null; this.y = null; this.width = null; this.height = null; super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Sector.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParametersSector * @aliasclass Feature.ShapeParameters.Sector * @deprecatedclass SuperMap.Feature.ShapeParameters.Sector * @category Visualization Theme * @classdesc 扇形参数对象。 * @extends {ShapeParameters} * @param {number} x - 圆心 x 坐标。 * @param {number} y - 圆心 y 坐标。 * @param {number} r - 外圆半径。 * @param {number} startAngle - 起始角度。取值范围[0, 360)。 * @param {number} endAngle - 结束角度。取值范围(0, 360]。 * @param {number} [r0=0] - 内圆半径,指定后将出现内弧,同时扇边长度为'r - r0'。取值范围[0, r)。 * @usage */ class Sector extends ShapeParameters { constructor(x, y, r, startAngle, endAngle, r0, clockWise) { super(x, y, r, startAngle, endAngle, r0, clockWise); /** * @member {number} ShapeParametersSector.prototype.x * @description 圆心 x 坐标。 */ this.x = !isNaN(x) ? x : 0; /** * @member {number} ShapeParametersSector.prototype.Y * @description 圆心 Y 坐标。 */ this.y = !isNaN(y) ? y : 0; /** * @member {number} ShapeParametersSector.prototype.r * @description 外圆半径。 */ this.r = !isNaN(r) ? r : 0; /** * @member {number} ShapeParametersSector.prototype.startAngle * @description 起始角度。取值范围[0, 360),默认值:null。 */ this.startAngle = !isNaN(startAngle) ? startAngle : 0; /** * @member {number} ShapeParametersSector.prototype.endAngle * @description 结束角度。取值范围(0, 360],默认值:null。 */ this.endAngle = !isNaN(endAngle) ? endAngle : 0; /** * @member {number} [ShapeParametersSector.prototype.r0=0] * @description 内圆半径,指定后将出现内弧,同时扇边长度为 r 减 r0。取值范围[0, r)。 */ this.r0 = !isNaN(r0) ? r0 : 0; /** * @member {number} [ShapeParametersSector.prototype.clockWise=false] * @description 是否是顺时针。默认值:false。 */ this.clockWise = clockWise; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters.Sector"; } /** * @function ShapeParametersSector.prototype.destroy * @description 销毁对象。 */ destroy() { this.x = null; this.y = null; this.r = null; this.startAngle = null; this.endAngle = null; this.r0 = null; this.clockWise = null; super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Label.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParametersLabel * @aliasclass Feature.ShapeParameters.Label * @deprecatedclass SuperMap.Feature.ShapeParameters.Label * @category Visualization Theme * @classdesc 标签参数对象。 * @extends {ShapeParameters} * @param {number} x - 横坐标。 * @param {number} y - 纵坐标。 * @param {string} text - 图形中的附加文本。 * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ShapeParametersLabel } from '{npm}'; * new ShapeParametersLabel(x, y, text); * * // 弃用的写法 * import { Label } from '{npm}'; * new Label(x, y, text); * * ``` */ class Label extends ShapeParameters { constructor(x, y, text) { super(x, y, text); /** * @member {number} ShapeParametersLabel.prototype.x * @description 标签 x 坐标。 */ this.x = x; /** * @member {number} ShapeParametersLabel.prototype.y * @description 标签 y 坐标。 */ this.y = y; /** * @member {number} ShapeParametersLabel.prototype.text * @description 标签的文本内容。 */ this.text = text; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters.Label"; } /** * @function ShapeParametersLabel.prototype.destroy * @description 销毁对象。 */ destroy() { this.x = null; this.y = null; this.text = null; super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Image.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParametersImage * @aliasclass Feature.ShapeParameters.Image * @deprecatedclass SuperMap.Feature.ShapeParameters.Image * @category Visualization Theme * @classdesc 图片参数对象。 * @extends {ShapeParameters} * @param {number} x - 左上角横坐标。 * @param {number} y - 左上角纵坐标。 * @param {(string|Object)} image - 图片地址或Cavans对象。 * @param {number} width - 绘制到画布上的宽度,默认为图片高度。 * @param {number} height - 绘制到画布上的高度,默认为图片高度。 * @param {number} sx - 从图片中裁剪的左上角横坐标。 * @param {number} sy - 从图片中裁剪的左上角纵坐标。 * @param {number} sWidth - 从图片中裁剪的宽度,默认为图片高度。 * @param {number} sHeight - 绘制到画布上的高度,默认为图片高度。 * @usage */ class Image_Image extends ShapeParameters { constructor(x, y, image, width, height, sx, sy, sWidth, sHeight) { super(x, y, image, width, height, sx, sy, sWidth, sHeight); /** * @member {number} ShapeParametersImage.prototype.x * @description 左上角横坐标,必设参数。 */ this.x = x; /** * @member {number} ShapeParametersImage.prototype.y * @description 左上角纵坐标,必设参数。 */ this.y = y; /** * @member {(string|Object)} ShapeParametersImage.prototype.image * @description 图片地址。 */ this.image = image; /** * @member {number} ShapeParametersImage.prototype.width * @description 绘制到画布上的宽度,默认为图片高度。 */ this.width = width; /** * @member {number} ShapeParametersImage.prototype.height * @description 绘制到画布上的高度,默认为图片高度。 */ this.height = height; /** * @member {number} ShapeParametersImage.prototype.sx * @description 从图片中裁剪的左上角横坐标。 */ this.sx = sx; /** * @member {number} ShapeParametersImage.prototype.sy * @description 从图片中裁剪的左上角纵坐标。 */ this.sy = sy; /** * @member {number} ShapeParametersImage.prototype.sWidth * @description 从图片中裁剪的宽度,默认为图片高度。 */ this.sWidth = sWidth; /** * @member {number} ShapeParametersImage.prototype.sHeight * @description 绘制到画布上的高度,默认为图片高度。 */ this.sHeight = sHeight; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters.Image"; } /** * @function ShapeParametersImage.prototype.destroy * @description 销毁对象。 */ destroy() { this.x = null; this.y = null; this.image = null; this.width = null; this.height = null; this.sx = null; this.sy = null; this.sWidth = null; this.sHeight = null; super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Circle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ShapeParametersCircle * @aliasclass Feature.ShapeParameters.Circle * @deprecatedclass SuperMap.Feature.ShapeParameters.Circle * @classdesc 圆形参数对象。 * @category Visualization Theme * @extends {ShapeParameters} * @param {number} x - 圆心 x 坐标。 * @param {number} y - 圆心 y 坐标。 * @param {number} r - 圆半径。 * @usage */ class Circle_Circle extends ShapeParameters { constructor(x, y, r) { super(x, y, r); /** * @member {number} ShapeParametersCircle.prototype.x * @description 圆心 x 坐标。 */ this.x = !isNaN(x) ? x : 0; /** * @member {number} ShapeParametersCircle.prototype.y * @description 圆心 y 坐标。 */ this.y = !isNaN(y) ? y : 0; /** * @member {number} ShapeParametersCircle.prototype.r * @description 圆半径。 */ this.r = !isNaN(r) ? r : 0; this.CLASS_NAME = "SuperMap.Feature.ShapeParameters.Circle"; } /** * @function ShapeParametersCircle.prototype.destroy * @description 销毁对象。 */ destroy() { this.x = null; this.y = null; this.r = null; super.destroy(); } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Eventful.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Eventful * @category Visualization Theme * @classdesc 事件分发器超类,所有支持事件处理的类均是此类的子类。 * 此类不可实例化。 * 支持的事件: * Symbolizer properties: * onclick - {function} 默认值:null。 * onmouseover - {function} 默认值:null。 * onmouseout - {function} 默认值:null。 * onmousemove - {function} 默认值:null。 * onmousewheel - {function} 默认值:null。 * onmousedown - {function} 默认值:null。 * onmouseup - {function} 默认值:null。 * ondragstart - {function} 默认值:null。 * ondragend - {function} 默认值:null。 * ondragenter - {function} 默认值:null。 * ondragleave - {function} 默认值:null。 * ondragover - {function} 默认值:null。 * ondrop - {function} 默认值:null。 * @private */ class Eventful { constructor() { /** * @member {Object} LevelRenderer.Eventful.prototype._handlers * @description 事件处理对象(事件分发器)。 */ this._handlers = {}; this.CLASS_NAME = "SuperMap.LevelRenderer.Eventful"; } /** * @function {Object} LevelRenderer.Eventful.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this._handlers = null; } /** * @function LevelRenderer.Eventful.prototype.one * @description 单次触发绑定,dispatch后销毁。 * @param {string} event - 事件名。 * @param {boolean} handler - 响应函数。 * @param {Object} context - context。 * @returns {LevelRenderer.Eventful} this */ one(event, handler, context) { var _h = this._handlers; if (!handler || !event) { return this; } if (!_h[event]) { _h[event] = []; } _h[event].push({ h: handler, one: true, ctx: context || this }); return this; } /** * @function LevelRenderer.Eventful.prototype.bind * @description 绑定事件。 * @param {string} event - 事件名。 * @param {boolean} handler - 响应函数。 * @param {Object} context - context。 * @returns {LevelRenderer.Eventful} this */ bind(event, handler, context) { var _h = this._handlers; if (!handler || !event) { return this; } if (!_h[event]) { _h[event] = []; } _h[event].push({ h: handler, one: false, ctx: context || this }); return this; } /** * @function LevelRenderer.Eventful.prototype.unbind * @description 解绑事件。 * @param {string} event - 事件名。 * @param {boolean} handler - 响应函数。 * @returns {LevelRenderer.Eventful} this */ unbind(event, handler) { var _h = this._handlers; if (!event) { this._handlers = {}; return this; } if (handler) { if (_h[event]) { var newList = []; for (var i = 0, l = _h[event].length; i < l; i++) { if (_h[event][i]['h'] != handler) { newList.push(_h[event][i]); } } _h[event] = newList; } if (_h[event] && _h[event].length === 0) { delete _h[event]; } } else { delete _h[event]; } return this; } /** * @function LevelRenderer.Eventful.prototype.dispatch * @description 事件分发。 * @param {string} type - 事件类型。 * @returns {LevelRenderer.Eventful} this */ dispatch(type) { if (this._handlers[type]) { var args = arguments; var argLen = args.length; if (argLen > 3) { args = Array.prototype.slice.call(args, 1); } var _h = this._handlers[type]; var len = _h.length; for (var i = 0; i < len;) { // Optimize advise from backbone switch (argLen) { case 1: _h[i]['h'].call(_h[i]['ctx']); break; case 2: _h[i]['h'].call(_h[i]['ctx'], args[1]); break; case 3: _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]); break; default: // have more than 2 given arguments _h[i]['h'].apply(_h[i]['ctx'], args); break; } if (_h[i]['one']) { _h.splice(i, 1); len--; } else { i++; } } } return this; } /** * @function LevelRenderer.Eventful.prototype.dispatchWithContext * @description 带有context的事件分发,最后一个参数是事件回调的 context。 * @param {string} type - 事件类型。 * @returns {LevelRenderer.Eventful} this */ dispatchWithContext(type) { if (this._handlers[type]) { var args = arguments; var argLen = args.length; if (argLen > 4) { args = Array.prototype.slice.call(args, 1, args.length - 1); } var ctx = args[args.length - 1]; var _h = this._handlers[type]; var len = _h.length; for (var i = 0; i < len;) { // Optimize advise from backbone switch (argLen) { case 1: _h[i]['h'].call(ctx); break; case 2: _h[i]['h'].call(ctx, args[1]); break; case 3: _h[i]['h'].call(ctx, args[1], args[2]); break; default: // have more than 2 given arguments _h[i]['h'].apply(ctx, args); break; } if (_h[i]['one']) { _h.splice(i, 1); len--; } else { i++; } } } return this; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Vector.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Tool.Vector * @category Visualization Theme * @classdesc LevelRenderer 二维向量类 * */ class levelRenderer_Vector_Vector { constructor() { this.ArrayCtor = typeof Float32Array === 'undefined' ? Array : Float32Array; this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Vector"; } /** * @function LevelRenderer.Tool.Vector.prototype.create * @description 创建一个向量。 * * @param {number} x - x坐标 * @param {number} y - Y坐标 * @return {Vector2} 向量。 */ create(x, y) { var ArrayCtor = this.ArrayCtor; var out = new ArrayCtor(2); out[0] = x || 0; out[1] = y || 0; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.copy * @description 复制一个向量。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v - 向量。 * @return {Vector2} 克隆向量。 */ copy(out, v) { out[0] = v[0]; out[1] = v[1]; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.set * @description 设置向量的两个项。 * * @param {Vector2} out - 基础向量。 * @param {number} a - 项 a。 * @param {number} b - 项 b。 * @return {Vector2} 结果。 */ set(out, a, b) { out[0] = a; out[1] = b; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.add * @description 向量相加。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {Vector2} 结果。 */ add(out, v1, v2) { out[0] = v1[0] + v2[0]; out[1] = v1[1] + v2[1]; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.scaleAndAdd * @description 向量缩放后相加。 * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2(缩放向量)。 * @param {number} a - 缩放参数。 * @return {Vector2} 结果。 */ scaleAndAdd(out, v1, v2, a) { out[0] = v1[0] + v2[0] * a; out[1] = v1[1] + v2[1] * a; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.sub * @description 向量相减。 * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {Vector2} 结果。 */ sub(out, v1, v2) { out[0] = v1[0] - v2[0]; out[1] = v1[1] - v2[1]; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.len * @description 向量长度。 * @param {Vector2} v - 向量。 * @return {number} 向量长度。 */ len(v) { return Math.sqrt(this.lenSquare(v)); } /** * @function LevelRenderer.Tool.Vector.prototype.lenSquare * @description 向量长度平方。 * @param {Vector2} v - 向量。 * @return {number} 向量长度平方。 */ lenSquare(v) { return v[0] * v[0] + v[1] * v[1]; } /** * @function LevelRenderer.Tool.Vector.prototype.mul * @description 向量乘法。 * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {Vector2} 结果。 */ mul(out, v1, v2) { out[0] = v1[0] * v2[0]; out[1] = v1[1] * v2[1]; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.div * @description 向量除法。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {Vector2} 结果。 */ div(out, v1, v2) { out[0] = v1[0] / v2[0]; out[1] = v1[1] / v2[1]; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.dot * @description 向量点乘。 * * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {number} 向量点乘。 */ dot(v1, v2) { return v1[0] * v2[0] + v1[1] * v2[1]; } /** * @function LevelRenderer.Tool.Vector.prototype.scale * @description 向量缩放。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v - 向量v。 * @param {number} s -缩放参数。 * @return {Vector2} 结果。 */ scale(out, v, s) { out[0] = v[0] * s; out[1] = v[1] * s; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.normalize * @description 向量归一化。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v - 向量 v。 * @return {Vector2} 结果。 */ normalize(out, v) { var d = this.len(v); if (d === 0) { out[0] = 0; out[1] = 0; } else { out[0] = v[0] / d; out[1] = v[1] / d; } return out; } /** * @function LevelRenderer.Tool.Vector.prototype.distance * @description 计算向量间距离。 * * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {number} 向量间距离。 */ distance(v1, v2) { return Math.sqrt( (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]) ); } /** * @function LevelRenderer.Tool.Vector.prototype.distanceSquare * @description 向量距离平方。 * * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {number} 向量距离平方。 */ distanceSquare(v1, v2) { return (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]); } /** * @function LevelRenderer.Tool.Vector.prototype.negate * @description 求负向量。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v - 向量 v。 * @return {Vector2} 负向量。 */ negate(out, v) { out[0] = -v[0]; out[1] = -v[1]; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.lerp * @description 两点之间线性插值。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @param {number} t * @return {Vector2} 结果。 */ lerp(out, v1, v2, t) { out[0] = v1[0] + t * (v2[0] - v1[0]); out[1] = v1[1] + t * (v2[1] - v1[1]); return out; } /** * @function LevelRenderer.Tool.Vector.prototype.applyTransform * @description 矩阵左乘向量。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {Vector2} 结果。 */ applyTransform(out, v, m) { var x = v[0]; var y = v[1]; out[0] = m[0] * x + m[2] * y + m[4]; out[1] = m[1] * x + m[3] * y + m[5]; return out; } /** * @function LevelRenderer.Tool.Vector.prototype.min * @description 求两个向量最小值。 * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {Vector2} 结果。 */ min(out, v1, v2) { out[0] = Math.min(v1[0], v2[0]); out[1] = Math.min(v1[1], v2[1]); return out; } /** * @function LevelRenderer.Tool.Vector.prototype.max * @description 求两个向量最大值。 * * @param {Vector2} out - 基础向量。 * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {Vector2} 结果。 */ max(out, v1, v2) { out[0] = Math.max(v1[0], v2[0]); out[1] = Math.max(v1[1], v2[1]); return out; } /** * @function LevelRenderer.Tool.Vector.prototype.length * @description 向量长度。 * * @param {Vector2} v - 向量。 * @return {number} 向量长度。 */ length(v) { return this.len(v); } /** * @function LevelRenderer.Tool.Vector.prototype.lengthSquare * @description 向量长度平方。 * * @param {Vector2} v - 向量。 * @return {number} 向量长度平方。 */ lengthSquare(v) { return this.lenSquare(v); } /** * @function LevelRenderer.Tool.Vector.prototype.dist * @description 计算向量间距离。 * * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {number} 向量间距离。 */ dist(v1, v2) { return this.distance(v1, v2); } /** * @function LevelRenderer.Tool.Vector.prototype.distSquare * @description 向量距离平方。 * * @param {Vector2} v1 - 向量 v1。 * @param {Vector2} v2 - 向量 v2。 * @return {number} 向量距离平方 */ distSquare(v1, v2) { return this.distanceSquare(v1, v2); } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Curve.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Tool.Curve * @category Visualization Theme * @classdesc LevelRenderer 工具-曲线 * @private */ class Curve_Curve { constructor() { /** * @member {LevelRenderer.Tool.Vector} LevelRenderer.Tool.Curve.prototype.vector * @description 矢量工具。 */ this.vector = new levelRenderer_Vector_Vector(); /** * @member {number} LevelRenderer.Tool.Curve.prototype.EPSILON * @description e。 */ this.EPSILON = 1e-4; /** * @member {number} LevelRenderer.Tool.Curve.prototype.THREE_SQRT * @description 3 的平方根。 */ this.THREE_SQRT = Math.sqrt(3); /** * @member {number} LevelRenderer.Tool.Curve.prototype.ONE_THIRD * @description 1/3。 */ this.ONE_THIRD = 1 / 3; this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Curve"; } /* * Method: evalCubicCoeff * * Parameters: * a - {number} 值。 * b - {number} 值。 * c - {number} 值。 * d - {number} 值。 * t - {number} 值。 * * Returns: * {number} */ /* evalCubicCoeff: function(a, b, c, d, t){ return ((a * t + b) * t + c) * t + d; }, */ /** * @function LevelRenderer.Tool.Curve.prototype.isAroundZero * @description 判断一个值是否趋于0,判断参考值:1e-4。 * @param {number} val - 值。 * @returns {boolean} 值是否趋于0。 */ isAroundZero(val) { return val > -this.EPSILON && val < this.EPSILON; } /** * @function LevelRenderer.Tool.Curve.prototype.isNotAroundZero * @description 判断一个值是否不趋于0,判断参考值:1e-4。 * @param {number} val - 值。 * @returns {boolean} 值是否不趋于0。 */ isNotAroundZero(val) { return val > this.EPSILON || val < -this.EPSILON; } /** * @function LevelRenderer.Tool.Curve.prototype.cubicAt * @description 计算三次贝塞尔值 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @param {number} p3 - 点p3。 * @param {number} t - t值。 * @returns {number} 三次贝塞尔值。 */ cubicAt(p0, p1, p2, p3, t) { var onet = 1 - t; return onet * onet * (onet * p0 + 3 * t * p1) + t * t * (t * p3 + 3 * onet * p2); } /** * @function LevelRenderer.Tool.Curve.prototype.cubicDerivativeAt * @description 计算三次贝塞尔导数值 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @param {number} p3 - 点p3。 * @param {number} t - t值。 * @returns {number} 三次贝塞尔导数值。 */ cubicDerivativeAt(p0, p1, p2, p3, t) { var onet = 1 - t; return 3 * ( ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet + (p3 - p2) * t * t ); } /** * @function LevelRenderer.Tool.Curve.prototype.cubicRootAt * @description 计算三次贝塞尔方程根,使用盛金公式 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @param {number} p3 - 点p3。 * @param {number} val - 值。 * @param {Array.} roots - 有效根数目。 * @returns {number} 有效根。 */ cubicRootAt(p0, p1, p2, p3, val, roots) { // Evaluate roots of cubic functions var a = p3 + 3 * (p1 - p2) - p0; var b = 3 * (p2 - p1 * 2 + p0); var c = 3 * (p1 - p0); var d = p0 - val; var A = b * b - 3 * a * c; var B = b * c - 9 * a * d; var C = c * c - 3 * b * d; var n = 0; if (this.isAroundZero(A) && this.isAroundZero(B)) { if (this.isAroundZero(b)) { roots[0] = 0; } else { let t1 = -c / b; //t1, t2, t3, b is not zero if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } } else { var disc = B * B - 4 * A * C; if (this.isAroundZero(disc)) { var K = B / A; let t1 = -b / a + K; // t1, a is not zero let t2 = -K / 2; // t2, t3 if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } } else if (disc > 0) { let discSqrt = Math.sqrt(disc); let Y1 = A * b + 1.5 * a * (-B + discSqrt); let Y2 = A * b + 1.5 * a * (-B - discSqrt); if (Y1 < 0) { Y1 = -Math.pow(-Y1, this.ONE_THIRD); } else { Y1 = Math.pow(Y1, this.ONE_THIRD); } if (Y2 < 0) { Y2 = -Math.pow(-Y2, this.ONE_THIRD); } else { Y2 = Math.pow(Y2, this.ONE_THIRD); } let t1 = (-b - (Y1 + Y2)) / (3 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } else { var T = (2 * A * b - 3 * a * B) / (2 * Math.sqrt(A * A * A)); var theta = Math.acos(T) / 3; var ASqrt = Math.sqrt(A); var tmp = Math.cos(theta); let t1 = (-b - 2 * ASqrt * tmp) / (3 * a); let t2 = (-b + ASqrt * (tmp + this.THREE_SQRT * Math.sin(theta))) / (3 * a); let t3 = (-b + ASqrt * (tmp - this.THREE_SQRT * Math.sin(theta))) / (3 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } if (t3 >= 0 && t3 <= 1) { roots[n++] = t3; } } } return n; } /** * @function LevelRenderer.Tool.Curve.prototype.cubicRootAt * @description 计算三次贝塞尔方程极限值的位置 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @param {number} p3 - 点p3。 * @param {Array.} extrema - 值。 * @returns {number} 有效数目。 */ cubicExtrema(p0, p1, p2, p3, extrema) { var b = 6 * p2 - 12 * p1 + 6 * p0; var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2; var c = 3 * p1 - 3 * p0; var n = 0; if (this.isAroundZero(a)) { if (this.isNotAroundZero(b)) { let t1 = -c / b; if (t1 >= 0 && t1 <= 1) { extrema[n++] = t1; } } } else { var disc = b * b - 4 * a * c; if (this.isAroundZero(disc)) { extrema[0] = -b / (2 * a); } else if (disc > 0) { let discSqrt = Math.sqrt(disc); let t1 = (-b + discSqrt) / (2 * a); let t2 = (-b - discSqrt) / (2 * a); if (t1 >= 0 && t1 <= 1) { extrema[n++] = t1; } if (t2 >= 0 && t2 <= 1) { extrema[n++] = t2; } } } return n; } /** * @function LevelRenderer.Tool.Curve.prototype.cubicSubdivide * @description 细分三次贝塞尔曲线 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @param {number} p3 - 点p3。 * @param {number} t - t值。 * @param {Array.} out - 投射点。 * @returns {number} 投射点。 */ cubicSubdivide(p0, p1, p2, p3, t, out) { var p01 = (p1 - p0) * t + p0; var p12 = (p2 - p1) * t + p1; var p23 = (p3 - p2) * t + p2; var p012 = (p12 - p01) * t + p01; var p123 = (p23 - p12) * t + p12; var p0123 = (p123 - p012) * t + p012; // Seg0 out[0] = p0; out[1] = p01; out[2] = p012; out[3] = p0123; // Seg1 out[4] = p0123; out[5] = p123; out[6] = p23; out[7] = p3; } /** * @function LevelRenderer.Tool.Curve.prototype.cubicProjectPoint * @description 投射点到三次贝塞尔曲线上,返回投射距离。投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。 * @param {number} x0 - 点p0横坐标。 * @param {number} y0 - 点p0纵坐标。 * @param {number} x1 - 点p1横坐标。 * @param {number} y1 - 点p1纵坐标。 * @param {number} x2 - 点p2横坐标。 * @param {number} y2 - 点p2纵坐标。 * @param {number} x3 - 点p3横坐标。 * @param {number} y3 - 点p3纵坐标。 * @param {number} x - 点p横坐标。 * @param {number} y - 点p纵坐标。 * @param {Array.} out - 投射点。 * @returns {number} 投射点。 */ cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) { // 临时变量 var _v0 = this.vector.create(); var _v1 = this.vector.create(); var _v2 = this.vector.create(); // var _v3 = vector.create(); // http://pomax.github.io/bezierinfo/#projections var t; var interval = 0.005; var d = Infinity; _v0[0] = x; _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值 // PENDING for (let _t = 0; _t < 1; _t += 0.05) { _v1[0] = this.cubicAt(x0, x1, x2, x3, _t); _v1[1] = this.cubicAt(y0, y1, y2, y3, _t); let d1 = this.vector.distSquare(_v0, _v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; // At most 32 iteration for (let i = 0; i < 32; i++) { if (interval < this.EPSILON) { break; } let prev = t - interval; let next = t + interval; // t - interval _v1[0] = this.cubicAt(x0, x1, x2, x3, prev); _v1[1] = this.cubicAt(y0, y1, y2, y3, prev); let d1 = this.vector.distSquare(_v1, _v0); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { // t + interval _v2[0] = this.cubicAt(x0, x1, x2, x3, next); _v2[1] = this.cubicAt(y0, y1, y2, y3, next); let d2 = this.vector.distSquare(_v2, _v0); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } // t if (out) { out[0] = this.cubicAt(x0, x1, x2, x3, t); out[1] = this.cubicAt(y0, y1, y2, y3, t); } // console.log(interval, i); return Math.sqrt(d); } /** * @function LevelRenderer.Tool.Curve.prototype.quadraticAt * @description 计算二次方贝塞尔值。 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @param {number} t - t值。 * @returns {number} 二次方贝塞尔值。 */ quadraticAt(p0, p1, p2, t) { var onet = 1 - t; return onet * (onet * p0 + 2 * t * p1) + t * t * p2; } /** * @function LevelRenderer.Tool.Curve.prototype.quadraticAt * @description 计算二次方贝塞尔导数值。 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @param {number} t - t值。 * @returns {number} 二次方贝塞尔导数值。 */ quadraticDerivativeAt(p0, p1, p2, t) { return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1)); } /** * @function LevelRenderer.Tool.Curve.prototype.quadraticRootAt * @description 计算二次方贝塞尔方程根 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @param {number} val - 值。 * @param {Array.} roots - 有效根数目。 * @returns {number} 有效根数目。 */ quadraticRootAt(p0, p1, p2, val, roots) { var a = p0 - 2 * p1 + p2; var b = 2 * (p1 - p0); var c = p0 - val; var n = 0; if (this.isAroundZero(a)) { if (this.isNotAroundZero(b)) { var t1 = -c / b; if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } } else { var disc = b * b - 4 * a * c; if (this.isAroundZero(disc)) { let t1 = -b / (2 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } else if (disc > 0) { let discSqrt = Math.sqrt(disc); let t1 = (-b + discSqrt) / (2 * a); let t2 = (-b - discSqrt) / (2 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } } } return n; } /** * @function LevelRenderer.Tool.Curve.prototype.quadraticExtremum * @description 计算二次贝塞尔方程极限值 * @param {number} p0 - 点p0。 * @param {number} p1 - 点p1。 * @param {number} p2 - 点p2。 * @returns {number} 二次贝塞尔方程极限值。 */ quadraticExtremum(p0, p1, p2) { var divider = p0 + p2 - 2 * p1; if (divider === 0) { // p1 is center of p0 and p2 return 0.5; } else { return (p0 - p1) / divider; } } /** * @function LevelRenderer.Tool.Curve.prototype.quadraticProjectPoint * @description 投射点到二次贝塞尔曲线上,返回投射距离。投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。 * @param {number} x0 - 点p0横坐标。 * @param {number} y0 - 点p0纵坐标。 * @param {number} x1 - 点p1横坐标。 * @param {number} y1 - 点p1纵坐标。 * @param {number} x2 - 点p2横坐标。 * @param {number} y2 - 点p2纵坐标。 * @param {number} x - 点p横坐标。 * @param {number} y - 点p纵坐标。 * @param {Array.} out - 投射点。 * @returns {number} 投射距离。 */ quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) { // 临时变量 var _v0 = this.vector.create(); var _v1 = this.vector.create(); var _v2 = this.vector.create(); // http://pomax.github.io/bezierinfo/#projections var t; var interval = 0.005; var d = Infinity; _v0[0] = x; _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值 // PENDING for (let _t = 0; _t < 1; _t += 0.05) { _v1[0] = this.quadraticAt(x0, x1, x2, _t); _v1[1] = this.quadraticAt(y0, y1, y2, _t); let d1 = this.vector.distSquare(_v0, _v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; // At most 32 iteration for (let i = 0; i < 32; i++) { if (interval < this.EPSILON) { break; } let prev = t - interval; let next = t + interval; // t - interval _v1[0] = this.quadraticAt(x0, x1, x2, prev); _v1[1] = this.quadraticAt(y0, y1, y2, prev); let d1 = this.vector.distSquare(_v1, _v0); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { // t + interval _v2[0] = this.quadraticAt(x0, x1, x2, next); _v2[1] = this.quadraticAt(y0, y1, y2, next); let d2 = this.vector.distSquare(_v2, _v0); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } // t if (out) { out[0] = this.quadraticAt(x0, x1, x2, t); out[1] = this.quadraticAt(y0, y1, y2, t); } // console.log(interval, i); return Math.sqrt(d); } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Area.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Tool.Area * @category Visualization Theme * @classdesc LevelRenderer 工具-图形范围判断 * @private */ class Area { constructor() { /** * @member {LevelRenderer.Tool.Util} LevelRenderer.Tool.Areal.prototype.util * @description 基础工具对象。 */ this.util = new Util_Util(); /** * @member {LevelRenderer.Tool.Curve} LevelRenderer.Tool.Areal.prototype.curve * @description 曲线工具对象 */ this.curve = new Curve_Curve(); /** * @member {Object} LevelRenderer.Tool.Areal.prototype._ctx * @description Cavans2D 渲染上下文 */ this._ctx = null; /** * @member {Object} LevelRenderer.Tool.Areal.prototype._textWidthCache * @description 文本宽度缓存 */ this._textWidthCache = {}; /** * @member {Object} LevelRenderer.Tool.Areal.prototype._textHeightCache * @description 文本高度缓存 */ this._textHeightCache = {}; /** * @member {number} LevelRenderer.Tool.Areal.prototype._textWidthCacheCounter * @description 文本宽度缓存数量 */ this._textWidthCacheCounter = 0; /** * @member {number} LevelRenderer.Tool.Areal.prototype._textHeightCacheCounter * @description 文本高度缓存数量 */ this._textHeightCacheCounter = 0; /** * @member {number} LevelRenderer.Tool.Areal.prototype.TEXT_CACHE_MAX * @description 文本最大缓存数量 */ this.TEXT_CACHE_MAX = 5000; /** * @member {number} LevelRenderer.Tool.Areal.prototype.PI2 * @description 2*PI 的值 */ this.PI2 = Math.PI * 2; /** * @member {Array.} LevelRenderer.Tool.Areal.prototype.roots * @description 临时数组 */ this.roots = [-1, -1, -1]; /** * @member {Array.} LevelRenderer.Tool.Areal.prototype.extrema * @description 临时数组 */ this.extrema = [-1, -1]; this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Area"; } /** * @function LevelRenderer.Tool.Areal.prototype.normalizeRadian * @description 弧度标准化函数。 * @param {number} angle - 弧度值。 * @returns {number} 标准化后的弧度值。 */ normalizeRadian(angle) { angle %= this.PI2; if (angle < 0) { angle += this.PI2; } return angle; } /** * @function LevelRenderer.Tool.Areal.prototype.isInside * @description 包含判断。 * @param {Object} shape - 图形。 * @param {number} area - 目标区域。 * @param {number} x - 横坐标。 * @param {number} y - 纵坐标。 * @returns {boolean} 图形是否包含鼠标位置。 */ isInside(shape, area, x, y) { if (!area || !shape) { // 无参数或不支持类型 return false; } var zoneType = shape.type; this._ctx = this._ctx || this.util.getContext(); // 未实现或不可用时则数学运算,主要是line,brokenLine,ring var _mathReturn = this._mathMethod(shape, area, x, y); if (typeof _mathReturn != 'undefined') { return _mathReturn; } if (shape.buildPath && this._ctx.isPointInPath) { return this._buildPathMethod(shape, this._ctx, area, x, y); } // 上面的方法都行不通时 switch (zoneType) { case 'ellipse': // Todo,不精确 case 'smicellipse': // Todo,不精确 return true; // 旋轮曲线 不准确 case 'trochoid': var _r = area.location == 'out' ? area.r1 + area.r2 + area.d : area.r1 - area.r2 + area.d; return this.isInsideCircle(area, x, y, _r); // 玫瑰线 不准确 case 'rose' : return this.isInsideCircle(area, x, y, area.maxr); // 路径,椭圆,曲线等-----------------13 default: return false; // Todo,暂不支持 } } /** * @function LevelRenderer.Tool.Areal.prototype._mathMethod * @description 包含判断。用数学方法判断,三个方法中最快,但是支持的shape少。 * @param {Object} shape - 图形。 * @param {number} area - 目标区域。 * @param {number} x - 横坐标。 * @param {number} y - 纵坐标。 * @returns {boolean} 图形是否包含鼠标位置,true表示坐标处在图形中。 */ _mathMethod(shape, area, x, y) { var zoneType = shape.type; // 在矩形内则部分图形需要进一步判断 switch (zoneType) { // 贝塞尔曲线 case 'bezier-curve': if (typeof(area.cpX2) === 'undefined') { return this.isInsideQuadraticStroke( area.xStart, area.yStart, area.cpX1, area.cpY1, area.xEnd, area.yEnd, area.lineWidth, x, y ); } return this.isInsideCubicStroke( area.xStart, area.yStart, area.cpX1, area.cpY1, area.cpX2, area.cpY2, area.xEnd, area.yEnd, area.lineWidth, x, y ); // 线 case 'line': return this.isInsideLine( area.xStart, area.yStart, area.xEnd, area.yEnd, area.lineWidth, x, y ); // 折线 case 'broken-line': return this.isInsideBrokenLine( area.pointList, area.lineWidth, x, y ); // 扩展折线 case 'smicbroken-line': { // SMIC-修改 - start let icX = x; let icY = y; if (shape.refOriginalPosition) { icX = x - shape.refOriginalPosition[0]; icY = y - shape.refOriginalPosition[1]; } return this.isInsideBrokenLine( area.pointList, area.lineWidth, icX, icY ); } //初始代码: // return isInsideBrokenLine( // area.pointList, area.lineWidth, x, y // ); // SMIC-修改 - end // 圆环 case 'ring': return this.isInsideRing( area.x, area.y, area.r0, area.r, x, y ); case 'smicring': { let areaX = area.x; let areaY = area.y; if (shape.refOriginalPosition) { areaX = area.x + shape.refOriginalPosition[0]; areaY = area.y + shape.refOriginalPosition[1]; } return this.isInsideRing( areaX, areaY, area.r0, area.r, x, y ); } // 圆形 case 'circle': return this.isInsideCircle( area.x, area.y, area.r, x, y ); // 扩展-点 case 'smicpoint': { // SMIC-修改 - start let icX = x; let icY = y; if (shape.refOriginalPosition) { icX = x - shape.refOriginalPosition[0]; icY = y - shape.refOriginalPosition[1]; } return this.isInsideCircle( area.x, area.y, area.r, icX, icY ); } //初始代码: // 无 // SMIC-修改 - end // 扇形 case 'sector': { let startAngle = area.startAngle * Math.PI / 180; let endAngle = area.endAngle * Math.PI / 180; if (!area.clockWise) { startAngle = -startAngle; endAngle = -endAngle; } return this.isInsideSector( area.x, area.y, area.r0, area.r, startAngle, endAngle, !area.clockWise, x, y ); } //初始代码: // 无 // SMIC-增加 - end // 扇形 case 'smicsector': { let startAngle = area.startAngle * Math.PI / 180; let endAngle = area.endAngle * Math.PI / 180; if (!area.clockWise) { startAngle = -startAngle; endAngle = -endAngle; } let areaX = area.x; let areaY = area.y; if (shape.refOriginalPosition) { areaX = area.x + shape.refOriginalPosition[0]; areaY = area.y + shape.refOriginalPosition[1]; } return this.isInsideSector( areaX, areaY, area.r0, area.r, startAngle, endAngle, !area.clockWise, x, y ); } // 多边形 case 'path': return this.isInsidePath( area.pathArray, Math.max(area.lineWidth, 5), area.brushType, x, y ); case 'polygon': case 'star': case 'smicstar': case 'isogon': case 'smicisogon': return this.isInsidePolygon(area.pointList, x, y); // 扩展多边形 case 'smicpolygon': { // SMIC-修改 - start let icX = x; let icY = y; if (shape.refOriginalPosition) { icX = x - shape.refOriginalPosition[0]; icY = y - shape.refOriginalPosition[1]; } //岛洞面 if (shape.holePolygonPointLists && shape.holePolygonPointLists.length > 0) { var isOnBase = this.isInsidePolygon(area.pointList, icX, icY); // 遍历岛洞子面 var holePLS = shape.holePolygonPointLists; var isOnHole = false; for (var i = 0, holePLSen = holePLS.length; i < holePLSen; i++) { var holePL = holePLS[i]; var isOnSubHole = this.isInsidePolygon(holePL, icX, icY); if (isOnSubHole === true) { isOnHole = true; } } // 捕获判断 return isOnBase === true && isOnHole === false; } else { return this.isInsidePolygon(area.pointList, icX, icY); } } // 初始代码: // 无 // SMIC-修改 - end // 文本 case 'text': var rect = area.__rect || shape.getRect(area); return this.isInsideRect( rect.x, rect.y, rect.width, rect.height, x, y ); // 扩展文本 case 'smictext': //用文本背景矩形判断 var textBg = shape.getTextBackground(area); return this.isInsidePolygon(textBg, x, y); //初始代码: // 无 // SMIC-修改 - end // 矩形 case 'rectangle': case 'image': // 图片 return this.isInsideRect( area.x, area.y, area.width, area.height, x, y ); case 'smicimage': { let areaX = area.x; let areaY = area.y; if (shape.refOriginalPosition) { areaX = area.x + shape.refOriginalPosition[0]; areaY = area.y + shape.refOriginalPosition[1]; } return this.isInsideRect( areaX, areaY, area.width, area.height, x, y ); } //// 扩展矩形 //case 'smicpolygon': // // SMIC-修改 - start // var icX = x; // var icY = y; // if(shape.refOriginalPosition) { // icX = x - shape.refOriginalPosition[0]; // icY = y - shape.refOriginalPosition[1]; // } // return this.isInsideRect( // area.x, area.y, area.width, area.height, icX, icY // ); //初始代码: // 无 // SMIC-修改 - end } } /** * @function LevelRenderer.Tool.Areal.prototype._buildPathMethod * @description 包含判断。通过buildPath方法来判断,三个方法中较快,但是不支持线条类型的 shape。 * @param {Object} shape - 图形。 * @param {Object} context - 上下文。 * @param {number} area - 目标区域。 * @param {number} x - 横坐标。 * @param {number} y - 纵坐标。 * @returns {boolean} 图形是否包含鼠标位置,true表示坐标处在图形中。 */ _buildPathMethod(shape, context, area, x, y) { // 图形类实现路径创建了则用类的path context.beginPath(); shape.buildPath(context, area); context.closePath(); return context.isPointInPath(x, y); } /** * @function LevelRenderer.Tool.Areal.prototype.isOutside * @description 图形是否不包含鼠标位置。 * @param {Object} shape - 图形。 * @param {number} area - 目标区域。 * @param {number} x - 横坐标。 * @param {number} y - 纵坐标。 * @returns {boolean} 图形是否不包含鼠标位置, true表示坐标处在图形外。 */ isOutside(shape, area, x, y) { return !this.isInside(shape, area, x, y); } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideLine * @description 线段包含判断。 * @param {number} x0 - 线起始点横坐标。 * @param {number} y0 - 线起始点纵坐标。 * @param {number} x1 - 线终点横坐标。 * @param {number} y1 - 线终点纵坐标。 * @param {number} lineWidth - 线宽。 * @param {number} x - 鼠标位置横坐标。 * @param {number} y - 鼠标位置纵坐标。 * @returns {boolean} 图形是否包含鼠标位置,true表示坐标处在图形内。 */ isInsideLine(x0, y0, x1, y1, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = Math.max(lineWidth, 5); var _a = 0; var _b = 0; // Quick reject if ( (y > y0 + _l && y > y1 + _l) || (y < y0 - _l && y < y1 - _l) || (x > x0 + _l && x > x1 + _l) || (x < x0 - _l && x < x1 - _l) ) { return false; } if (x0 !== x1) { _a = (y0 - y1) / (x0 - x1); _b = (x0 * y1 - x1 * y0) / (x0 - x1); } else { return Math.abs(x - x0) <= _l / 2; } var tmp = _a * x - y + _b; var _s = tmp * tmp / (_a * _a + 1); return _s <= _l / 2 * _l / 2; } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideCubicStroke * @description 三次贝塞尔曲线描边包含判断。 * @param {number} x0 - 点1横坐标。 * @param {number} y0 - 点1纵坐标。 * @param {number} x1 - 点2横坐标。 * @param {number} y1 - 点2纵坐标。 * @param {number} x2 - 点3纵坐标。 * @param {number} y2 - 点3纵坐标。 * @param {number} lineWidth - 线宽。 * @param {number} x - 鼠标位置横坐标。 * @param {number} y - 鼠标位置纵坐标。 * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsideCubicStroke(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = Math.max(lineWidth, 5); // Quick reject if ( (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l) || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l) || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l) || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l) ) { return false; } var d = this.curve.cubicProjectPoint( x0, y0, x1, y1, x2, y2, x3, y3, x, y, null ); return d <= _l / 2; } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideQuadraticStroke * @description 二次贝塞尔曲线描边包含判断。 * @param {number} x0 - 点1横坐标。 * @param {number} y0 - 点1纵坐标。 * @param {number} x1 - 点2横坐标。 * @param {number} y1 - 点2纵坐标。 * @param {number} x2 - 点3纵坐标。 * @param {number} y2 - 点3纵坐标。 * @param {number} lineWidth - 线宽。 * @param {number} x - 鼠标位置横坐标。 * @param {number} y - 鼠标位置纵坐标。 * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsideQuadraticStroke(x0, y0, x1, y1, x2, y2, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = Math.max(lineWidth, 5); // Quick reject if ( (y > y0 + _l && y > y1 + _l && y > y2 + _l) || (y < y0 - _l && y < y1 - _l && y < y2 - _l) || (x > x0 + _l && x > x1 + _l && x > x2 + _l) || (x < x0 - _l && x < x1 - _l && x < x2 - _l) ) { return false; } var d = this.curve.quadraticProjectPoint( x0, y0, x1, y1, x2, y2, x, y, null ); return d <= _l / 2; } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideArcStroke * @description 圆弧描边包含判断。 * @param {number} cx - 圆心横坐标。 * @param {number} cy - 圆心纵坐标。 * @param {number} r - 圆半径。 * @param {number} startAngle - 起始角度。 * @param {number} endAngle - 终止角度。 * @param {number} anticlockwise - 顺时针还是逆时针。 * @param {number} lineWidth - 线宽。 * @param {number} x - 鼠标位置横坐标。 * @param {number} y - 鼠标位置纵坐标。 * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsideArcStroke(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) { var PI2 = this.PI2; if (lineWidth === 0) { return false; } var _l = Math.max(lineWidth, 5); x -= cx; y -= cy; var d = Math.sqrt(x * x + y * y); if ((d - _l > r) || (d + _l < r)) { return false; } if (Math.abs(startAngle - endAngle) >= PI2) { // Is a circle return true; } if (anticlockwise) { var tmp = startAngle; startAngle = this.normalizeRadian(endAngle); endAngle = this.normalizeRadian(tmp); } else { startAngle = this.normalizeRadian(startAngle); endAngle = this.normalizeRadian(endAngle); } if (startAngle > endAngle) { endAngle += PI2; } var angle = Math.atan2(y, x); if (angle < 0) { angle += PI2; } return (angle >= startAngle && angle <= endAngle) || (angle + PI2 >= startAngle && angle + PI2 <= endAngle); } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideBrokenLine * @description 图形 BrokenLine 是否包含鼠标位置, true表示坐标处在图形内。 * @param {Array} points - 曲线点对象。 * @param {number} lineWidth - 线宽。 * @param {number} x - 鼠标位置横坐标。 * @param {number} y - 鼠标位置纵坐标。 * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsideBrokenLine(points, lineWidth, x, y) { var _lineWidth = Math.max(lineWidth, 10); for (var i = 0, l = points.length - 1; i < l; i++) { var x0 = points[i][0]; var y0 = points[i][1]; var x1 = points[i + 1][0]; var y1 = points[i + 1][1]; if (this.isInsideLine(x0, y0, x1, y1, _lineWidth, x, y)) { return true; } } return false; } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideRing * @description 图形 Ring 是否包含鼠标位置, true表示坐标处在图形内。 * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsideRing(cx, cy, r0, r, x, y) { var d = (x - cx) * (x - cx) + (y - cy) * (y - cy); return (d < r * r) && (d > r0 * r0); } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideRect * @description 图形 Rect 是否包含鼠标位置, true表示坐标处在图形内。 * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsideRect(x0, y0, width, height, x, y) { return x >= x0 && x <= (x0 + width) && y >= y0 && y <= (y0 + height); } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideCircle * @description 图形 Circle 是否包含鼠标位置, true表示坐标处在图形内。 * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsideCircle(x0, y0, r, x, y) { return (x - x0) * (x - x0) + (y - y0) * (y - y0) < r * r; } /** * @function LevelRenderer.Tool.Areal.prototype.isInsideSector * @description 图形 Sector 是否包含鼠标位置, true表示坐标处在图形内。 * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsideSector(cx, cy, r0, r, startAngle, endAngle, anticlockwise, x, y) { return this.isInsideArcStroke(cx, cy, (r0 + r) / 2, startAngle, endAngle, anticlockwise, r - r0, x, y); } /** * @function LevelRenderer.Tool.Areal.prototype.isInsidePolygon * @description 图形 Polygon 是否包含鼠标位置, true表示坐标处在图形内。与 canvas 一样采用 non-zero winding rule * @returns {boolean} 图形是否包含鼠标位置, true表示坐标处在图形内。 */ isInsidePolygon(points, x, y) { var N = points.length; var w = 0; for (var i = 0, j = N - 1; i < N; i++) { var x0 = points[j][0]; var y0 = points[j][1]; var x1 = points[i][0]; var y1 = points[i][1]; w += this.windingLine(x0, y0, x1, y1, x, y); j = i; } return w !== 0; } /** * @function LevelRenderer.Tool.Areal.prototype.windingLine */ windingLine(x0, y0, x1, y1, x, y) { if ((y > y0 && y > y1) || (y < y0 && y < y1)) { return 0; } if (y1 == y0) { return 0; } var dir = y1 < y0 ? 1 : -1; var t = (y - y0) / (y1 - y0); var x_ = t * (x1 - x0) + x0; return x_ > x ? dir : 0; } /** * @function LevelRenderer.Tool.Areal.prototype.swapExtrema */ swapExtrema() { var tmp = this.extrema[0]; this.extrema[0] = this.extrema[1]; this.extrema[1] = tmp; } /** * @function LevelRenderer.Tool.Areal.prototype.windingCubic */ windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) { var curve = this.curve; var roots = this.roots; var extrema = this.extrema; // Quick reject if ( (y > y0 && y > y1 && y > y2 && y > y3) || (y < y0 && y < y1 && y < y2 && y < y3) ) { return 0; } var nRoots = curve.cubicRootAt(y0, y1, y2, y3, y, roots); if (nRoots === 0) { return 0; } else { var w = 0; var nExtrema = -1; var y0_, y1_; for (var i = 0; i < nRoots; i++) { var t = roots[i]; var x_ = curve.cubicAt(x0, x1, x2, x3, t); if (x_ < x) { // Quick reject continue; } if (nExtrema < 0) { nExtrema = curve.cubicExtrema(y0, y1, y2, y3, extrema); if (extrema[1] < extrema[0] && nExtrema > 1) { this.swapExtrema(); } y0_ = curve.cubicAt(y0, y1, y2, y3, extrema[0]); if (nExtrema > 1) { y1_ = curve.cubicAt(y0, y1, y2, y3, extrema[1]); } } if (nExtrema == 2) { // 分成三段单调函数 if (t < extrema[0]) { w += y0_ < y0 ? 1 : -1; } else if (t < extrema[1]) { w += y1_ < y0_ ? 1 : -1; } else { w += y3 < y1_ ? 1 : -1; } } else { // 分成两段单调函数 if (t < extrema[0]) { w += y0_ < y0 ? 1 : -1; } else { w += y3 < y0_ ? 1 : -1; } } } return w; } } /** * @function LevelRenderer.Tool.Areal.prototype.windingQuadratic */ windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) { var curve = this.curve; var roots = this.roots; // Quick reject if ( (y > y0 && y > y1 && y > y2) || (y < y0 && y < y1 && y < y2) ) { return 0; } var nRoots = curve.quadraticRootAt(y0, y1, y2, y, roots); if (nRoots === 0) { return 0; } else { var t = curve.quadraticExtremum(y0, y1, y2); if (t >= 0 && t <= 1) { var w = 0; var y_ = curve.quadraticAt(y0, y1, y2, t); for (let i = 0; i < nRoots; i++) { let x_ = curve.quadraticAt(x0, x1, x2, roots[i]); if (x_ > x) { continue; } if (roots[i] < t) { w += y_ < y0 ? 1 : -1; } else { w += y2 < y_ ? 1 : -1; } } return w; } else { let x_ = curve.quadraticAt(x0, x1, x2, roots[0]); if (x_ > x) { return 0; } return y2 < y0 ? 1 : -1; } } } /** * @function LevelRenderer.Tool.Areal.prototype.windingArc * // TODO Arc 旋转 */ windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) { var roots = this.roots; var PI2 = this.PI2; y -= cy; if (y > r || y < -r) { return 0; } let tmp = Math.sqrt(r * r - y * y); roots[0] = -tmp; roots[1] = tmp; if (Math.abs(startAngle - endAngle) >= PI2) { // Is a circle startAngle = 0; endAngle = PI2; var dir = anticlockwise ? 1 : -1; if (x >= roots[0] + cx && x <= roots[1] + cx) { return dir; } else { return 0; } } if (anticlockwise) { let tmp = startAngle; startAngle = this.normalizeRadian(endAngle); endAngle = this.normalizeRadian(tmp); } else { startAngle = this.normalizeRadian(startAngle); endAngle = this.normalizeRadian(endAngle); } if (startAngle > endAngle) { endAngle += PI2; } var w = 0; for (let i = 0; i < 2; i++) { var x_ = roots[i]; if (x_ + cx > x) { let angle = Math.atan2(y, x_); let dir = anticlockwise ? 1 : -1; if (angle < 0) { angle = PI2 + angle; } if ( (angle >= startAngle && angle <= endAngle) || (angle + PI2 >= startAngle && angle + PI2 <= endAngle) ) { if (angle > Math.PI / 2 && angle < Math.PI * 1.5) { dir = -dir; } w += dir; } } } return w; } /** * @function LevelRenderer.Tool.Areal.prototype.isInsidePath * @description 与 canvas 一样采用 non-zero winding rule */ isInsidePath(pathArray, lineWidth, brushType, x, y) { var w = 0; var xi = 0; var yi = 0; var x0 = 0; var y0 = 0; var beginSubpath = true; var firstCmd = true; brushType = brushType || 'fill'; var hasStroke = brushType === 'stroke' || brushType === 'both'; var hasFill = brushType === 'fill' || brushType === 'both'; // var roots = [-1, -1, -1]; for (var i = 0; i < pathArray.length; i++) { var seg = pathArray[i]; var p = seg.points; // Begin a new subpath if (beginSubpath || seg.command === 'M') { if (i > 0) { // Close previous subpath if (hasFill) { w += this.windingLine(xi, yi, x0, y0, x, y); } if (w !== 0) { return true; } } x0 = p[p.length - 2]; y0 = p[p.length - 1]; beginSubpath = false; if (firstCmd && seg.command !== 'A') { // 如果第一个命令不是M, 是lineTo, bezierCurveTo // 等绘制命令的话,是会从该绘制的起点开始算的 // Arc 会在之后做单独处理所以这里忽略 firstCmd = false; xi = x0; yi = y0; } } switch (seg.command) { case 'M': xi = p[0]; yi = p[1]; break; case 'L': if (hasStroke) { if (this.isInsideLine( xi, yi, p[0], p[1], lineWidth, x, y )) { return true; } } if (hasFill) { w += this.windingLine(xi, yi, p[0], p[1], x, y); } xi = p[0]; yi = p[1]; break; case 'C': if (hasStroke) { if (this.isInsideCubicStroke( xi, yi, p[0], p[1], p[2], p[3], p[4], p[5], lineWidth, x, y )) { return true; } } if (hasFill) { w += this.windingCubic( xi, yi, p[0], p[1], p[2], p[3], p[4], p[5], x, y ); } xi = p[4]; yi = p[5]; break; case 'Q': if (hasStroke) { if (this.isInsideQuadraticStroke( xi, yi, p[0], p[1], p[2], p[3], lineWidth, x, y )) { return true; } } if (hasFill) { w += this.windingQuadratic( xi, yi, p[0], p[1], p[2], p[3], x, y ); } xi = p[2]; yi = p[3]; break; case 'A': // TODO Arc 旋转 // TODO Arc 判断的开销比较大 var cx = p[0]; var cy = p[1]; var rx = p[2]; var ry = p[3]; var theta = p[4]; var dTheta = p[5]; var x1 = Math.cos(theta) * rx + cx; var y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令 if (!firstCmd) { w += this.windingLine(xi, yi, x1, y1); } else { firstCmd = false; // 第一个命令起点还未定义 x0 = x1; y0 = y1; } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放 var _x = (x - cx) * ry / rx + cx; if (hasStroke) { if (this.isInsideArcStroke( cx, cy, ry, theta, theta + dTheta, 1 - p[7], lineWidth, _x, y )) { return true; } } if (hasFill) { w += this.windingArc( cx, cy, ry, theta, theta + dTheta, 1 - p[7], _x, y ); } xi = Math.cos(theta + dTheta) * rx + cx; yi = Math.sin(theta + dTheta) * ry + cy; break; case 'z': if (hasStroke) { if (this.isInsideLine( xi, yi, x0, y0, lineWidth, x, y )) { return true; } } beginSubpath = true; break; } } if (hasFill) { w += this.windingLine(xi, yi, x0, y0, x, y); } return w !== 0; } /** * @function LevelRenderer.Tool.Areal.prototype.getTextWidth * @description 测算多行文本宽度 */ getTextWidth(text, textFont) { var key = text + ':' + textFont; if (this._textWidthCache[key]) { return this._textWidthCache[key]; } this._ctx = this._ctx || this.util.getContext(); this._ctx.save(); if (textFont) { this._ctx.font = textFont; } text = (text + '').split('\n'); var width = 0; for (var i = 0, l = text.length; i < l; i++) { width = Math.max( this._ctx.measureText(text[i]).width, width ); } this._ctx.restore(); this._textWidthCache[key] = width; if (++this._textWidthCacheCounter > this.TEXT_CACHE_MAX) { // 内存释放 this._textWidthCacheCounter = 0; this._textWidthCache = {}; } return width; } /** * @function LevelRenderer.Tool.Areal.prototype.getTextHeight * @description 测算多行文本高度 */ getTextHeight(text, textFont) { var key = text + ':' + textFont; if (this._textHeightCache[key]) { return this._textHeightCache[key]; } this._ctx = this._ctx || this.util.getContext(); this._ctx.save(); if (textFont) { this._ctx.font = textFont; } text = (text + '').split('\n'); // 比较粗暴 //var height = (this._ctx.measureText('国').width + 2) * text.length; //打包不支持中文,替换掉 var height = (this._ctx.measureText('ZH').width + 2) * text.length; this._ctx.restore(); this._textHeightCache[key] = height; if (++this._textHeightCacheCounter > this.TEXT_CACHE_MAX) { // 内存释放 this._textHeightCacheCounter = 0; this._textHeightCache = {}; } return height; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/ComputeBoundingBox.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Tool.ComputeBoundingBox * @category Visualization Theme * @classdesc LevelRenderer 工具-图形 Bounds 计算 * @private */ class ComputeBoundingBox { constructor() { if (arguments.length === 3) { this.computeBoundingBox(arguments); } this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.ComputeBoundingBox"; } /** * @function LevelRenderer.Tool.ComputeBoundingBox.prototype.computeBoundingBox * @description 从顶点数组中计算出最小包围盒,写入'min'和'max'中。 * @param {Array.} points - 顶点数组。 * @param {Array.} min - 最小 * @param {Array.} max - 最大 */ computeBoundingBox(points, min, max) { if (points.length === 0) { return; } var left = points[0][0]; var right = points[0][0]; var top = points[0][1]; var bottom = points[0][1]; for (var i = 1; i < points.length; i++) { var p = points[i]; if (p[0] < left) { left = p[0]; } if (p[0] > right) { right = p[0]; } if (p[1] < top) { top = p[1]; } if (p[1] > bottom) { bottom = p[1]; } } min[0] = left; min[1] = top; max[0] = right; max[1] = bottom; } /** * @function LevelRenderer.Tool.ComputeBoundingBox.prototype.cubeBezier * @description 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入'min'和'max'中。原:computeCubeBezierBoundingBox。 * @param {Array.} p0 - 三阶贝塞尔曲线p0点 * @param {Array.} p1 - 三阶贝塞尔曲线p1点 * @param {Array.} p2 - 三阶贝塞尔曲线p2点 * @param {Array.} p3 - 三阶贝塞尔曲线p3点 * @param {Array.} min - 最小 * @param {Array.} max - 最大 */ cubeBezier(p0, p1, p2, p3, min, max) { var curve = new Curve_Curve(); var xDim = []; curve.cubicExtrema(p0[0], p1[0], p2[0], p3[0], xDim); for (let i = 0; i < xDim.length; i++) { xDim[i] = curve.cubicAt(p0[0], p1[0], p2[0], p3[0], xDim[i]); } var yDim = []; curve.cubicExtrema(p0[1], p1[1], p2[1], p3[1], yDim); for (let i = 0; i < yDim.length; i++) { yDim[i] = curve.cubicAt(p0[1], p1[1], p2[1], p3[1], yDim[i]); } xDim.push(p0[0], p3[0]); yDim.push(p0[1], p3[1]); var left = Math.min.apply(null, xDim); var right = Math.max.apply(null, xDim); var top = Math.min.apply(null, yDim); var bottom = Math.max.apply(null, yDim); min[0] = left; min[1] = top; max[0] = right; max[1] = bottom; } /** * @function LevelRenderer.Tool.ComputeBoundingBox.prototype.quadraticBezier * @description 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入'min'和'max'中。原:computeQuadraticBezierBoundingBox。 * @param {Array.} p0 - 二阶贝塞尔曲线p0点 * @param {Array.} p1 - 二阶贝塞尔曲线p1点 * @param {Array.} p2 - 二阶贝塞尔曲线p2点 * @param {Array.} min - 最小 * @param {Array.} max - 最大 */ quadraticBezier(p0, p1, p2, min, max) { var curve = new Curve_Curve(); // Find extremities, where derivative in x dim or y dim is zero var t1 = curve.quadraticExtremum(p0[0], p1[0], p2[0]); var t2 = curve.quadraticExtremum(p0[1], p1[1], p2[1]); t1 = Math.max(Math.min(t1, 1), 0); t2 = Math.max(Math.min(t2, 1), 0); var ct1 = 1 - t1; var ct2 = 1 - t2; var x1 = ct1 * ct1 * p0[0] + 2 * ct1 * t1 * p1[0] + t1 * t1 * p2[0]; var y1 = ct1 * ct1 * p0[1] + 2 * ct1 * t1 * p1[1] + t1 * t1 * p2[1]; var x2 = ct2 * ct2 * p0[0] + 2 * ct2 * t2 * p1[0] + t2 * t2 * p2[0]; var y2 = ct2 * ct2 * p0[1] + 2 * ct2 * t2 * p1[1] + t2 * t2 * p2[1]; min[0] = Math.min(p0[0], p2[0], x1, x2); min[1] = Math.min(p0[1], p2[1], y1, y2); max[0] = Math.max(p0[0], p2[0], x1, x2); max[1] = Math.max(p0[1], p2[1], y1, y2); } /** * @function LevelRenderer.Tool.ComputeBoundingBox.prototype.arc * @description 从圆弧中计算出最小包围盒,写入'min'和'max'中。原:computeArcBoundingBox。 * @param {number} x - 圆弧中心点 x * @param {number} y - 圆弧中心点 y * @param {number} r - 圆弧半径 * @param {number} startAngle - 圆弧开始角度 * @param {number} endAngle - 圆弧结束角度 * @param {number} anticlockwise - 是否是顺时针 * @param {number} min - 最小 * @param {number} max - 最大 */ arc(x, y, r, startAngle, endAngle, anticlockwise, min, max) { var vec2 = new levelRenderer_Vector_Vector(); var start = vec2.create(); var end = vec2.create(); var extremity = vec2.create(); start[0] = Math.cos(startAngle) * r + x; start[1] = Math.sin(startAngle) * r + y; end[0] = Math.cos(endAngle) * r + x; end[1] = Math.sin(endAngle) * r + y; vec2.min(min, start, end); vec2.max(max, start, end); // Thresh to [0, Math.PI * 2] startAngle = startAngle % (Math.PI * 2); if (startAngle < 0) { startAngle = startAngle + Math.PI * 2; } endAngle = endAngle % (Math.PI * 2); if (endAngle < 0) { endAngle = endAngle + Math.PI * 2; } if (startAngle > endAngle && !anticlockwise) { endAngle += Math.PI * 2; } else if (startAngle < endAngle && anticlockwise) { startAngle += Math.PI * 2; } if (anticlockwise) { var tmp = endAngle; endAngle = startAngle; startAngle = tmp; } // var number = 0; // var step = (anticlockwise ? -Math.PI : Math.PI) / 2; for (var angle = 0; angle < endAngle; angle += Math.PI / 2) { if (angle > startAngle) { extremity[0] = Math.cos(angle) * r + x; extremity[1] = Math.sin(angle) * r + y; vec2.min(min, extremity, min); vec2.max(max, extremity, max); } } } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Env.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Tool.Env * @category Visualization Theme * @classdesc 环境识别 * @private */ class Env { constructor() { // Zepto.js // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Env"; var me = this; function detect(ua) { var os = me.os = {}; var browser = me.browser = {}; var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/); var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); var ipad = ua.match(/(iPad).*OS\s([\d_]+)/); var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/); var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/); var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/); var touchpad = webos && ua.match(/TouchPad/); var kindle = ua.match(/Kindle\/([\d.]+)/); var silk = ua.match(/Silk\/([\d._]+)/); var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/); var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/); var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/); var playbook = ua.match(/PlayBook/); var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/); var firefox = ua.match(/Firefox\/([\d.]+)/); var ie = ua.match(/MSIE ([\d.]+)/); var safari = webkit && ua.match(/Mobile\//) && !chrome; var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome; // Todo: clean this up with a better OS/browser seperation: // - discern (more) between multiple browsers on android // - decide if kindle fire in silk mode is android or not // - Firefox on Android doesn't specify the Android version // - possibly devide in os, device and browser hashes /*eslint-disable*/ if (browser.webkit = !!webkit) { browser.version = webkit[1]; } if (android) { os.android = true; os.version = android[2]; } if (iphone && !ipod) { os.ios = os.iphone = true; os.version = iphone[2].replace(/_/g, '.'); } if (ipad) { os.ios = os.ipad = true; os.version = ipad[2].replace(/_/g, '.'); } if (ipod) { os.ios = os.ipod = true; os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null; } if (webos) { os.webos = true; os.version = webos[2]; } if (touchpad) { os.touchpad = true; } if (blackberry) { os.blackberry = true; os.version = blackberry[2]; } if (bb10) { os.bb10 = true; os.version = bb10[2]; } if (rimtabletos) { os.rimtabletos = true; os.version = rimtabletos[2]; } if (playbook) { browser.playbook = true; } if (kindle) { os.kindle = true; os.version = kindle[1]; } if (silk) { browser.silk = true; browser.version = silk[1]; } if (!silk && os.android && ua.match(/Kindle Fire/)) { browser.silk = true; } if (chrome) { browser.chrome = true; browser.version = chrome[1]; } if (firefox) { browser.firefox = true; browser.version = firefox[1]; } if (ie) { browser.ie = true; browser.version = ie[1]; } if (safari && (ua.match(/Safari/) || !!os.ios)) { browser.safari = true; } if (webview) { browser.webview = true; } if (ie) { browser.ie = true; browser.version = ie[1]; } os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) || (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/))); os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos || blackberry || bb10 || (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) || (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/)))); return { browser: browser, os: os, // 原生canvas支持 canvasSupported: document.createElement('canvas').getContext ? true : false }; } return detect(navigator.userAgent); } destory() { return true; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Event.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Tool.Event * @category Visualization Theme * @classdesc LevelRenderer 工具-事件辅助类 * @private */ class Event_Event { constructor() { /** * @member {function} LevelRenderer.Tool.Event.prototype.stop * @description 停止冒泡和阻止默认行为 */ this.stop = typeof window.addEventListener === 'function' ? function (e) { e.preventDefault(); e.stopPropagation(); e.cancelBubble = true; } : function (e) { e.returnValue = false; e.cancelBubble = true; }; this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Event"; } /** * @function LevelRenderer.Tool.Event.prototype.getX * @description 提取鼠标(手指)x坐标。 * @param {Event} e - 事件。 * @returns {number} 鼠标(手指)x坐标。 */ getX(e) { return typeof e.zrenderX != 'undefined' && e.zrenderX || typeof e.offsetX != 'undefined' && e.offsetX || typeof e.layerX != 'undefined' && e.layerX || typeof e.clientX != 'undefined' && e.clientX; } /** * @function LevelRenderer.Tool.Event.prototype.getY * @description 提取鼠标(手指)y坐标。 * @param {Event} e - 事件。 * @returns {number} 鼠标(手指)y坐标。 */ getY(e) { return typeof e.zrenderY != 'undefined' && e.zrenderY || typeof e.offsetY != 'undefined' && e.offsetY || typeof e.layerY != 'undefined' && e.layerY || typeof e.clientY != 'undefined' && e.clientY; } /** * @function LevelRenderer.Tool.Event.prototype.getDelta * @description 提取鼠标滚轮变化。 * @param {Event} e - 事件。 * @returns {number} 滚轮变化,正值说明滚轮是向上滚动,如果是负值说明滚轮是向下滚动。 */ getDelta(e) { return typeof e.zrenderDelta != 'undefined' && e.zrenderDelta || typeof e.wheelDelta != 'undefined' && e.wheelDelta || typeof e.detail != 'undefined' && -e.detail; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Http.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Tool.Http * @category Visualization Theme * @classdesc LevelRenderer 工具-Http */ class Http { constructor() { this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Http" } /** * @function LevelRenderer.Tool.Http.prototype.get * @description get请求。 * @param {(string|IHTTPGetOption)} url - 请求url * @param {function} onsuccess - 请求成功函数 * @param {function} onerror - 请求失败函数 * @param {Object} opts - 额外参数 * @returns {number} cos值 */ get(url, onsuccess, onerror) { if (typeof(url) === 'object') { var obj = url; url = obj.url; onsuccess = obj.onsuccess; onerror = obj.onerror; } var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP'); xhr.open('GET', url, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { onsuccess && onsuccess(xhr.responseText); } else { onerror && onerror(); } xhr.onreadystatechange = new Function(); xhr = null; } }; xhr.send(null); } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Config.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ class Config { } /** * @enum EVENT * @description 事件 * @type {Object} * @private */ Config.EVENT = { //窗口大小变化 RESIZE: 'resize', //鼠标按钮被(手指)按下,事件对象是:目标图形元素或空 CLICK: 'click', //双击事件 DBLCLICK: 'dblclick', //鼠标滚轮变化,事件对象是:目标图形元素或空 MOUSEWHEEL: 'mousewheel', //鼠标(手指)被移动,事件对象是:目标图形元素或空 MOUSEMOVE: 'mousemove', //鼠标移到某图形元素之上,事件对象是:目标图形元素 MOUSEOVER: 'mouseover', //鼠标从某图形元素移开,事件对象是:目标图形元素 MOUSEOUT: 'mouseout', //鼠标按钮(手指)被按下,事件对象是:目标图形元素或空 MOUSEDOWN: 'mousedown', //鼠标按键(手指)被松开,事件对象是:目标图形元素或空 MOUSEUP: 'mouseup', //全局离开,MOUSEOUT触发比较频繁,一次离开优化绑定 GLOBALOUT: 'globalout', // 一次成功元素拖拽的行为事件过程是: // dragstart > dragenter > dragover [> dragleave] > drop > dragend //开始拖拽时触发,事件对象是:被拖拽图形元素 DRAGSTART: 'dragstart', //拖拽完毕时触发(在drop之后触发),事件对象是:被拖拽图形元素 DRAGEND: 'dragend', //拖拽图形元素进入目标图形元素时触发,事件对象是:目标图形元素 DRAGENTER: 'dragenter', //拖拽图形元素在目标图形元素上移动时触发,事件对象是:目标图形元素 DRAGOVER: 'dragover', //拖拽图形元素离开目标图形元素时触发,事件对象是:目标图形元素 DRAGLEAVE: 'dragleave', //拖拽图形元素放在目标图形元素内时触发,事件对象是:目标图形元素 DROP: 'drop', //touch end - start < delay is click touchClickDelay: 300 }; /** * @enum catchBrushException * @description 是否异常捕获 * @type {boolean} * @private */ Config.catchBrushException = false; /** * @enum debugMode * @description debug 日志选项:catchBrushException 为 true 下有效。 * 0 : 不生成debug数据,发布用 * 1 : 异常抛出,调试用 * 2 : 控制台输出,调试用 * @type {boolean} * @private */ Config.debugMode = 0; ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Log.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Tool.Log * @category Visualization Theme * @classdesc LevelRenderer 工具-日志 */ class Log { constructor() { this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Log"; return function () { if (+Config.debugMode === 0) { return; } else if (+Config.debugMode === 1) { for (let k in arguments) { throw new Error(arguments[k]); } } else if (+Config.debugMode > 1) { for (let k in arguments) { console.log(arguments[k]); } } }; /* for debug return function(mes) { document.getElementById('wrong-message').innerHTML = mes + ' ' + (new Date() - 0) + '
' + document.getElementById('wrong-message').innerHTML; }; */ } destory() { return true; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Math.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Tool.Math * @category Visualization Theme * @classdesc LevelRenderer 工具-数学辅助类 */ class MathTool { constructor() { /** * @member {number} LevelRenderer.Tool.Math._radians * @description 角度与弧度转化参数 */ this._radians = window.Math.PI / 180; this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Math"; } /** * @function LevelRenderer.Tool.Math.prototype.sin * @description 正弦函数。 * @param {number} angle - 弧度(角度)参数。 * @param {boolean} [isDegrees=false] - angle参数是否为角度计算,angle为以弧度计量的角度。 * @returns {number} sin 值。 */ sin(angle, isDegrees) { return window.Math.sin(isDegrees ? angle * this._radians : angle); } /** * @function LevelRenderer.Tool.Math.prototype.cos * @description 余弦函数。 * @param {number} angle - 弧度(角度)参数。 * @param {boolean} [isDegrees=false] - angle参数是否为角度计算,angle为以弧度计量的角度。 * @returns {number} cos 值。 */ cos(angle, isDegrees) { return window.Math.cos(isDegrees ? angle * this._radians : angle); } /** * @function LevelRenderer.Tool.Math.prototype.degreeToRadian * @description 角度转弧度。 * @param {number} angle - 弧度(角度)参数。 * @param {boolean} [isDegrees=false] - angle参数是否为角度计算,angle为以弧度计量的角度。 * @returns {number} 弧度值。 */ degreeToRadian(angle) { return angle * this._radians; } /** * @function LevelRenderer.Tool.Math.prototype.radianToDegree * @description 弧度转角度。 * @param {number} angle - 弧度(角度)参数。 * @param {boolean} [isDegrees=false] - angle参数是否为角度计算,angle为以弧度计量的角度。 * @returns {number} 角度。 */ radianToDegree(angle) { return angle / this._radians; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Matrix.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Tool.Matrix * @category Visualization Theme * @classdesc LevelRenderer 工具-3x2矩阵操作类 */ class Matrix { constructor() { /** * @member {Object} LevelRenderer.Tool.Matrix.prototype.ArrayCtor * @description 数组类型控制 */ this.ArrayCtor = typeof Float32Array === 'undefined' ? Array : Float32Array; this.CLASS_NAME = "SuperMap.LevelRenderer.Tool.Matrix"; } /** * @function LevelRenderer.Tool.Matrix.prototype.create * @description 创建一个单位矩阵。 * @returns {(Float32Array|Array.)} 单位矩阵。 */ create() { var ArrayCtor = this.ArrayCtor; var out = new ArrayCtor(6); this.identity(out); return out; } /** * @function LevelRenderer.Tool.Matrix.prototype.identity * @description 设置矩阵为单位矩阵。 * @param {(Float32Array|Array.)} out - 单位矩阵。 * @returns {(Float32Array|Array.)} 单位矩阵。 */ identity(out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 1; out[4] = 0; out[5] = 0; return out; } /** * @function LevelRenderer.Tool.Matrix.prototype.copy * @description 复制矩阵。 * @param {(Float32Array|Array.)} out - 单位矩阵。 * @returns {(Float32Array|Array.)} 克隆矩阵。 */ copy(out, m) { out[0] = m[0]; out[1] = m[1]; out[2] = m[2]; out[3] = m[3]; out[4] = m[4]; out[5] = m[5]; return out; } /** * @function LevelRenderer.Tool.Matrix.prototype.mul * @description 矩阵相乘。 * @param {(Float32Array|Array.)} out - 单位矩阵。 * @param {(Float32Array|Array.)} m1 - 矩阵m1。 * @param {(Float32Array|Array.)} m2- 矩阵m2。 * @returns {(Float32Array|Array.)} 结果矩阵。 */ mul(out, m1, m2) { out[0] = m1[0] * m2[0] + m1[2] * m2[1]; out[1] = m1[1] * m2[0] + m1[3] * m2[1]; out[2] = m1[0] * m2[2] + m1[2] * m2[3]; out[3] = m1[1] * m2[2] + m1[3] * m2[3]; out[4] = m1[0] * m2[4] + m1[2] * m2[5] + m1[4]; out[5] = m1[1] * m2[4] + m1[3] * m2[5] + m1[5]; return out; } /** * @function LevelRenderer.Tool.Matrix.prototype.mul * @description 平移变换。 * @param {(Float32Array|Array.)} out - 单位矩阵。 * @param {(Float32Array|Array.)} a - 矩阵。 * @param {(Float32Array|Array.)} v- 平移参数。 * @returns {(Float32Array|Array.)} 结果矩阵。 */ translate(out, a, v) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4] + v[0]; out[5] = a[5] + v[1]; return out; } /** * @function LevelRenderer.Tool.Matrix.prototype.rotate * @description 平移变换。 * @param {(Float32Array|Array.)} out - 单位矩阵。 * @param {(Float32Array|Array.)} a - 矩阵。 * @param {(Float32Array|Array.)} rad - 旋转参数。 * @returns {(Float32Array|Array.)} 结果矩阵。 */ rotate(out, a, rad) { var aa = a[0]; var ac = a[2]; var atx = a[4]; var ab = a[1]; var ad = a[3]; var aty = a[5]; var st = Math.sin(rad); var ct = Math.cos(rad); out[0] = aa * ct + ab * st; out[1] = -aa * st + ab * ct; out[2] = ac * ct + ad * st; out[3] = -ac * st + ct * ad; out[4] = ct * atx + st * aty; out[5] = ct * aty - st * atx; return out; } /** * @function LevelRenderer.Tool.Matrix.prototype.scale * @description 缩放变换。 * @param {(Float32Array|Array.)} out - 单位矩阵。 * @param {(Float32Array|Array.)} a - 矩阵。 * @param {(Float32Array|Array.)} v - 缩放参数。 * @returns {(Float32Array|Array.)} 结果矩阵。 */ scale(out, a, v) { var vx = v[0]; var vy = v[1]; out[0] = a[0] * vx; out[1] = a[1] * vy; out[2] = a[2] * vx; out[3] = a[3] * vy; out[4] = a[4] * vx; out[5] = a[5] * vy; return out; } /** * @function LevelRenderer.Tool.Matrix.prototype.invert * @description 求逆矩阵。 * @param {(Float32Array|Array.)} out - 单位矩阵。 * @param {(Float32Array|Array.)} a - 矩阵。 * @returns {(Float32Array|Array.)} 结果矩阵。 */ invert(out, a) { var aa = a[0]; var ac = a[2]; var atx = a[4]; var ab = a[1]; var ad = a[3]; var aty = a[5]; var det = aa * ad - ab * ac; if (!det) { return null; } det = 1.0 / det; out[0] = ad * det; out[1] = -ab * det; out[2] = -ac * det; out[3] = aa * det; out[4] = (ac * aty - ad * atx) * det; out[5] = (ab * atx - aa * aty) * det; return out; } /** * @function LevelRenderer.Tool.Matrix.prototype.mulVector * @description 矩阵左乘向量。 * @param {(Float32Array|Array.)} out - 单位矩阵。 * @param {(Float32Array|Array.)} a - 矩阵。 * @param {(Float32Array|Array.)} v - 缩放参数。 * @returns {(Float32Array|Array.)} 结果矩阵。 */ mulVector(out, a, v) { var aa = a[0]; var ac = a[2]; var atx = a[4]; var ab = a[1]; var ad = a[3]; var aty = a[5]; out[0] = v[0] * aa + v[1] * ac + atx; out[1] = v[0] * ab + v[1] * ad + aty; return out; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SUtil.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ class SUtil_SUtil { /** * @function LevelRenderer.SUtil.SUtil_smoothBezier * @description 贝塞尔平滑曲线。 * @private * @param {Array} points - 线段顶点数组。 * @param {number} smooth - 平滑等级, 0-1。 * @param {boolean} isLoop - isLoop。 * @param {Array} constraint - 将计算出来的控制点约束在一个包围盒内,比如 [[0, 0], [100, 100]], 这个包围盒会与整个折线的包围盒做一个并集用来约束控制点。 * @param {Array.} [originalPosition=[0, 0]] - 参考原点。 * @return {Array} 生成的平滑节点数组。 */ static SUtil_smoothBezier(points, smooth, isLoop, constraint, originalPosition) { if (!originalPosition || originalPosition.length !== 2) { originalPosition = [0, 0]; } var __OP = originalPosition; var cps = []; var v = []; var v1 = []; var v2 = []; var hasConstraint = !!constraint; var min, max; if (hasConstraint) { min = [Infinity, Infinity]; max = [-Infinity, -Infinity]; let len = points.length; for (let i = 0; i < len; i++) { SUtil_SUtil.Util_vector.min(min, min, [points[i][0] + __OP[0], points[i][1] + __OP[1]]); SUtil_SUtil.Util_vector.max(max, max, [points[i][0] + __OP[0], points[i][1] + __OP[1]]); } // 与指定的包围盒做并集 SUtil_SUtil.Util_vector.min(min, min, constraint[0]); SUtil_SUtil.Util_vector.max(max, max, constraint[1]); } let len = points.length; for (let i = 0; i < len; i++) { let point = [points[i][0] + __OP[0], points[i][1] + __OP[1]]; let prevPoint; let nextPoint; if (isLoop) { prevPoint = [points[i ? i - 1 : len - 1][0] + __OP[0], points[i ? i - 1 : len - 1][1] + __OP[1]]; nextPoint = [points[(i + 1) % len][0] + __OP[0], points[(i + 1) % len][1] + __OP[1]]; } else { if (i === 0 || i === len - 1) { cps.push([points[i][0] + __OP[0], points[i][1] + __OP[1]]); continue; } else { prevPoint = [points[i - 1][0] + __OP[0], points[i - 1][1] + __OP[1]]; nextPoint = [points[i + 1][0] + __OP[0], points[i + 1][1] + __OP[1]]; } } SUtil_SUtil.Util_vector.sub(v, nextPoint, prevPoint); // use degree to scale the handle length SUtil_SUtil.Util_vector.scale(v, v, smooth); let d0 = SUtil_SUtil.Util_vector.distance(point, prevPoint); let d1 = SUtil_SUtil.Util_vector.distance(point, nextPoint); let sum = d0 + d1; if (sum !== 0) { d0 /= sum; d1 /= sum; } SUtil_SUtil.Util_vector.scale(v1, v, -d0); SUtil_SUtil.Util_vector.scale(v2, v, d1); let cp0 = SUtil_SUtil.Util_vector.add([], point, v1); let cp1 = SUtil_SUtil.Util_vector.add([], point, v2); if (hasConstraint) { SUtil_SUtil.Util_vector.max(cp0, cp0, min); SUtil_SUtil.Util_vector.min(cp0, cp0, max); SUtil_SUtil.Util_vector.max(cp1, cp1, min); SUtil_SUtil.Util_vector.min(cp1, cp1, max); } cps.push(cp0); cps.push(cp1); } if (isLoop) { cps.push(cps.shift()); } return cps; } /** * @function LevelRenderer.SUtil.SUtil_smoothSpline * @description 插值折线。 * @private * @param {Array} points - 线段顶点数组。 * @param {boolean} isLoop - isLoop。 * @param {Array} constraint - 将计算出来的控制点约束在一个包围盒内,比如 [[0, 0], [100, 100]], 这个包围盒会与整个折线的包围盒做一个并集用来约束控制点。 * @param {Array.} originalPosition - 参考原点。默认值:[0, 0]。 * @return {Array} 生成的平滑节点数组。 */ static SUtil_smoothSpline(points, isLoop, constraint, originalPosition) { if (!originalPosition || originalPosition.length !== 2) { originalPosition = [0, 0]; } var __OP = originalPosition; var len = points.length; var ret = []; var distance = 0; for (let i = 1; i < len; i++) { distance += SUtil_SUtil.Util_vector.distance([points[i - 1][0] + __OP[0], points[i - 1][1] + __OP[1]], [points[i][0] + __OP[0], points[i][1] + __OP[1]]); } var segs = distance / 5; segs = segs < len ? len : segs; for (let i = 0; i < segs; i++) { let pos = i / (segs - 1) * (isLoop ? len : len - 1); let idx = Math.floor(pos); let w = pos - idx; let p0; let p1 = [points[idx % len][0] + __OP[0], points[idx % len][1] + __OP[1]]; let p2; let p3; if (!isLoop) { p0 = [points[idx === 0 ? idx : idx - 1][0] + __OP[0], points[idx === 0 ? idx : idx - 1][1] + __OP[1]]; p2 = [points[idx > len - 2 ? len - 1 : idx + 1][0] + __OP[0], points[idx > len - 2 ? len - 1 : idx + 1][1] + __OP[1]]; p3 = [points[idx > len - 3 ? len - 1 : idx + 2][0] + __OP[0], points[idx > len - 3 ? len - 1 : idx + 2][1] + __OP[1]]; } else { p0 = [points[(idx - 1 + len) % len][0] + __OP[0], points[(idx - 1 + len) % len][1] + __OP[1]]; p2 = [points[(idx + 1) % len][0] + __OP[0], points[(idx + 1) % len][1] + __OP[1]]; p3 = [points[(idx + 2) % len][0] + __OP[0], points[(idx + 2) % len][1] + __OP[1]]; } let w2 = w * w; let w3 = w * w2; ret.push([ interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3), interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3) ]); } return ret; // inner Function function interpolate(p0, p1, p2, p3, t, t2, t3) { var v0 = (p2 - p0) * 0.5; var v1 = (p3 - p1) * 0.5; return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1; } } /** * @function LevelRenderer.SUtil.SUtil_dashedLineTo * @description 虚线 lineTo。 */ static SUtil_dashedLineTo(ctx, x1, y1, x2, y2, dashLength, customDashPattern) { // http://msdn.microsoft.com/en-us/library/ie/dn265063(v=vs.85).aspx var dashPattern = [5, 5]; dashLength = typeof dashLength != 'number' ? 5 : dashLength; if (ctx.setLineDash) { dashPattern[0] = dashLength; dashPattern[1] = dashLength; if (customDashPattern && (customDashPattern instanceof Array)) { ctx.setLineDash(customDashPattern); } else { ctx.setLineDash(dashPattern); } // ctx.setLineDash(dashPattern); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); return; } var dx = x2 - x1; var dy = y2 - y1; var numDashes = Math.floor( Math.sqrt(dx * dx + dy * dy) / dashLength ); dx = dx / numDashes; dy = dy / numDashes; var flag = true; for (var i = 0; i < numDashes; ++i) { if (flag) { ctx.moveTo(x1, y1); } else { ctx.lineTo(x1, y1); } flag = !flag; x1 += dx; y1 += dy; } ctx.lineTo(x2, y2); } } // 把所有工具对象放到全局静态变量上,以便直接调用工具方法, // 避免使用工具时频繁的创建工具对象带来的性能消耗。 SUtil_SUtil.Util_area = new Area(); SUtil_SUtil.Util_color = new Color(); SUtil_SUtil.Util_computeBoundingBox = new ComputeBoundingBox(); SUtil_SUtil.Util_curve = new Curve_Curve(); SUtil_SUtil.Util_env = new Env(); SUtil_SUtil.Util_event = new Event_Event(); SUtil_SUtil.Util_http = new Http(); SUtil_SUtil.Util_log = new Log(); SUtil_SUtil.Util_math = new MathTool(); SUtil_SUtil.Util_matrix = new Matrix(); SUtil_SUtil.Util = new Util_Util(); SUtil_SUtil.Util_vector = new levelRenderer_Vector_Vector(); ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Transformable.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Transformable * @category Visualization Theme * @classdesc 可变换超类,所有支持 Canvas Transform 变换操作的类均是此类的子类。此类不可实例化。 */ class Transformable { constructor() { /** * @member {Array.} LevelRenderer.Transformable.prototype.position * @description 平移,默认值:[0, 0]。 */ this.position = [0, 0]; /** * @member {Array.} LevelRenderer.Transformable.prototype.rotation * @description 旋转,可以通过数组二三项指定旋转的原点,默认值:[0, 0, 0]。 */ this.rotation = [0, 0, 0]; /** * @member {Array.} LevelRenderer.Transformable.prototype.scale * @description 缩放,可以通过数组三四项指定缩放的原点,默认值:[1, 1, 0, 0]。 */ this.scale = [1, 1, 0, 0]; /** * @member {boolean} LevelRenderer.Transformable.prototype.needLocalTransform * @description 是否变换。默认值:false。 */ this.needLocalTransform = false; /** * @member {boolean} LevelRenderer.Transformable.prototype.needTransform * @description 是否有坐标变换。默认值:false。 */ this.needTransform = false; this.CLASS_NAME = "SuperMap.LevelRenderer.Transformable"; /** * @function LevelRenderer.Transformable.prototype.lookAt * @description 设置图形的朝向。 */ this.lookAt = (function () { var v = SUtil_SUtil.Util_vector.create(); // {Array.|Float32Array} target return function (target) { if (!this.transform) { this.transform = SUtil_SUtil.Util_matrix.create(); } var m = this.transform; SUtil_SUtil.Util_vector.sub(v, target, this.position); if (isAroundZero(v[0]) && isAroundZero(v[1])) { return; } SUtil_SUtil.Util_vector.normalize(v, v); // Y Axis // TODO Scale origin ? m[2] = v[0] * this.scale[1]; m[3] = v[1] * this.scale[1]; // X Axis m[0] = v[1] * this.scale[0]; m[1] = -v[0] * this.scale[0]; // Position m[4] = this.position[0]; m[5] = this.position[1]; this.decomposeTransform(); function isAroundZero(val) { var EPSILON = 5e-5; return val > -EPSILON && val < EPSILON; } }; })(); } /** * @function LevelRenderer.Transformable.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.position = null; this.rotation = null; this.scale = null; this.needLocalTransform = null; this.needTransform = null; } /** * @function LevelRenderer.Transformable.prototype.updateNeedTransform * @description 更新 needLocalTransform */ updateNeedTransform() { this.needLocalTransform = isNotAroundZero(this.rotation[0]) || isNotAroundZero(this.position[0]) || isNotAroundZero(this.position[1]) || isNotAroundZero(this.scale[0] - 1) || isNotAroundZero(this.scale[1] - 1); function isNotAroundZero(val) { var EPSILON = 5e-5; return val > EPSILON || val < -EPSILON; } } /** * @function LevelRenderer.Transformable.prototype.updateTransform * @description 判断是否需要有坐标变换,更新 needTransform 属性。如果有坐标变换,则从 position, rotation, scale 以及父节点的 transform 计算出自身的 transform 矩阵。 */ updateTransform() { this.updateNeedTransform(); if (this.parent) { this.needTransform = this.needLocalTransform || this.parent.needTransform; } else { this.needTransform = this.needLocalTransform; } if (!this.needTransform) { return; } var origin = [0, 0]; var m = this.transform || SUtil_SUtil.Util_matrix.create(); SUtil_SUtil.Util_matrix.identity(m); if (this.needLocalTransform) { if ( isNotAroundZero(this.scale[0]) || isNotAroundZero(this.scale[1]) ) { origin[0] = -this.scale[2] || 0; origin[1] = -this.scale[3] || 0; let haveOrigin = isNotAroundZero(origin[0]) || isNotAroundZero(origin[1]); if (haveOrigin) { SUtil_SUtil.Util_matrix.translate( m, m, origin ); } SUtil_SUtil.Util_matrix.scale(m, m, this.scale); if (haveOrigin) { origin[0] = -origin[0]; origin[1] = -origin[1]; SUtil_SUtil.Util_matrix.translate( m, m, origin ); } } if (this.rotation instanceof Array) { if (this.rotation[0] !== 0) { origin[0] = -this.rotation[1] || 0; origin[1] = -this.rotation[2] || 0; let haveOrigin = isNotAroundZero(origin[0]) || isNotAroundZero(origin[1]); if (haveOrigin) { SUtil_SUtil.Util_matrix.translate( m, m, origin ); } SUtil_SUtil.Util_matrix.rotate(m, m, this.rotation[0]); if (haveOrigin) { origin[0] = -origin[0]; origin[1] = -origin[1]; SUtil_SUtil.Util_matrix.translate( m, m, origin ); } } } else { if (+this.rotation !== 0) { SUtil_SUtil.Util_matrix.rotate(m, m, this.rotation); } } if ( isNotAroundZero(this.position[0]) || isNotAroundZero(this.position[1]) ) { SUtil_SUtil.Util_matrix.translate(m, m, this.position); } } // 保存这个变换矩阵 this.transform = m; // 应用父节点变换 if (this.parent && this.parent.needTransform) { if (this.needLocalTransform) { SUtil_SUtil.Util_matrix.mul(this.transform, this.parent.transform, this.transform); } else { SUtil_SUtil.Util_matrix.copy(this.transform, this.parent.transform); } } function isNotAroundZero(val) { var EPSILON = 5e-5; return val > EPSILON || val < -EPSILON; } } /** * @function LevelRenderer.Transformable.prototype.setTransform * @description 将自己的 transform 应用到 context 上。 * * @param {Context2D} ctx - Context2D 上下文。 */ setTransform(ctx) { if (this.needTransform) { var m = this.transform; ctx.transform( m[0], m[1], m[2], m[3], m[4], m[5] ); } } /** * @function LevelRenderer.Transformable.prototype.decomposeTransform * @description 分解`transform`矩阵到`position`, `rotation`, `scale` 。 */ decomposeTransform() { if (!this.transform) { return; } var m = this.transform; var sx = m[0] * m[0] + m[1] * m[1]; var position = this.position; var scale = this.scale; var rotation = this.rotation; if (isNotAroundZero(sx - 1)) { sx = Math.sqrt(sx); } var sy = m[2] * m[2] + m[3] * m[3]; if (isNotAroundZero(sy - 1)) { sy = Math.sqrt(sy); } position[0] = m[4]; position[1] = m[5]; scale[0] = sx; scale[1] = sy; scale[2] = scale[3] = 0; rotation[0] = Math.atan2(-m[1] / sy, m[0] / sx); rotation[1] = rotation[2] = 0; function isNotAroundZero(val) { var EPSILON = 5e-5; return val > EPSILON || val < -EPSILON; } } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Shape.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape * @category Visualization Theme * @classdesc 图形(shape)基类。 * @extends LevelRenderer.Eventful * @extends LevelRenderer.Transformable * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 */ class Shape_Shape extends mixinExt(Eventful, Transformable) { constructor(options) { super(options); options = options || {}; /** * @member {string} LevelRenderer.Shape.prototype.id * @description 唯一标识。 */ this.id = null; /** * @member {Object} LevelRenderer.Shape.prototype.style * @description 基础绘制样式。 * @param {string} style.brushType - 画笔类型。可设值:"fill", "stroke", "both"。默认值:"fill"。 * @param {string} style.color - 填充颜色。默认值:"#000000'"。 * @param {string} style.strokeColor - 描边颜色。默认值:"#000000'"。 * @param {string} style.lineCape - 线帽样式。可设值:"butt", "round", "square"。默认值:"butt"。 * @param {number} style.lineWidth - 描边宽度。默认值:1。 * @param {number} style.opacity - 绘制透明度。默认值:1。 * @param {number} style.shadowBlur - 阴影模糊度,大于0有效。默认值:0。 * @param {number} style.shadowColor - 阴影颜色。默认值:"#000000'"。 * @param {number} style.shadowOffsetX - 阴影横向偏移。默认值:0。 * @param {number} style.shadowOffsetY - 阴影纵向偏移。默认值:0。 * @param {string} style.text - 图形中的附加文本。默认值:""。 * @param {string} style.textColor - 文本颜色。默认值:"#000000'"。 * @param {string} style.textFont - 附加文本样式。示例:'bold 18px verdana'。 * @param {string} style.textPosition - 附加文本位置。可设值:"inside", "left", "right", top", "bottom", "end"。默认值:"end"。 * @param {string} style.textAlign - 附加文本水平对齐。可设值:"start", "end", "left", "right", "center"。默认根据 textPosition 自动设置。 * @param {string} style.textBaseline - 附加文本垂直对齐。可设值:"top", "bottom", "middle", "alphabetic", "hanging", "ideographic"。默认根据 textPosition 自动设置。 * */ this.style = {}; /** * @member {Object} LevelRenderer.Shape.prototype.style.__rect * @description 包围图形的最小矩形盒子。 * * @param {number} x - 左上角顶点x轴坐标。 * @param {number} y - 左上角顶点y轴坐标。 * @param {number} width - 包围盒矩形宽度。 * @param {number} height - 包围盒矩形高度。 */ /** * @member {Object} LevelRenderer.Shape.prototype.highlightStyle * @description 高亮样式。 * * @param {string} highlightStyle.brushType - 画笔类型。可设值:"fill", "stroke", "both"。默认值:"fill"。 * @param {string} highlightStyle.color - 填充颜色。默认值:"#000000'"。 * @param {string} highlightStyle.strokeColor - 描边颜色。默认值:"#000000'"。 * @param {string} highlightStyle.lineCape - 线帽样式。可设值:"butt", "round", "square"。默认值:"butt"。 * @param {number} highlightStyle.lineWidth - 描边宽度。默认值:1。 * @param {number} highlightStyle.opacity - 绘制透明度。默认值:1。 * @param {number} highlightStyle.shadowBlur - 阴影模糊度,大于0有效。默认值:0。 * @param {number} highlightStyle.shadowColor - 阴影颜色。默认值:"#000000'"。 * @param {number} highlightStyle.shadowOffsetX - 阴影横向偏移。默认值:0。 * @param {number} highlightStyle.shadowOffsetY - 阴影纵向偏移。默认值:0。 * @param {string} highlightStyle.text - 图形中的附加文本。默认值:""。 * @param {string} highlightStyle.textColor - 文本颜色。默认值:"#000000'"。 * @param {string} highlightStyle.textFont - 附加文本样式。示例:'bold 18px verdana'。 * @param {string} highlightStyle.textPosition - 附加文本位置。可设值:"inside", "left", "right", top", "bottom", "end"。默认值:"end"。 * @param {string} highlightStyle.textAlign - 附加文本水平对齐。可设值:"start", "end", "left", "right", "center"。默认根据 textPosition 自动设置。 * @param {string} highlightStyle.textBaseline - 附加文本垂直对齐。可设值:"top", "bottom", "middle", "alphabetic", "hanging", "ideographic"。默认根据 textPosition 自动设置。 */ this.highlightStyle = null; /** * @member {Object} LevelRenderer.Shape.prototype.parent * @description 父节点,只读属性。 */ this.parent = null; /** * @member {boolean} LevelRenderer.Shape.prototype.__dirty * @description {boolean} */ this.__dirty = true; /** * @member {Array} LevelRenderer.Shape.prototype.__clipShapes * @description {Array} * */ this.__clipShapes = []; /** * @member {boolean} LevelRenderer.Shape.prototype.invisible * @description 图形是否可见,为 true 时不绘制图形,但是仍能触发鼠标事件。默认值:false。 */ this.invisible = false; /** * @member {boolean} LevelRenderer.Shape.prototype.ignore * @description 图形是否忽略,为 true 时忽略图形的绘制以及事件触发。默认值:false。 */ this.ignore = false; /** * @member {boolean} LevelRenderer.Shape.prototype.zlevel * @description z 层 level,决定绘画在哪层 canvas 中。默认值:0。 */ this.zlevel = 0; /** * @member {boolean} LevelRenderer.Shape.prototype.draggable * @description 是否可拖拽。默认值:false。 */ this.draggable = false; /** * @member {boolean} LevelRenderer.Shape.prototype.clickable * @description 是否可点击。默认值:false。 */ this.clickable = false; /** * @member {boolean} LevelRenderer.Shape.prototype.hoverable * @description 是否可以 hover。默认值:true。 */ this.hoverable = true; /** * @member {number} LevelRenderer.Shape.prototype.z * @description z值,跟zlevel一样影响shape绘制的前后顺序,z值大的shape会覆盖在z值小的上面,但是并不会创建新的canvas,所以优先级低于zlevel,而且频繁改动的开销比zlevel小很多。默认值:0。 */ this.z = 0; //地理扩展 /** * @member {Array.} LevelRenderer.Shape.prototype.refOriginalPosition * @description 图形参考原点位置,图形的参考中心位置。 * refOriginalPosition 是长度为 2 的数组,第一个元素表示 x 坐标,第二个元素表示 y 坐标。 * * refOriginalPosition 表示图形的参考中心,通常情况下,图形是使用 canvas 的原点位置作为位置参考, * 但 refOriginalPosition 可以改变图形的参考位置,例如: refOriginalPosition = [80, 80], * 图形圆的 style.x = 20, style.y = 20,那么圆在 canvas 中的实际位置是 [100, 100]。 * * 图形(Shape) 的所有位置相关属性都是以 refOriginalPosition 为参考中心, * 也就是说图形的所有位置信息在 canvas 中都是以 refOriginalPosition 为参考的相对位置,只有 * refOriginalPosition 的值为 [0, 0] 时,形的位置信息才是 canvas 绝对位置。 * * 图形的位置信息通常有:style.pointList,style.x,style.y。 * * refOriginalPosition。默认值是: [0, 0]。 */ this.refOriginalPosition = [0, 0]; /** * @member {string} LevelRenderer.Shape.prototype.refDataID * @description 图形所关联数据的 ID。 * */ this.refDataID = null; /** * @member {boolean} LevelRenderer.Shape.prototype.isHoverByRefDataID * @description 是否根据 refDataID 进行高亮。用于同时高亮所有 refDataID 相同的图形。 * */ this.isHoverByRefDataID = false; /** * @member {string} LevelRenderer.Shape.prototype.refDataHoverGroup * @description 高亮图形组的组名。此属性在 refDataID 有效且 isHoverByRefDataID 为 true 时生效。 * 一旦设置此属性,且属性值有效,只有关联同一个数据的图形且此属性相同的图形才会高亮。 * */ this.refDataHoverGroup = null; /** * @member {Object} LevelRenderer.Shape.prototype.dataInfo * @description 图形的数据信息。 * */ this.dataInfo = null; Util.extend(this, options); this.id = this.id || Util.createUniqueID("smShape_"); this.CLASS_NAME = "SuperMap.LevelRenderer.Shape"; /** * @function LevelRenderer.Shape.prototype.getTansform * @description 变换鼠标位置到 shape 的局部坐标空间 * */ this.getTansform = (function () { var invTransform = []; return function (x, y) { var originPos = [x, y]; // 对鼠标的坐标也做相同的变换 if (this.needTransform && this.transform) { SUtil_SUtil.Util_matrix.invert(invTransform, this.transform); SUtil_SUtil.Util_matrix.mulVector(originPos, invTransform, [x, y, 1]); if (x == originPos[0] && y == originPos[1]) { // 避免外部修改导致的 needTransform 不准确 this.updateNeedTransform(); } } return originPos; }; })(); } /** * @function LevelRenderer.Shape.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.id = null; this.style = null; this.highlightStyle = null; this.parent = null; this.__dirty = null; this.__clipShapes = null; this.invisible = null; this.ignore = null; this.zlevel = null; this.draggable = null; this.clickable = null; this.hoverable = null; this.z = null; this.refOriginalPosition = null; this.refDataID = null; this.refDataHoverGroup = null; this.isHoverByRefDataID = null; this.dataInfo = null; super.destroy(); } /** * @function LevelRenderer.Shape.prototype.brush * @description 绘制图形。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {boolean} isHighlight - 是否使用高亮属性。 * @param {function} updateCallback - 需要异步加载资源的 shape 可以通过这个 callback(e),让painter更新视图,base.brush 没用,需要的话重载 brush。 */ brush(ctx, isHighlight) { var style = this.beforeBrush(ctx, isHighlight); ctx.beginPath(); this.buildPath(ctx, style); switch (style.brushType) { /* jshint ignore:start */ case 'both': this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fill(); if (style.lineWidth > 0) { this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.stroke(); } this.setCtxGlobalAlpha(ctx, "reset", style); break; case 'stroke': this.setCtxGlobalAlpha(ctx, "stroke", style); style.lineWidth > 0 && ctx.stroke(); this.setCtxGlobalAlpha(ctx, "reset", style); break; /* jshint ignore:end */ default: this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fill(); this.setCtxGlobalAlpha(ctx, "reset", style); break; } this.drawText(ctx, style, this.style); this.afterBrush(ctx); } /** * @function LevelRenderer.Shape.prototype.beforeBrush * @description 具体绘制操作前的一些公共操作。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {boolean} isHighlight - 是否使用高亮属性。 * @return {Object} 处理后的样式。 */ beforeBrush(ctx, isHighlight) { var style = this.style; if (this.brushTypeOnly) { style.brushType = this.brushTypeOnly; } if (isHighlight) { // 根据style扩展默认高亮样式 style = this.getHighlightStyle( style, this.highlightStyle || {}, this.brushTypeOnly ); } if (this.brushTypeOnly == 'stroke') { style.strokeColor = style.strokeColor || style.color; } ctx.save(); this.doClip(ctx); this.setContext(ctx, style); // 设置transform this.setTransform(ctx); return style; } /** * @function LevelRenderer.Shape.prototype.afterBrush * @description 绘制后的处理。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * */ afterBrush(ctx) { ctx.restore(); } /** * @function LevelRenderer.Shape.prototype.setContext * @description 设置 fillStyle, strokeStyle, shadow 等通用绘制样式。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - 样式。 * */ setContext(ctx, style) { var STYLE_CTX_MAP = [ ['color', 'fillStyle'], ['strokeColor', 'strokeStyle'], ['opacity', 'globalAlpha'], ['lineCap', 'lineCap'], ['lineJoin', 'lineJoin'], ['miterLimit', 'miterLimit'], ['lineWidth', 'lineWidth'], ['shadowBlur', 'shadowBlur'], ['shadowColor', 'shadowColor'], ['shadowOffsetX', 'shadowOffsetX'], ['shadowOffsetY', 'shadowOffsetY'] ]; for (var i = 0, len = STYLE_CTX_MAP.length; i < len; i++) { var styleProp = STYLE_CTX_MAP[i][0]; var styleValue = style[styleProp]; var ctxProp = STYLE_CTX_MAP[i][1]; if (typeof styleValue != 'undefined') { ctx[ctxProp] = styleValue; } } } /** * @function LevelRenderer.Shape.prototype.doClip * */ doClip(ctx) { var clipShapeInvTransform = SUtil_SUtil.Util_matrix.create(); if (this.__clipShapes) { for (var i = 0; i < this.__clipShapes.length; i++) { var clipShape = this.__clipShapes[i]; if (clipShape.needTransform) { let m = clipShape.transform; SUtil_SUtil.Util_matrix.invert(clipShapeInvTransform, m); ctx.transform( m[0], m[1], m[2], m[3], m[4], m[5] ); } ctx.beginPath(); clipShape.buildPath(ctx, clipShape.style); ctx.clip(); // Transform back if (clipShape.needTransform) { let m = clipShapeInvTransform; ctx.transform( m[0], m[1], m[2], m[3], m[4], m[5] ); } } } } /** * @function LevelRenderer.Shape.prototype.getHighlightStyle * @description 根据默认样式扩展高亮样式 * * @param {Object} style - 样式。 * @param {Object} highlightStyle - 高亮样式。 * @param {string} brushTypeOnly - brushTypeOnly。 * */ getHighlightStyle(style, highlightStyle, brushTypeOnly) { var newStyle = {}; for (let k in style) { newStyle[k] = style[k]; } var highlightColor = SUtil_SUtil.Util_color.getHighlightColor(); // 根据highlightStyle扩展 if (style.brushType != 'stroke') { // 带填充则用高亮色加粗边线 newStyle.strokeColor = highlightColor; // SMIC-方法修改 - start newStyle.lineWidth = (style.lineWidth || 1); // 原始代码 // newStyle.lineWidth = (style.lineWidth || 1) // + this.getHighlightZoom(); // 修改代码1 // if(!style.lineType || style.lineType === "solid"){ // newStyle.lineWidth = (style.lineWidth || 1) // + this.getHighlightZoom(); // } // else{ // newStyle.lineWidth = (style.lineWidth || 1); // } // SMIC-方法修改 - end newStyle.brushType = 'both'; } else { if (brushTypeOnly != 'stroke') { // 描边型的则用原色加工高亮 newStyle.strokeColor = highlightColor; // SMIC-方法修改 - start newStyle.lineWidth = (style.lineWidth || 1); // 原始代码 // newStyle.lineWidth = (style.lineWidth || 1) // + this.getHighlightZoom(); // 修改代码1 // if(!style.lineType || style.lineType === "solid"){ // newStyle.lineWidth = (style.lineWidth || 1) // + this.getHighlightZoom(); // } // else{ // newStyle.lineWidth = (style.lineWidth || 1); // } // SMIC-方法修改 - end } else { // 线型的则用原色加工高亮 newStyle.strokeColor = highlightStyle.strokeColor || SUtil_SUtil.Util_color.mix( style.strokeColor, SUtil_SUtil.Util_color.toRGB(highlightColor) ); } } // 可自定义覆盖默认值 for (let k in highlightStyle) { if (typeof highlightStyle[k] != 'undefined') { newStyle[k] = highlightStyle[k]; } } return newStyle; } /** * @function LevelRenderer.Shape.prototype.getHighlightZoom * @description 高亮放大效果参数,当前统一设置为6,如有需要差异设置,通过 this.type 判断实例类型 * */ getHighlightZoom() { return this.type != 'text' ? 6 : 2; } /** * @function LevelRenderer.Shape.prototype.drift * @description 移动位置 * * @param {Object} dx - 横坐标变化。 * @param {Object} dy - 纵坐标变化。 * */ drift(dx, dy) { this.position[0] += dx; this.position[1] += dy; } /** * @function LevelRenderer.Shape.prototype.buildPath * @description 构建绘制的Path。子类必须重新实现此方法。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - 样式。 */ buildPath(ctx, style) { // eslint-disable-line no-unused-vars SUtil_SUtil.Util_log('buildPath not implemented in ' + this.type); } /** * @function LevelRenderer.Shape.prototype.getRect * @description 计算返回包围盒矩形。子类必须重新实现此方法。 * * @param {Object} style - 样式。 */ getRect(style) { // eslint-disable-line no-unused-vars SUtil_SUtil.Util_log('getRect not implemented in ' + this.type); } /** * @function LevelRenderer.Shape.prototype.isCover * @description 判断鼠标位置是否在图形内。 * * @param {number} x - x。 * @param {number} y - y。 */ isCover(x, y) { var originPos = this.getTansform(x, y); x = originPos[0]; y = originPos[1]; // 快速预判并保留判断矩形 var rect = this.style.__rect; if (!rect) { rect = this.style.__rect = this.getRect(this.style); } if (x >= rect.x && x <= (rect.x + rect.width) && y >= rect.y && y <= (rect.y + rect.height) ) { // 矩形内 return SUtil_SUtil.Util_area.isInside(this, this.style, x, y); } return false; } /** * @function LevelRenderer.Shape.prototype.drawText * @description 绘制附加文本。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {string} style - 样式。 * @param {string} normalStyle - normalStyle 默认样式,用于定位文字显示。 */ drawText(ctx, style, normalStyle) { if (typeof(style.text) == 'undefined' || style.text === false) { return; } // 字体颜色策略 var textColor = style.textColor || style.color || style.strokeColor; ctx.fillStyle = textColor; // 文本与图形间空白间隙 var dd = 10; var al; // 文本水平对齐 var bl; // 文本垂直对齐 var tx; // 文本横坐标 var ty; // 文本纵坐标 var textPosition = style.textPosition // 用户定义 || this.textPosition // shape默认 || 'top'; // 全局默认 // Smic 方法修改 -start var __OP = []; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { __OP = [0, 0]; } else { __OP = this.refOriginalPosition; } //原代码: // Smic 方法修改 -end switch (textPosition) { case 'inside': case 'top': case 'bottom': case 'left': case 'right': if (this.getRect) { var rect = (normalStyle || style).__rect || this.getRect(normalStyle || style); switch (textPosition) { case 'inside': tx = rect.x + rect.width / 2; ty = rect.y + rect.height / 2; al = 'center'; bl = 'middle'; if (style.brushType != 'stroke' && textColor == style.color ) { ctx.fillStyle = '#fff'; } break; case 'left': tx = rect.x - dd; ty = rect.y + rect.height / 2; al = 'end'; bl = 'middle'; break; case 'right': tx = rect.x + rect.width + dd; ty = rect.y + rect.height / 2; al = 'start'; bl = 'middle'; break; case 'top': tx = rect.x + rect.width / 2; ty = rect.y - dd; al = 'center'; bl = 'bottom'; break; case 'bottom': tx = rect.x + rect.width / 2; ty = rect.y + rect.height + dd; al = 'center'; bl = 'top'; break; } } break; case 'start': case 'end': var xStart = 0; var xEnd = 0; var yStart = 0; var yEnd = 0; if (typeof style.pointList != 'undefined') { var pointList = style.pointList; if (pointList.length < 2) { // 少于2个点就不画了~ return; } var length = pointList.length; switch (textPosition) { // Smic 方法修改 -start case 'start': xStart = pointList[0][0] + __OP[0]; xEnd = pointList[1][0] + __OP[0]; yStart = pointList[0][1] + __OP[1]; yEnd = pointList[1][1] + __OP[1]; break; case 'end': xStart = pointList[length - 2][0] + __OP[0]; xEnd = pointList[length - 1][0] + __OP[0]; yStart = pointList[length - 2][1] + __OP[1]; yEnd = pointList[length - 1][1] + __OP[1]; break; //原代码: /* case 'start': xStart = pointList[0][0]; xEnd = pointList[1][0]; yStart = pointList[0][1]; yEnd = pointList[1][1]; break; case 'end': xStart = pointList[length - 2][0]; xEnd = pointList[length - 1][0]; yStart = pointList[length - 2][1]; yEnd = pointList[length - 1][1]; break; */ // Smic 方法修改 -end } } else { // Smic 方法修改 -start xStart = (style.xStart + __OP[0]) || 0; xEnd = (style.xEnd + __OP[0]) || 0; yStart = (style.yStart + __OP[1]) || 0; yEnd = (style.yEnd + __OP[1]) || 0; //原代码: /* xStart = style.xStart || 0; xEnd = style.xEnd || 0; yStart = style.yStart || 0; yEnd = style.yEnd || 0; */ // Smic 方法修改 -end } switch (textPosition) { case 'start': al = xStart < xEnd ? 'end' : 'start'; bl = yStart < yEnd ? 'bottom' : 'top'; tx = xStart; ty = yStart; break; case 'end': al = xStart < xEnd ? 'start' : 'end'; bl = yStart < yEnd ? 'top' : 'bottom'; tx = xEnd; ty = yEnd; break; } dd -= 4; if (xStart && xEnd && xStart != xEnd) { tx -= (al == 'end' ? dd : -dd); } else { al = 'center'; } if (yStart != yEnd) { ty -= (bl == 'bottom' ? dd : -dd); } else { bl = 'middle'; } break; case 'specific': tx = style.textX || 0; ty = style.textY || 0; al = 'start'; bl = 'middle'; break; } // Smic 方法修改 -start if (style.labelXOffset && !isNaN(style.labelXOffset)) { tx += style.labelXOffset; } if (style.labelYOffset && !isNaN(style.labelYOffset)) { ty += style.labelYOffset; } //原代码: // Smic 方法修改 -end if (tx != null && ty != null) { Shape_Shape._fillText( ctx, style.text, tx, ty, style.textFont, style.textAlign || al, style.textBaseline || bl ); } } /** * @function LevelRenderer.Shape.prototype.modSelf * @description 图形发生改变 */ modSelf() { this.__dirty = true; if (this.style) { this.style.__rect = null; } if (this.highlightStyle) { this.highlightStyle.__rect = null; } } /** * @function LevelRenderer.Shape.prototype.isSilent * @description 图形是否会触发事件,通过 bind 绑定的事件 */ isSilent() { return !( this.hoverable || this.draggable || this.clickable || this.onmousemove || this.onmouseover || this.onmouseout || this.onmousedown || this.onmouseup || this.onclick || this.ondragenter || this.ondragover || this.ondragleave || this.ondrop ); } /** * @function LevelRenderer.Shape.prototype.setCtxGlobalAlpha * @description 设置 Cavans 上下文全局透明度 * * @param {Object} _ctx - Cavans 上下文 * @param {string} type - one of 'stroke', 'fill', or 'reset' * @param {Object} style - Symbolizer hash */ setCtxGlobalAlpha(_ctx, type, style) { if (type === "fill") { _ctx.globalAlpha = typeof(style["fillOpacity"]) === "undefined" ? (typeof(style["opacity"]) === "undefined" ? 1 : style['opacity']) : style['fillOpacity']; } else if (type === "stroke") { _ctx.globalAlpha = typeof(style["strokeOpacity"]) === "undefined" ? (typeof(style["opacity"]) === "undefined" ? 1 : style['opacity']) : style['strokeOpacity']; } else { _ctx.globalAlpha = typeof(style["opacity"]) === "undefined" ? 1 : style['opacity']; } } /** * @function LevelRenderer.Shape.prototype._fillText * @description 填充文本 */ static _fillText(ctx, text, x, y, textFont, textAlign, textBaseline) { if (textFont) { ctx.font = textFont; } ctx.textAlign = textAlign; ctx.textBaseline = textBaseline; var rect = Shape_Shape._getTextRect( text, x, y, textFont, textAlign, textBaseline ); text = (text + '').split('\n'); var lineHeight = SUtil_SUtil.Util_area.getTextHeight('ZH', textFont); switch (textBaseline) { case 'top': y = rect.y; break; case 'bottom': y = rect.y + lineHeight; break; default: y = rect.y + lineHeight / 2; } for (var i = 0, l = text.length; i < l; i++) { ctx.fillText(text[i], x, y); y += lineHeight; } } /** * @function LevelRenderer.Shape._getTextRect * @description 返回矩形区域,用于局部刷新和文字定位 * * @param {string} text - text。 * @param {number} x - x。 * @param {number} y - y。 * @param {string} textFont - textFont。 * @param {string} textAlign - textAlign。 * @param {string} textBaseline - textBaseline。 * @return {Object} 矩形区域。 */ static _getTextRect(text, x, y, textFont, textAlign, textBaseline) { var width = SUtil_SUtil.Util_area.getTextWidth(text, textFont); var lineHeight = SUtil_SUtil.Util_area.getTextHeight('ZH', textFont); text = (text + '').split('\n'); switch (textAlign) { case 'end': case 'right': x -= width; break; case 'center': x -= (width / 2); break; } switch (textBaseline) { case 'top': break; case 'bottom': y -= lineHeight * text.length; break; default: y -= lineHeight * text.length / 2; } return { x: x, y: y, width: width, height: lineHeight * text.length }; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicPoint.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicPoint * @category Visualization Theme * @classdesc 点。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicPoint({ * style: { * x: 100, * y: 100, * r: 40, * brushType: 'both', * color: 'blue', * strokeColor: 'red', * lineWidth: 3, * text: 'point' * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 * */ class SmicPoint extends Shape_Shape { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicPoint.prototype.type * @description 图形类型。 */ this.type = 'smicpoint'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicPoint"; } /** * @function cdestroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicPoint.prototype.buildPath * @description 创建点触。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; ctx.arc(style.x + __OP[0], style.y + __OP[1], style.r, 0, Math.PI * 2, true); return; } /** * @function LevelRenderer.Shape.SmicPoint.prototype.getRect * @description 计算返回点的包围盒矩形。该包围盒是直接从四个控制点计算,并非最小包围盒。 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 */ getRect(style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; if (style.__rect) { return style.__rect; } var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } style.__rect = { x: Math.round((style.x + __OP[0]) - style.r - lineWidth / 2), y: Math.round((style.y + __OP[1]) - style.r - lineWidth / 2), width: style.r * 2 + lineWidth, height: style.r * 2 + lineWidth }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicText.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicText * @category Visualization Theme * @extends {LevelRenderer.Shape} * @example * var shape = new LevelRenderer.Shape.SmicText({ * style: { * text: 'Label', * x: 100, * y: 100, * textFont: '14px Arial' * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 */ class SmicText extends Shape_Shape { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicText.prototype.type * @description 图形类型. */ this.type = 'smictext'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicText"; } /** * @function LevelRenderer.Shape.SmicText.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicText.prototype.brush * @description 笔触。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {boolean} isHighlight - 是否使用高亮属性。 * */ brush(ctx, isHighlight) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var style = this.style; if (isHighlight) { // 根据style扩展默认高亮样式 style = this.getHighlightStyle( style, this.highlightStyle || {} ); } if (typeof(style.text) == 'undefined' || style.text === false) { return; } ctx.save(); this.doClip(ctx); this.setContext(ctx, style); // 设置transform this.setTransform(ctx); if (style.textFont) { ctx.font = style.textFont; } ctx.textAlign = style.textAlign || 'start'; ctx.textBaseline = style.textBaseline || 'middle'; var text = (style.text + '').split('\n'); var lineHeight = SUtil_SUtil.Util_area.getTextHeight('ZH', style.textFont); var rect = this.getRectNoRotation(style); // var x = style.x; var x = style.x + __OP[0]; var y; if (style.textBaseline == 'top') { y = rect.y; } else if (style.textBaseline == 'bottom') { y = rect.y + lineHeight; } else { y = rect.y + lineHeight / 2; } var ox = style.x + __OP[0]; var oy = style.y + __OP[1]; //文本绘制 for (var i = 0, l = text.length; i < l; i++) { //是否渲染矩形背景及颜色 if (style.labelRect) { //+4,-2是为了让文字距边框左右边缘有点间隔 ctx.fillRect(rect.x - 2, rect.y, rect.width + 4, rect.height); ctx.fillStyle = style.strokeColor; ctx.strokeRect(rect.x - 2, rect.y, rect.width + 4, rect.height); ctx.fillStyle = style.textColor; } switch (style.brushType) { case 'stroke': this.setCtxGlobalAlpha(ctx, "stroke", style); if (style.textRotation && style.textRotation !== 0) { ctx.save(); ctx.translate(ox, oy); ctx.rotate(style.textRotation * Math.PI / 180); if (style.textBaseline == 'top') { if (style.maxWidth) { ctx.strokeText(text[i], 0, lineHeight * i, style.maxWidth); } else { ctx.strokeText(text[i], 0, lineHeight * i); } } else if (style.textBaseline == 'bottom') { if (style.maxWidth) { ctx.strokeText(text[i], 0, lineHeight * (i + 1) - rect.height, style.maxWidth); } else { ctx.strokeText(text[i], 0, lineHeight * (i + 1) - rect.height); } } else { if (style.maxWidth) { ctx.strokeText(text[i], 0, lineHeight * (i + 1) - rect.height / 2 - lineHeight / 2, style.maxWidth); } else { ctx.strokeText(text[i], 0, lineHeight * (i + 1) - rect.height / 2 - lineHeight / 2); } } ctx.restore(); } else { if (style.maxWidth) { ctx.strokeText(text[i], x, y, style.maxWidth); } else { ctx.strokeText(text[i], x, y); } } this.setCtxGlobalAlpha(ctx, "reset", style); break; case 'both': if (style.textRotation && style.textRotation !== 0) { ctx.save(); ctx.translate(ox, oy); ctx.rotate(style.textRotation * Math.PI / 180); if (style.textBaseline == 'top') { if (style.maxWidth) { this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fillText(text[i], 0, lineHeight * i, style.maxWidth); this.setCtxGlobalAlpha(ctx, "reset", style); this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.strokeText(text[i], 0, lineHeight * i, style.maxWidth); this.setCtxGlobalAlpha(ctx, "reset", style); } else { this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fillText(text[i], 0, lineHeight * i); this.setCtxGlobalAlpha(ctx, "reset", style); this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.strokeText(text[i], 0, lineHeight * i); this.setCtxGlobalAlpha(ctx, "reset", style); } } else if (style.textBaseline == 'bottom') { if (style.maxWidth) { this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fillText(text[i], 0, lineHeight * (i + 1) - rect.height, style.maxWidth); this.setCtxGlobalAlpha(ctx, "reset", style); this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.strokeText(text[i], 0, lineHeight * (i + 1) - rect.height, style.maxWidth); this.setCtxGlobalAlpha(ctx, "reset", style); } else { this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fillText(text[i], 0, lineHeight * (i + 1) - rect.height); this.setCtxGlobalAlpha(ctx, "reset", style); this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.strokeText(text[i], 0, lineHeight * (i + 1) - rect.height); this.setCtxGlobalAlpha(ctx, "reset", style); } } else { if (style.maxWidth) { this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fillText(text[i], 0, lineHeight * (i + 1) - rect.height / 2 - lineHeight / 2, style.maxWidth); this.setCtxGlobalAlpha(ctx, "reset", style); this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.strokeText(text[i], 0, lineHeight * (i + 1) - rect.height / 2 - lineHeight / 2, style.maxWidth); this.setCtxGlobalAlpha(ctx, "reset", style); } else { this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fillText(text[i], 0, lineHeight * (i + 1) - rect.height / 2 - lineHeight / 2); this.setCtxGlobalAlpha(ctx, "reset", style); this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.strokeText(text[i], 0, lineHeight * (i + 1) - rect.height / 2 - lineHeight / 2); this.setCtxGlobalAlpha(ctx, "reset", style); } } ctx.restore(); } else { if (style.maxWidth) { this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fillText(text[i], x, y, style.maxWidth); this.setCtxGlobalAlpha(ctx, "reset", style); this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.strokeText(text[i], x, y, style.maxWidth); this.setCtxGlobalAlpha(ctx, "reset", style); } else { this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fillText(text[i], x, y); this.setCtxGlobalAlpha(ctx, "reset", style); this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.strokeText(text[i], x, y); this.setCtxGlobalAlpha(ctx, "reset", style); } } break; default: //fill or others this.setCtxGlobalAlpha(ctx, "fill", style); if (style.textRotation && style.textRotation !== 0) { ctx.save(); ctx.translate(ox, oy); ctx.rotate(style.textRotation * Math.PI / 180); if (style.textBaseline == 'top') { if (style.maxWidth) { ctx.fillText(text[i], 0, lineHeight * i, style.maxWidth); } else { ctx.fillText(text[i], 0, lineHeight * i); } } else if (style.textBaseline == 'bottom') { if (style.maxWidth) { ctx.fillText(text[i], 0, lineHeight * (i + 1) - rect.height, style.maxWidth); } else { ctx.fillText(text[i], 0, lineHeight * (i + 1) - rect.height); } } else { if (style.maxWidth) { ctx.fillText(text[i], 0, lineHeight * (i + 1) - rect.height / 2 - lineHeight / 2, style.maxWidth); } else { ctx.fillText(text[i], 0, lineHeight * (i + 1) - rect.height / 2 - lineHeight / 2); } } ctx.restore(); } else { if (style.maxWidth) { ctx.fillText(text[i], x, y, style.maxWidth); } else { ctx.fillText(text[i], x, y); } } this.setCtxGlobalAlpha(ctx, "reset", style); } y += lineHeight; } ctx.restore(); return; } /** * @function LevelRenderer.Shape.SmicText.prototype.getRect * @description 返回文字包围盒矩形 */ getRect(style) { if (style.__rect) { return style.__rect; } var left, top, right, bottom var tbg = this.getTextBackground(style, true); for (var i = 0, len = tbg.length; i < len; i++) { var poi = tbg[i]; //用第一个点初始化 if (i == 0) { left = poi[0]; right = poi[0]; top = poi[1]; bottom = poi[1]; } else { if (poi[0] < left) { left = poi[0] } if (poi[0] > right) { right = poi[0] } if (poi[1] < top) { top = poi[1] } if (poi[1] > bottom) { bottom = poi[1] } } } style.__rect = { x: left, y: top, width: right - left, height: bottom - top }; return style.__rect; } /** * @function LevelRenderer.Shape.SmicText.prototype.getRectNoRotation * @description 返回忽略旋转和maxWidth时文字包围盒矩形 */ getRectNoRotation(style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var lineHeight = SUtil_SUtil.Util_area.getTextHeight('ZH', style.textFont); var width = SUtil_SUtil.Util_area.getTextWidth(style.text, style.textFont); var height = SUtil_SUtil.Util_area.getTextHeight(style.text, style.textFont); //处理文字位置,注:文本的绘制是由此 rect 决定 var textX = style.x + __OP[0]; // 默认start == left if (style.textAlign == 'end' || style.textAlign == 'right') { textX -= width; } else if (style.textAlign == 'center') { textX -= (width / 2); } var textY; if (style.textBaseline == 'top') { // textY = style.y; textY = style.y + __OP[1]; } else if (style.textBaseline == 'bottom') { textY = (style.y + __OP[1]) - height; } else { // middle textY = (style.y + __OP[1]) - height / 2; } var isWidthChangeByMaxWidth = false; var widthBeforeChangeByMaxWidth; //处理 maxWidth if (style.maxWidth) { var maxWidth = parseInt(style.maxWidth); if (maxWidth < width) { widthBeforeChangeByMaxWidth = width; isWidthChangeByMaxWidth = true; width = maxWidth; } textX = style.x + __OP[0]; if (style.textAlign == 'end' || style.textAlign == 'right') { textX -= width; } else if (style.textAlign == 'center') { textX -= (width / 2); } } //处理斜体字 if (style.textFont) { var textFont = style.textFont; var textFontStr = textFont.toLowerCase() if (textFontStr.indexOf("italic") > -1) { if (isWidthChangeByMaxWidth === true) { width += (lineHeight / 3) * (width / widthBeforeChangeByMaxWidth); } else { width += lineHeight / 3; } } } var rect = { x: textX, y: textY, width: width, height: height }; return rect; } /** * @function LevelRenderer.Shape.SmicText.prototype.getTextBackground * @description 获取文本背景框范围 * * @param {Object} style - 样式。 * @param {boolean} redo - 是否强制重新计算 textBackground。 */ getTextBackground(style, redo) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; if ((!redo) && style.__textBackground) { return style.__textBackground; } //不旋转时矩形框 var rect = this.getRectNoRotation(style); //旋转中心点 var ox = style.x + __OP[0]; var oy = style.y + __OP[1]; //背景框 var background = []; if (style.textRotation && style.textRotation !== 0) { let textRotation = style.textRotation; let ltPoi = this.getRotatedLocation(rect.x, rect.y, ox, oy, textRotation); let rtPoi = this.getRotatedLocation(rect.x + rect.width, rect.y, ox, oy, textRotation); let rbPoi = this.getRotatedLocation(rect.x + rect.width, rect.y + rect.height, ox, oy, textRotation); let lbPoi = this.getRotatedLocation(rect.x, rect.y + rect.height, ox, oy, textRotation); background.push(ltPoi); background.push(rtPoi); background.push(rbPoi); background.push(lbPoi); } else { let ltPoi = [rect.x, rect.y]; let rtPoi = [rect.x + rect.width, rect.y]; let rbPoi = [rect.x + rect.width, rect.y + rect.height]; let lbPoi = [rect.x, rect.y + rect.height]; background.push(ltPoi); background.push(rtPoi); background.push(rbPoi); background.push(lbPoi); } style.__textBackground = background; return style.__textBackground; } /** * @function LevelRenderer.Shape.SmicText.prototype.getRotatedLocation * @description 获取一个点绕旋转中心顺时针旋转后的位置。(此方法用于屏幕坐标) * * @param {number} x - 旋转点横坐标。 * @param {number} y - 旋转点纵坐标。 * @param {number} rx - 旋转中心点横坐标。 * @param {number} ry - 旋转中心点纵坐标。 * @param {number} angle - 旋转角度(度)。 * @return {Array.} 旋转后的坐标位置,长度为 2 的一维数组,数组第一个元素表示 x 坐标,第二个元素表示 y 坐标。 */ getRotatedLocation(x, y, rx, ry, angle) { var loc = new Array(), x0, y0; y = -y; ry = -ry; angle = -angle;//顺时针旋转 x0 = (x - rx) * Math.cos((angle / 180) * Math.PI) - (y - ry) * Math.sin((angle / 180) * Math.PI) + rx; y0 = (x - rx) * Math.sin((angle / 180) * Math.PI) + (y - ry) * Math.cos((angle / 180) * Math.PI) + ry; loc[0] = x0; loc[1] = -y0; return loc; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicCircle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicCircle * @category Visualization Theme * @classdesc 圆形 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicCircle({ * style: { * x: 100, * y: 100, * r: 60, * brushType: "both", * color: "blue", * strokeColor: "red", * lineWidth: 3, * text: "Circle" * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 * */ class SmicCircle extends Shape_Shape { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicCircle.prototype.type * @description 图形类型。 */ this.type = 'smiccircle'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicCircle"; } /** * @function LevelRenderer.Shape.SmicCircle.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicCircle.prototype.buildPath * @description 创建图形路径。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var x = style.x + __OP[0]; // 圆心x var y = style.y + __OP[1]; // 圆心y ctx.moveTo(x + style.r, y); ctx.arc(x, y, style.r, 0, Math.PI * 2, true); return true; } /** * @function LevelRenderer.Shape.SmicCircle.prototype.getRect * @description 返回圆形包围盒矩形 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 * */ getRect(style) { if (style.__rect) { return style.__rect; } if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var x = style.x + __OP[0]; // 圆心x var y = style.y + __OP[1]; // 圆心y var r = style.r; // 圆r var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } style.__rect = { x: Math.round(x - r - lineWidth / 2), y: Math.round(y - r - lineWidth / 2), width: r * 2 + lineWidth, height: r * 2 + lineWidth }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicPolygon.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicPolygon * @category Visualization Theme * @classdesc 多边形。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicPolygon({ * style: { * // 100x100 的正方形 * pointList: [[0, 0], [100, 0], [100, 100], [0, 100]], * color: 'blue' * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 */ class SmicPolygon extends Shape_Shape { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicPolygon.prototype.type * @description 图形类型. */ this.type = 'smicpolygon'; /** * @member {Array} LevelRenderer.Shape.SmicPolygon.prototype._holePolygonPointList * @description 岛洞面多边形顶点数组(三维数组) * */ this.holePolygonPointLists = null; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicPolygon"; } /** * @function LevelRenderer.Shape.SmicPolygon.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; this.holePolygonPointLists = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicPolygon.prototype.brush * @description 笔触。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {boolean} isHighlight - 是否使用高亮属性。 * */ brush(ctx, isHighlight) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var style = this.style; if (isHighlight) { // 根据style扩展默认高亮样式 style = this.getHighlightStyle( style, this.highlightStyle || {} ); } ctx.save(); this.setContext(ctx, style); // 设置 transform this.setTransform(ctx); // 先 fill 再stroke var hasPath = false; if (style.brushType == 'fill' || style.brushType == 'both' || typeof style.brushType == 'undefined') { // 默认为fill ctx.beginPath(); if (style.lineType == 'dashed' || style.lineType == 'dotted' || style.lineType == 'dot' || style.lineType == 'dash' || style.lineType == 'dashdot' || style.lineType == 'longdash' || style.lineType == 'longdashdot' ) { // 特殊处理,虚线围不成path,实线再build一次 this.buildPath(ctx, { lineType: 'solid', lineWidth: style.lineWidth, pointList: style.pointList } ); } else { this.buildPath(ctx, style); hasPath = true; // 这个path能用 } ctx.closePath(); this.setCtxGlobalAlpha(ctx, "fill", style); ctx.fill(); this.setCtxGlobalAlpha(ctx, "reset", style); } if (style.lineWidth > 0 && (style.brushType == 'stroke' || style.brushType == 'both')) { if (!hasPath) { ctx.beginPath(); this.buildPath(ctx, style); } this.setCtxGlobalAlpha(ctx, "stroke", style); ctx.stroke(); this.setCtxGlobalAlpha(ctx, "reset", style); } this.drawText(ctx, style, this.style); //岛洞 var hpStyle = Util.cloneObject(style); if (hpStyle.pointList) { if (this.holePolygonPointLists && this.holePolygonPointLists.length > 0) { var holePLS = this.holePolygonPointLists; var holePLSen = holePLS.length; for (var i = 0; i < holePLSen; i++) { var holePL = holePLS[i]; //岛洞面 hpStyle.pointList = holePL; ctx.globalCompositeOperation = "destination-out"; // 先 fill 再stroke hasPath = false; if (hpStyle.brushType == 'fill' || hpStyle.brushType == 'both' || typeof hpStyle.brushType == 'undefined') { // 默认为fill ctx.beginPath(); if (hpStyle.lineType == 'dashed' || hpStyle.lineType == 'dotted' || hpStyle.lineType == 'dot' || hpStyle.lineType == 'dash' || hpStyle.lineType == 'dashdot' || hpStyle.lineType == 'longdash' || hpStyle.lineType == 'longdashdot' ) { // 特殊处理,虚线围不成path,实线再build一次 this.buildPath(ctx, { lineType: 'solid', lineWidth: hpStyle.lineWidth, pointList: hpStyle.pointList } ); } else { this.buildPath(ctx, hpStyle); hasPath = true; // 这个path能用 } ctx.closePath(); this.setCtxGlobalAlpha(ctx, "fill", hpStyle); ctx.fill(); this.setCtxGlobalAlpha(ctx, "reset", hpStyle); } if (hpStyle.lineWidth > 0 && (hpStyle.brushType == 'stroke' || hpStyle.brushType == 'both')) { if (!hasPath) { ctx.beginPath(); this.buildPath(ctx, hpStyle); } //如果描边,先回复 globalCompositeOperation 默认值再描边。 ctx.globalCompositeOperation = "source-over"; this.setCtxGlobalAlpha(ctx, "stroke", hpStyle); ctx.stroke(); this.setCtxGlobalAlpha(ctx, "reset", hpStyle); } else { ctx.globalCompositeOperation = "source-over"; } } } } ctx.restore(); return; } /** * @function LevelRenderer.Shape.SmicPolygon.prototype.buildPath * @description 创建多边形路径。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (style.showShadow) { ctx.shadowBlur = style.shadowBlur; ctx.shadowColor = style.shadowColor; ctx.shadowOffsetX = style.shadowOffsetX; ctx.shadowOffsetY = style.shadowOffsetY; } if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; // 虽然能重用 brokenLine,但底层图形基于性能考虑,重复代码减少调用吧 var pointList = style.pointList; if (pointList.length < 2) { // 少于2个点就不画了~ return; } if (style.smooth && style.smooth !== 'spline') { var controlPoints = SUtil_SUtil.SUtil_smoothBezier(pointList, style.smooth, true, style.smoothConstraint, __OP); ctx.moveTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); var cp1; var cp2; var p; var len = pointList.length; for (var i = 0; i < len; i++) { cp1 = controlPoints[i * 2]; cp2 = controlPoints[i * 2 + 1]; p = [pointList[(i + 1) % len][0] + __OP[0], pointList[(i + 1) % len][1] + __OP[1]]; ctx.bezierCurveTo( cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1] ); } } else { if (style.smooth === 'spline') { pointList = SUtil_SUtil.SUtil_smoothSpline(pointList, true, null, __OP); } if (!style.lineType || style.lineType == 'solid') { // 默认为实线 ctx.moveTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); for (let i = 1; i < pointList.length; i++) { ctx.lineTo(pointList[i][0] + __OP[0], pointList[i][1] + __OP[1]); } ctx.lineTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); } else if (style.lineType === 'dashed' || style.lineType === 'dotted' || style.lineType === 'dot' || style.lineType === 'dash' || style.lineType === 'longdash' ) { // SMIC-方法修改 - start let dashLengthForStyle = style._dashLength || (style.lineWidth || 1) * (style.lineType == 'dashed' ? 5 : 1); style._dashLength = dashLengthForStyle; let dashLength = (style.lineWidth || 1); let pattern1 = dashLength; let pattern2 = dashLength; //dashed if (style.lineType === 'dashed') { pattern1 *= 5; pattern2 *= 5; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; } } //dotted if (style.lineType === 'dotted') { if (style.lineCap && style.lineCap !== "butt") { pattern1 = 1; pattern2 += dashLength; } } //dot if (style.lineType === 'dot') { pattern2 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 = 1; pattern2 += dashLength; } } //dash if (style.lineType === 'dash') { pattern1 *= 4; pattern2 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; } } //longdash if (style.lineType === 'longdash') { pattern1 *= 8; pattern2 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; } } ctx.moveTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); for (let i = 1; i < pointList.length; i++) { SUtil_SUtil.SUtil_dashedLineTo( ctx, pointList[i - 1][0] + __OP[0], pointList[i - 1][1] + __OP[1], pointList[i][0] + __OP[0], pointList[i][1] + __OP[1], dashLength, [pattern1, pattern2] ); } SUtil_SUtil.SUtil_dashedLineTo( ctx, pointList[pointList.length - 1][0] + __OP[0], pointList[pointList.length - 1][1] + __OP[1], pointList[0][0] + __OP[0], pointList[0][1] + __OP[1], dashLength, [pattern1, pattern2] ); } else if (style.lineType === 'dashdot' || style.lineType === 'longdashdot' ) { let dashLengthForStyle = style._dashLength || (style.lineWidth || 1) * (style.lineType == 'dashed' ? 5 : 1); style._dashLength = dashLengthForStyle; let dashLength = (style.lineWidth || 1); let pattern1 = dashLength; let pattern2 = dashLength; let pattern3 = dashLength; let pattern4 = dashLength; //dashdot if (style.lineType === 'dashdot') { pattern1 *= 4; pattern2 *= 4; pattern4 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; pattern3 = 1; pattern4 += dashLength; } } //longdashdot if (style.lineType === 'longdashdot') { pattern1 *= 8; pattern2 *= 4; pattern4 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; pattern3 = 1; pattern4 += dashLength; } } ctx.moveTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); for (let i = 1; i < pointList.length; i++) { SUtil_SUtil.SUtil_dashedLineTo( ctx, pointList[i - 1][0] + __OP[0], pointList[i - 1][1] + __OP[1], pointList[i][0] + __OP[0], pointList[i][1] + __OP[1], dashLength, [pattern1, pattern2, pattern3, pattern4] ); } SUtil_SUtil.SUtil_dashedLineTo( ctx, pointList[pointList.length - 1][0] + __OP[0], pointList[pointList.length - 1][1] + __OP[1], pointList[0][0] + __OP[0], pointList[0][1] + __OP[1], dashLength, [pattern1, pattern2, pattern3, pattern4] ); } } return; } /** * @function LevelRenderer.Shape.SmicPolygon.prototype.getRect * @description 计算返回多边形包围盒矩阵。该包围盒是直接从四个控制点计算,并非最小包围盒。 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 * */ getRect(style, refOriginalPosition) { var __OP; if (!refOriginalPosition) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } __OP = this.refOriginalPosition; } else { __OP = refOriginalPosition; } if (style.__rect) { return style.__rect; } var minX = Number.MAX_VALUE; var maxX = Number.MIN_VALUE; var minY = Number.MAX_VALUE; var maxY = Number.MIN_VALUE; var pointList = style.pointList; for (var i = 0, l = pointList.length; i < l; i++) { if (pointList[i][0] + __OP[0] < minX) { minX = pointList[i][0] + __OP[0]; } if (pointList[i][0] + __OP[0] > maxX) { maxX = pointList[i][0] + __OP[0]; } if (pointList[i][1] + __OP[1] < minY) { minY = pointList[i][1] + __OP[1]; } if (pointList[i][1] + __OP[1] > maxY) { maxY = pointList[i][1] + __OP[1]; } } var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } style.__rect = { x: Math.round(minX - lineWidth / 2), y: Math.round(minY - lineWidth / 2), width: maxX - minX + lineWidth, height: maxY - minY + lineWidth }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicBrokenLine.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicBrokenLine * @category Visualization Theme * @classdesc 折线(ic)。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicBrokenLine({ * style: { * pointList: [[0, 0], [100, 100], [100, 0]], * smooth: 'bezier', * strokeColor: 'purple' * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 * */ class SmicBrokenLine extends Shape_Shape { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicBrokenLine.prototype.brushTypeOnly * @description 线条只能描边。 */ this.brushTypeOnly = 'stroke'; /** * @member {string} LevelRenderer.Shape.SmicBrokenLine.prototype.textPosition * @description 文本位置。 */ this.textPosition = 'end'; /** * @member {string} LevelRenderer.Shape.SmicBrokenLine.prototype.type * @description 图形类型. */ this.type = 'smicbroken-line'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicBrokenLine"; } /** * @function LevelRenderer.Shape.SmicBrokenLine.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.brushTypeOnly = null; this.textPosition = null; this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicBrokenLine.prototype.buildPath * @description 创建折线路径。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var pointList = style.pointList; if (pointList.length < 2) { // 少于2个点就不画了~ return; } var len = Math.min(style.pointList.length, Math.round(style.pointListLength || style.pointList.length)); if (style.smooth && style.smooth !== 'spline') { var controlPoints = SUtil_SUtil.SUtil_smoothBezier(pointList, style.smooth, false, style.smoothConstraint, __OP); ctx.moveTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); var cp1; var cp2; var p; for (let i = 0; i < len - 1; i++) { cp1 = controlPoints[i * 2]; cp2 = controlPoints[i * 2 + 1]; p = [pointList[i + 1][0] + __OP[0], pointList[i + 1][1] + __OP[1]]; ctx.bezierCurveTo( cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1] ); } } else { if (style.smooth === 'spline') { pointList = SUtil_SUtil.SUtil_smoothSpline(pointList, null, null, __OP); len = pointList.length; } if (!style.lineType || style.lineType === 'solid') { // 默认为实线 ctx.moveTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); for (let i = 1; i < len; i++) { ctx.lineTo(pointList[i][0] + __OP[0], pointList[i][1] + __OP[1]); } } else if (style.lineType === 'dashed' || style.lineType === 'dotted' || style.lineType === 'dot' || style.lineType === 'dash' || style.lineType === 'longdash' ) { let dashLength = (style.lineWidth || 1); let pattern1 = dashLength; let pattern2 = dashLength; //dashed if (style.lineType === 'dashed') { pattern1 *= 5; pattern2 *= 5; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; } } //dotted if (style.lineType === 'dotted') { if (style.lineCap && style.lineCap !== "butt") { pattern1 = 1; pattern2 += dashLength; } } //dot if (style.lineType === 'dot') { pattern2 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 = 1; pattern2 += dashLength; } } //dash if (style.lineType === 'dash') { pattern1 *= 4; pattern2 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; } } //longdash if (style.lineType === 'longdash') { pattern1 *= 8; pattern2 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; } } ctx.moveTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); for (var i = 1; i < len; i++) { SUtil_SUtil.SUtil_dashedLineTo( ctx, pointList[i - 1][0] + __OP[0], pointList[i - 1][1] + __OP[1], pointList[i][0] + __OP[0], pointList[i][1] + __OP[1], dashLength, [pattern1, pattern2] ); } } else if (style.lineType === 'dashdot' || style.lineType === 'longdashdot' ) { let dashLength = (style.lineWidth || 1); let pattern1 = dashLength; let pattern2 = dashLength; let pattern3 = dashLength; let pattern4 = dashLength; //dashdot if (style.lineType === 'dashdot') { pattern1 *= 4; pattern2 *= 4; pattern4 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; pattern3 = 1; pattern4 += dashLength; } } //longdashdot if (style.lineType === 'longdashdot') { pattern1 *= 8; pattern2 *= 4; pattern4 *= 4; if (style.lineCap && style.lineCap !== "butt") { pattern1 -= dashLength; pattern2 += dashLength; pattern3 = 1; pattern4 += dashLength; } } dashLength = (style.lineWidth || 1) * (style.lineType === 'dashed' ? 5 : 1); ctx.moveTo(pointList[0][0] + __OP[0], pointList[0][1] + __OP[1]); for (let i = 1; i < len; i++) { SUtil_SUtil.SUtil_dashedLineTo( ctx, pointList[i - 1][0] + __OP[0], pointList[i - 1][1] + __OP[1], pointList[i][0] + __OP[0], pointList[i][1] + __OP[1], dashLength, [pattern1, pattern2, pattern3, pattern4] ); } } } return; } /** * @function LevelRenderer.Shape.SmicBrokenLine.prototype.getRect * @description 计算返回折线包围盒矩形。该包围盒是直接从四个控制点计算,并非最小包围盒。 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 */ getRect(style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; return SmicPolygon.prototype.getRect.apply(this, [style, __OP]); } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicImage.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicImage * @category Visualization Theme * @classdesc 图片绘制。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicImage({ * style: { * image: 'test.jpg', * x: 100, * y: 100 * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 * */ class SmicImage extends Shape_Shape { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicImage.prototype.type * @description 图形类型。 */ this.type = 'smicimage'; /** * @member {string} LevelRenderer.Shape.SmicImage.prototype._imageCache * @description 图片缓存。 */ this._imageCache = {}; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicImage"; } /** * @function LevelRenderer.Shape.SmicImage.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; this._imageCache = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicImage.prototype.buildPath * @description 创建图片。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ brush(ctx, isHighlight, refresh) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var style = this.style || {}; if (isHighlight) { // 根据style扩展默认高亮样式 style = this.getHighlightStyle( style, this.highlightStyle || {} ); } var image = style.image; var me = this; if (typeof(image) === 'string') { var src = image; if (this._imageCache[src]) { image = this._imageCache[src]; } else { image = new Image(); image.onload = function () { image.onload = null; clearTimeout(SmicImage._refreshTimeout); SmicImage._needsRefresh.push(me); // 防止因为缓存短时间内触发多次onload事件 SmicImage._refreshTimeout = setTimeout(function () { refresh && refresh(SmicImage._needsRefresh); // 清空 needsRefresh SmicImage._needsRefresh = []; }, 10); }; image.src = src; this._imageCache[src] = image; } } if (image) { // 图片已经加载完成 if (image.nodeName.toUpperCase() == 'IMG') { if (window.ActiveXObject) { if (image.readyState != 'complete') { return; } } else { if (!image.complete) { return; } } } // Else is canvas var width = style.width || image.width; var height = style.height || image.height; var x = style.x + __OP[0]; var y = style.y + __OP[1]; // 图片加载失败 if (!image.width || !image.height) { return; } ctx.save(); this.doClip(ctx); this.setContext(ctx, style); // 设置transform this.setTransform(ctx); if (style.sWidth && style.sHeight) { let sx = (style.sx + __OP[0]) || 0; let sy = (style.sy + __OP[1]) || 0; ctx.drawImage( image, sx, sy, style.sWidth, style.sHeight, x, y, width, height ); } else if (style.sx && style.sy) { let sx = style.sx + __OP[0]; let sy = style.sy + __OP[1]; var sWidth = width - sx; var sHeight = height - sy; ctx.drawImage( image, sx, sy, sWidth, sHeight, x, y, width, height ); } else { ctx.drawImage(image, x, y, width, height); } // 如果没设置宽和高的话自动根据图片宽高设置 if (!style.width) { style.width = width; } if (!style.height) { style.height = height; } if (!this.style.width) { this.style.width = width; } if (!this.style.height) { this.style.height = height; } this.drawText(ctx, style, this.style); ctx.restore(); } } /** * @function LevelRenderer.Shape.SmicImage.prototype.getRect * @description 计算返回图片的包围盒矩形。 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 */ getRect(style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; return { x: style.x + __OP[0], y: style.y + __OP[1], width: style.width, height: style.height }; } /** * @function LevelRenderer.Shape.SmicImage.prototype.clearCache * @description 清除图片缓存。 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 * */ clearCache() { this._imageCache = {}; } } SmicImage._needsRefresh = []; SmicImage._refreshTimeout = null; ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicRectangle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicRectangle * @category Visualization Theme * @classdesc 矩形。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicRectangle({ * style: { * x: 0, * y: 0, * width: 100, * height: 100, * radius: 20 * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 */ class SmicRectangle extends Shape_Shape { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicRectangle.prototype.type * @description 图形类型. */ this.type = 'smicrectangle'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicRectangle"; } /** * @function LevelRenderer.Shape.SmicRectangle.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * APIMethod: _buildRadiusPath * 创建矩形的圆角路径。 * * Parameters: * ctx - {CanvasRenderingContext2D} Context2D 上下文。 * style - {Object} style。 * */ _buildRadiusPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4 // r缩写为1 相当于 [1, 1, 1, 1] // r缩写为[1] 相当于 [1, 1, 1, 1] // r缩写为[1, 2] 相当于 [1, 2, 1, 2] // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2] var x = style.x + __OP[0]; var y = style.y + __OP[1]; var width = style.width; var height = style.height; var r = style.radius; var r1; var r2; var r3; var r4; if (typeof r === 'number') { r1 = r2 = r3 = r4 = r; } else if (r instanceof Array) { if (r.length === 1) { r1 = r2 = r3 = r4 = r[0]; } else if (r.length === 2) { r1 = r3 = r[0]; r2 = r4 = r[1]; } else if (r.length === 3) { r1 = r[0]; r2 = r4 = r[1]; r3 = r[2]; } else { r1 = r[0]; r2 = r[1]; r3 = r[2]; r4 = r[3]; } } else { r1 = r2 = r3 = r4 = 0; } var total; if (r1 + r2 > width) { total = r1 + r2; r1 *= width / total; r2 *= width / total; } if (r3 + r4 > width) { total = r3 + r4; r3 *= width / total; r4 *= width / total; } if (r2 + r3 > height) { total = r2 + r3; r2 *= height / total; r3 *= height / total; } if (r1 + r4 > height) { total = r1 + r4; r1 *= height / total; r4 *= height / total; } ctx.moveTo(x + r1, y); ctx.lineTo(x + width - r2, y); r2 !== 0 && ctx.quadraticCurveTo( x + width, y, x + width, y + r2 ); ctx.lineTo(x + width, y + height - r3); r3 !== 0 && ctx.quadraticCurveTo( x + width, y + height, x + width - r3, y + height ); ctx.lineTo(x + r4, y + height); r4 !== 0 && ctx.quadraticCurveTo( x, y + height, x, y + height - r4 ); ctx.lineTo(x, y + r1); r1 !== 0 && ctx.quadraticCurveTo(x, y, x + r1, y); } /** * @function LevelRenderer.Shape.SmicRectangle.prototype.buildPath * @description 创建矩形路径。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; if (!style.radius) { ctx.moveTo(style.x + __OP[0], style.y + __OP[1]); ctx.lineTo((style.x + __OP[0]) + style.width, (style.y + __OP[1])); ctx.lineTo((style.x + __OP[0]) + style.width, (style.y + __OP[1]) + style.height); ctx.lineTo((style.x + __OP[0]), (style.y + __OP[1]) + style.height); ctx.lineTo(style.x + __OP[0], style.y + __OP[1]); // ctx.rect(style.x, style.y, style.width, style.height); } else { this._buildRadiusPath(ctx, style); } ctx.closePath(); return; } /** * @function LevelRenderer.Shape.SmicRectangle.prototype.getRect * @description 计算返回矩形包围盒矩阵。该包围盒是直接从四个控制点计算,并非最小包围盒。 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 */ getRect(style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; if (style.__rect) { return style.__rect; } var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } style.__rect = { x: Math.round((style.x + __OP[0]) - lineWidth / 2), y: Math.round((style.y + __OP[1]) - lineWidth / 2), width: style.width + lineWidth, height: style.height + lineWidth }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicSector.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicSector * @category Visualization Theme * @classdesc 扇形。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicSector({ * style: { * x: 100, * y: 100, * r: 60, * r0: 30, * startAngle: 0, * endEngle: 180 * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 * */ class SmicSector extends Shape_Shape { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicSector.protptype.type * @description 图形类型。 */ this.type = 'smicsector'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicSector"; } /** * @function LevelRenderer.Shape.SmicSector.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicSector.prototype.buildPath * @description 创建扇形路径。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var x = style.x + __OP[0]; // 圆心x var y = style.y + __OP[1]; // 圆心y var r0 = style.r0 || 0; // 形内半径[0,r) var r = style.r; // 扇形外半径(0,r] var startAngle = style.startAngle; // 起始角度[0,360) var endAngle = style.endAngle; // 结束角度(0,360] var clockWise = style.clockWise || false; startAngle = SUtil_SUtil.Util_math.degreeToRadian(startAngle); endAngle = SUtil_SUtil.Util_math.degreeToRadian(endAngle); if (!clockWise) { // 扇形默认是逆时针方向,Y轴向上 // 这个跟arc的标准不一样,为了兼容echarts startAngle = -startAngle; endAngle = -endAngle; } var unitX = SUtil_SUtil.Util_math.cos(startAngle); var unitY = SUtil_SUtil.Util_math.sin(startAngle); ctx.moveTo( unitX * r0 + x, unitY * r0 + y ); ctx.lineTo( unitX * r + x, unitY * r + y ); ctx.arc(x, y, r, startAngle, endAngle, !clockWise); ctx.lineTo( SUtil_SUtil.Util_math.cos(endAngle) * r0 + x, SUtil_SUtil.Util_math.sin(endAngle) * r0 + y ); if (r0 !== 0) { ctx.arc(x, y, r0, endAngle, startAngle, clockWise); } ctx.closePath(); return; } /** * @function LevelRenderer.Shape.SmicSector.prototype.getRect * @description 返回扇形包围盒矩形 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 * */ getRect(style) { if (style.__rect) { return style.__rect; } if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var min0 = SUtil_SUtil.Util_vector.create(); var min1 = SUtil_SUtil.Util_vector.create(); var max0 = SUtil_SUtil.Util_vector.create(); var max1 = SUtil_SUtil.Util_vector.create(); var x = style.x + __OP[0]; // 圆心x var y = style.y + __OP[1]; // 圆心y var r0 = style.r0 || 0; // 形内半径[0,r) var r = style.r; // 扇形外半径(0,r] var startAngle = SUtil_SUtil.Util_math.degreeToRadian(style.startAngle); var endAngle = SUtil_SUtil.Util_math.degreeToRadian(style.endAngle); var clockWise = style.clockWise; if (!clockWise) { startAngle = -startAngle; endAngle = -endAngle; } if (r0 > 1) { SUtil_SUtil.Util_computeBoundingBox.arc( x, y, r0, startAngle, endAngle, !clockWise, min0, max0 ); } else { min0[0] = max0[0] = x; min0[1] = max0[1] = y; } SUtil_SUtil.Util_computeBoundingBox.arc( x, y, r, startAngle, endAngle, !clockWise, min1, max1 ); SUtil_SUtil.Util_vector.min(min0, min0, min1); SUtil_SUtil.Util_vector.max(max0, max0, max1); style.__rect = { x: min0[0], y: min0[1], width: max0[0] - min0[0], height: max0[1] - min0[1] }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/ShapeFactory.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureShapeFactory * @aliasclass Feature.ShapeFactory * @deprecatedclass SuperMap.Feature.ShapeFactory * @category Visualization Theme * @classdesc 图形工厂类。 * 目前支持创建的图形有:
* 用于统计专题图:
* 点 - 参数对象 <{@link ShapeParametersPoint}>
* 线 - 参数对象 <{@link ShapeParametersLine}>
* 面 - 参数对象 <{@link ShapeParametersPolygon}>
* 矩形 - 参数对象 <{@link ShapeParametersPolygon}>
* 扇形 - 参数对象 <{@link ShapeParametersSector}>
* 标签 - 参数对象 <{@link ShapeParametersLabel}>
* 图片 - 参数对象 <{@link ShapeParametersImage}>
* 用于符号专题图:
* 圆形 - 参数对象:<{@link ShapeParametersCircle}> * @param {Object} [shapeParameters] - 图形参数对象,<{@link ShapeParameters}> 子类对象。 * @usage */ class ShapeFactory { constructor(shapeParameters) { /** * @member {Object} FeatureShapeFactory.prototype.shapeParameters * @description 图形参数对象,<{@link ShapeParameters}> 子类对象。必设参数,默认值 null。 */ this.shapeParameters = shapeParameters; this.CLASS_NAME = "SuperMap.Feature.ShapeFactory"; } /** * @function FeatureShapeFactory.prototype.destroy * @description 销毁图形工厂类对象。 */ destroy() { this.shapeParameters = null; } /** * @function FeatureShapeFactory.prototype.createShape * @description 创建一个图形。具体图形由 shapeParameters 决定。 * @param {Object} shapeParameters - 图形参数对象,<{@link ShapeParameters}> 子类对象。 * 此参数可选,如果使用此参数(不为 null),shapeParameters 属性值将被修改为参数的值,然后再使用 shapeParameters 属性值创建图形; * 如果不使用此参数,createShape 方法将直接使用 shapeParameters 属性创建图形。 * @returns {Object} 图形对象(或 null - 图形创建失败)。 */ createShape(shapeParameters) { if (shapeParameters) { this.shapeParameters = shapeParameters; } if (!this.shapeParameters) { return null; } var sps = this.shapeParameters; if (sps instanceof Point_Point) { // 点 //设置style let style = new Object(); style["x"] = sps.x; style["y"] = sps.y; style["r"] = sps.r; style = Util.copyAttributesWithClip(style, sps.style, ['x', 'y']); //创建图形 let shape = new SmicPoint(); shape.style = ShapeFactory.transformStyle(style); shape.highlightStyle = ShapeFactory.transformStyle(sps.highlightStyle); Util.copyAttributesWithClip(shape, sps, ['x', 'y', 'style', 'highlightStyle']); return shape; } else if (sps instanceof Line_Line) { // 线 //检查参数 pointList 是否存在 if (!sps.pointList) { return null; } // 设置style let style = new Object(); style["pointList"] = sps.pointList; style = Util.copyAttributesWithClip(style, sps.style, ['pointList']); // 创建图形 let shape = new SmicBrokenLine(); shape.style = ShapeFactory.transformStyle(style); shape.highlightStyle = ShapeFactory.transformStyle(sps.highlightStyle); Util.copyAttributesWithClip(shape, sps, ['pointList', 'style', 'highlightStyle']); return shape; } else if (sps instanceof Polygon_Polygon) { // 面 //检查参数 pointList 是否存在 if (!sps.pointList) { return null; } //设置style let style = new Object(); style["pointList"] = sps.pointList; style = Util.copyAttributesWithClip(style, sps.style, ['pointList']); //创建图形 let shape = new SmicPolygon(); shape.style = ShapeFactory.transformStyle(style); shape.highlightStyle = ShapeFactory.transformStyle(sps.highlightStyle); Util.copyAttributesWithClip(shape, sps, ['pointList', 'style', "highlightStyle"]); return shape; } else if (sps instanceof Rectangle_Rectangle) { // 矩形 //检查参数 pointList 是否存在 if (!sps.x && !sps.y & !sps.width & !sps.height) { return null; } //设置style let style = new Object(); style["x"] = sps.x; style["y"] = sps.y; style["width"] = sps.width; style["height"] = sps.height; style = Util.copyAttributesWithClip(style, sps.style, ['x', 'y', 'width', 'height']); //创建图形 let shape = new SmicRectangle(); shape.style = ShapeFactory.transformStyle(style); shape.highlightStyle = ShapeFactory.transformStyle(sps.highlightStyle); Util.copyAttributesWithClip(shape, sps, ['x', 'y', 'width', 'height', 'style', 'highlightStyle']); return shape; } else if (sps instanceof Sector) { // 扇形 //设置style let style = new Object(); style["x"] = sps.x; style["y"] = sps.y; style["r"] = sps.r; style["startAngle"] = sps.startAngle; style["endAngle"] = sps.endAngle; if (sps["r0"]) { style["r0"] = sps.r0 } if (sps["clockWise"]) { style["clockWise"] = sps.clockWise } style = Util.copyAttributesWithClip(style, sps.style, ['x', 'y', 'r', 'startAngle', 'endAngle', 'r0', 'endAngle']); //创建图形 let shape = new SmicSector(); shape.style = ShapeFactory.transformStyle(style); shape.highlightStyle = ShapeFactory.transformStyle(sps.highlightStyle); Util.copyAttributesWithClip(shape, sps, ['x', 'y', 'r', 'startAngle', 'endAngle', 'r0', 'endAngle', 'style', 'highlightStyle']); return shape; } else if (sps instanceof Label) { // 标签 //设置style let style = new Object(); style["x"] = sps.x; style["y"] = sps.y; style["text"] = sps.text; style = Util.copyAttributesWithClip(style, sps.style, ['x', 'y', 'text']); //创建图形 let shape = new SmicText(); shape.style = ShapeFactory.transformStyle(style); shape.highlightStyle = ShapeFactory.transformStyle(sps.highlightStyle); Util.copyAttributesWithClip(shape, sps, ['x', 'y', 'text', 'style', 'highlightStyle']); return shape; } else if (sps instanceof Image_Image) { // 图片 //设置style let style = new Object(); style["x"] = sps.x; style["y"] = sps.y; if (sps["image"]) { style["image"] = sps.image; } if (sps["width"]) { style["width"] = sps.width; } if (sps["height"]) { style["height"] = sps.height; } if (sps["sx"]) { style["sx"] = sps.sx; } if (sps["sy"]) { style["sy"] = sps.sy; } if (sps["sWidth"]) { style["sWidth"] = sps.sWidth } if (sps["sHeight"]) { style["sHeight"] = sps.sHeight } style = Util.copyAttributesWithClip(style, sps.style, ['x', 'y', 'image', 'width', 'height', 'sx', 'sy', 'sWidth', 'sHeight']); //创建图形 let shape = new SmicImage(); shape.style = ShapeFactory.transformStyle(style); shape.highlightStyle = ShapeFactory.transformStyle(sps.highlightStyle); Util.copyAttributesWithClip(shape, sps, ['x', 'y', 'image', 'width', 'height', 'style', 'highlightStyle']); return shape; } else if (sps instanceof Circle_Circle) { //圆形 用于符号专题图 //设置stytle let style = new Object(); style["x"] = sps.x; style["r"] = sps.r; style["y"] = sps.y; style = Util.copyAttributesWithClip(style, sps.style, ['x', 'y', 'r']); //创建图形 let shape = new SmicCircle(); shape.style = ShapeFactory.transformStyle(style); shape.highlightStyle = ShapeFactory.transformStyle(sps.highlightStyle); Util.copyAttributesWithClip(shape, sps, ['x', 'y', 'r', 'style', 'highlightStyle', 'lineWidth', 'text', 'textPosition']); return shape; } return null } /** * @function FeatureShapeFactory.prototype.transformStyle * @description 将用户 feature.style (类 Svg style 标准) 的样式,转换为 levelRenderer 的样式标准(类 CSS-Canvas 样式) * @param {Object} style - 用户 style。 * @returns {Object} 符合 levelRenderer 的 style。 */ static transformStyle(style) { var newStyle = {}; //字体 ["font-style", "font-variant", "font-weight", "font-size / line-height", "font-family"]; var fontStr = ["normal", "normal", "normal", "12", "arial,sans-serif"]; //画笔类型 ["fill", "stroke"]; var brushType = [true, false]; for (var ss in style) { switch (ss) { case "fill": brushType[0] = style[ss]; break; case "fillColor": newStyle["color"] = style[ss]; break; case "stroke": brushType[1] = style[ss]; break; case "strokeWidth": newStyle["lineWidth"] = style[ss]; break; case "strokeLinecap": newStyle["lineCap"] = style[ss]; break; case "strokeLineJoin": newStyle["lineJoin"] = style[ss]; break; case "strokeDashstyle": newStyle["lineType"] = style[ss]; break; case "pointRadius": newStyle["r"] = style[ss]; break; case "label": newStyle["text"] = style[ss]; break; case "labelRect": newStyle["labelRect"] = style[ss]; break; case "fontColor": newStyle["textColor"] = style[ss]; break; case "fontStyle": fontStr[0] = style[ss]; break; case "fontVariant": fontStr[1] = style[ss]; break; case "fontWeight": fontStr[2] = style[ss]; break; case "fontSize": var unit = ""; if (style[ss] && style[ss].toString().indexOf("px") < 0) { unit = "px"; } fontStr[3] = style[ss] + unit; break; case "fontFamily": fontStr[4] = style[ss]; break; case "fontOpacity": newStyle["opacity"] = style[ss]; break; case "labelPosition": newStyle["textPosition"] = style[ss]; break; case "labelAlign": newStyle["textAlign"] = style[ss]; break; case "labelBaseline": newStyle["textBaseline"] = style[ss]; break; case "labelRotation": newStyle["textRotation"] = style[ss]; break; default: newStyle[ss] = style[ss]; break; } } //拼接字体字符串 newStyle["textFont"] = fontStr.join(" "); //画笔类型 if (brushType[0] === true && brushType[1] === false) { newStyle["brushType"] = "fill"; } else if (brushType[0] === false && brushType[1] === true) { newStyle["brushType"] = "stroke"; } else if (brushType[0] === true && brushType[1] === true) { newStyle["brushType"] = "both"; } else { newStyle["brushType"] = "fill"; } //默认线宽 1 if (newStyle["lineWidth"] == null) { newStyle["lineWidth"] = 1; } return newStyle; } /** * @function FeatureShapeFactory.prototype.Background * @description 创建一个矩形背景框图形对象。 * @param {FeatureShapeFactory} shapeFactory - 图形工厂对象。 * @param {Array.} box - 框区域,长度为 4 的一维数组,像素坐标,[left, bottom, right, top]。 * @param {Object} setting - 图表配置参数。本函数中图形配置对象 setting 可设属性: * @param {Object} setting.backgroundStyle - 背景样式,此样式对象对象可设属性:。 * @param {Array.} [setting.backgroundRadius=[0,0,0,0]] - 背景框矩形圆角半径,可以用数组分别指定四个角的圆角半径,设:左上、右上、右下、左下角的半径依次为 r1、r2、r3、r4,则 backgroundRadius 为 [r1、r2、r3、r4 ]。 * @returns {Object} 背景框图形,一个可视化图形(矩形)对象。 */ static Background(shapeFactory, box, setting) { var sets = setting ? setting : {}; // 背景框图形参数对象 var bgSP = new Rectangle_Rectangle(box[0], box[3], Math.abs(box[2] - box[0]), Math.abs(box[3] - box[1])); // 默认样式 bgSP.style = { fillColor: "#f3f3f3" }; // 设置用户 style if (sets.backgroundStyle) { Util.copyAttributesWithClip(bgSP.style, sets.backgroundStyle); } // 设置背景框圆角参数 if (sets.backgroundRadius) { bgSP.style["radius"] = sets.backgroundRadius; } // 禁止背景框响应事件 bgSP.clickable = false; bgSP.hoverable = false; return shapeFactory.createShape(bgSP); } /** * @function FeatureShapeFactory.prototype.GraphAxis * @description 创建一个统计图表坐标轴图形对象组。 * @param {FeatureShapeFactory} shapeFactory - 图形工厂对象。 * @param {Array.} dataViewBox - 统计图表模型的数据视图框,长度为 4 的一维数组,像素坐标,[left, bottom, right, top]。 * @param {Object} setting - 图表配置参数。 * @param {Object} setting.axisStyle - 坐标轴样式,此样式对象对象可设属性:。 * @param {boolean} [setting.axisUseArrow=false] - 坐标轴是否使用箭头。 * @param {number} [setting.axisYTick=0] - y 轴刻度数量,0表示不使用箭头。 * @param {Array.} setting.axisYLabels - y 轴上的标签组内容,标签顺序沿着数据视图框左面条边自上而下,等距排布。例如:["1000", "750", "500", "250", "0"]。 * @param {Object} setting.axisYLabelsStyle - y 轴上的标签组样式,此样式对象对象可设属性:。 * @param {Array.} [setting.axisYLabelsOffset=[0,0]] - y 轴上的标签组偏移量。长度为 2 的数组,数组第一项表示 y 轴标签组横向上的偏移量,向左为正,默认值:0;数组第二项表示 y 轴标签组纵向上的偏移量,向下为正,默认值:0。 * @param {Array.} setting.axisXLabels - x 轴上的标签组内容,标签顺序沿着数据视图框下面条边自左向右排布,例如:["92年", "95年", "99年"]。 * 标签排布规则:当标签数量与 xShapeInfo 中的属性 xPositions 数量相同(即标签个数与数据个数相等时), 按照 xPositions 提供的位置在水平方向上排布标签,否则沿数据视图框下面条边等距排布标签。 * @param {Object} setting.axisXLabelsStyle - x 轴上的标签组样式,此样式对象对象可设属性:。 * @param {Array.} [setting.axisXLabelsOffset=[0,0]] - x 轴上的标签组偏移量。长度为 2 的数组,数组第一项表示 x 轴标签组横向上的偏移量,向左为正,默认值:0;数组第二项表示 x 轴标签组纵向上的偏移量,向下为正,默认值:0。 * @param {boolean} setting.useXReferenceLine - 是否使用水平参考线,如果为 true,在 axisYTick 大于 0 时有效,水平参考线是 y 轴刻度在数据视图框里的延伸。 * @param {Object} setting.xReferenceLineStyle - 水平参考线样式,此样式对象对象可设属性:。 * @param {number} [setting.axis3DParameter=0] - 3D 坐标轴参数,此属性值在大于等于 15 时有效。 * @param {Object} xShapeInfo - X 方向上的图形信息对象,包含两个属性。 * @param {Array.} xShapeInfo.xPositions - 图形在 x 轴方向上的像素坐标值,是一个一维数组,如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。 * @param {number} xShapeInfo.width - 图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 * @returns {Array.} 统计图表坐标轴图形对象数组。 */ static GraphAxis(shapeFactory, dataViewBox, setting, xShapeInfo) { var dvb = dataViewBox; var sets = setting ? setting : {}; // 参考线图形对象组 var refLines = []; //坐标轴箭头对象组 var arrows = []; // 是否使用参水平考线,默认不使用 var isAddRefLine = sets.useXReferenceLine ? sets.useXReferenceLine : false; // y 轴上的刻度 var axisytick = (sets.axisYTick && !isNaN(sets.axisYTick)) ? sets.axisYTick : 0; // 坐标轴节点数组 var pois = []; //z 轴箭头数组 var zArrowPois = []; // x,y 轴主干节点数组 var xMainPois = []; if (axisytick == 0) { xMainPois.push([dvb[0], dvb[3] - 5]); xMainPois.push([dvb[0], dvb[1]]); // 3D 坐标轴 第三象限平分线 if (sets.axis3DParameter && !isNaN(sets.axis3DParameter) && sets.axis3DParameter >= 15) { let axis3DParameter = parseInt(sets.axis3DParameter); let axis3DPoi = [dvb[0] - axis3DParameter, dvb[1] + axis3DParameter]; // 添加 3D 轴节点 if (sets.axisUseArrow) { // 添加 3D 轴箭头节点坐标 //箭头坐标 zArrowPois.push([axis3DPoi[0] + 1.5, axis3DPoi[1] - 7.5]); zArrowPois.push([axis3DPoi[0] - 1, axis3DPoi[1] + 1]); zArrowPois.push([axis3DPoi[0] + 7.5, axis3DPoi[1] - 1.5]); //3D轴 xMainPois.push([axis3DPoi[0], axis3DPoi[1]]); } else { xMainPois.push([axis3DPoi[0], axis3DPoi[1]]); } xMainPois.push([dvb[0], dvb[1]]); } xMainPois.push([dvb[2] + 5, dvb[1]]); } else { // 单位刻度长度 var unitTick = Math.abs(dvb[1] - dvb[3]) / axisytick; // 刻度 y 坐标 var thckY = dvb[3]; xMainPois.push([dvb[0], thckY - 5]); for (var i = 0; i < axisytick; i++) { xMainPois.push([dvb[0], thckY]); xMainPois.push([dvb[0] - 5, thckY]); xMainPois.push([dvb[0], thckY]); // 参考线 if (isAddRefLine) { // 参考线参数对象 var refLineSP = new Line_Line([ [dvb[0], thckY], [dvb[2], thckY] ]); // 参考线默认样式对象 refLineSP.style = { strokeColor: "#cfcfcf", strokeLinecap: "butt", strokeLineJoin: "round", strokeWidth: 1 }; // 禁止事件 refLineSP.clickable = false; refLineSP.hoverable = false; // 用户style if (sets.xReferenceLineStyle) { Util.copyAttributesWithClip(refLineSP.style, sets.xReferenceLineStyle); } // 生成参考线图形对象 refLines.push(shapeFactory.createShape(refLineSP)) } // y 刻度增量 thckY += unitTick; } xMainPois.push([dvb[0], dvb[1]]); // 3D 坐标轴 第三象限平分线 if (sets.axis3DParameter && !isNaN(sets.axis3DParameter) && sets.axis3DParameter >= 15) { let axis3DParameter = parseInt(sets.axis3DParameter); let axis3DPoi = [dvb[0] - axis3DParameter, dvb[1] + axis3DParameter]; /* // 箭头计算过程 var axis3DPoiRef = [axis3DPoi[0] + 7, axis3DPoi[1] - 7]; // 7 是 10 为斜边 cos(45度)时邻边的值 var axis3DPoiLT = [axis3DPoiRef[0] - 4, axis3DPoiRef[1] - 4]; var axis3DPoiRB = [axis3DPoiRef[0] + 4, axis3DPoiRef[1] + 4]; if(sets.axisUseArrow){ xMainPois.push([axis3DPoi[0], axis3DPoi[1]]); xMainPois.push([axis3DPoiLT[0], axis3DPoiLT[1]]); xMainPois.push([axis3DPoi[0], axis3DPoi[1]]); xMainPois.push([axis3DPoiRB[0], axis3DPoiRB[1]]); xMainPois.push([axis3DPoi[0], axis3DPoi[1]]); } else{ xMainPois.push([axis3DPoi[0], axis3DPoi[1]]); } */ // 添加 3D 轴节点 if (sets.axisUseArrow) { // 添加 3D 轴和箭头坐标 //箭头坐标 zArrowPois.push([axis3DPoi[0] + 1.5, axis3DPoi[1] - 7.5]); zArrowPois.push([axis3DPoi[0] - 1, axis3DPoi[1] + 1]); zArrowPois.push([axis3DPoi[0] + 7.5, axis3DPoi[1] - 1.5]); //3D轴 xMainPois.push([axis3DPoi[0], axis3DPoi[1]]); } else { xMainPois.push([axis3DPoi[0], axis3DPoi[1]]); } xMainPois.push([dvb[0], dvb[1]]); } xMainPois.push([dvb[2] + 5, dvb[1]]); } // 坐标轴箭头 if (sets.axisUseArrow) { // x 轴箭头节点数组 var xArrowPois = [ [dvb[2] + 5, dvb[1] + 4], [dvb[2] + 13, dvb[1]], [dvb[2] + 5, dvb[1] - 4] ]; // y 轴箭头节点数组 var yArrowPois = [ [dvb[0] - 4, dvb[3] - 5], [dvb[0], dvb[3] - 13], [dvb[0] + 4, dvb[3] - 5] ]; //x轴箭头 var xSP = new Polygon_Polygon(xArrowPois); xSP.style = {fillColor: "#008acd"}; Util.copyAttributesWithClip(xSP.style, sets.axisStyle); arrows.push(shapeFactory.createShape(xSP)); //y轴箭头 var ySP = new Polygon_Polygon(yArrowPois); ySP.style = {fillColor: "#008acd"}; Util.copyAttributesWithClip(ySP.style, sets.axisStyle); arrows.push(shapeFactory.createShape(ySP)); // z轴箭头 坐标轴箭头是否要使用 if (sets.axis3DParameter && !isNaN(sets.axis3DParameter) && sets.axis3DParameter >= 15) { var zSP = new Polygon_Polygon(zArrowPois); zSP.style = {fillColor: "#008acd"}; Util.copyAttributesWithClip(zSP.style, sets.axisStyle); arrows.push(shapeFactory.createShape(zSP)); } } //不带箭头的坐标轴 pois = xMainPois; // 坐标轴参数对象 var axisSP = new Line_Line(pois); // 坐标轴默认style axisSP.style = { strokeLinecap: "butt", strokeLineJoin: "round", strokeColor: "#008acd", strokeWidth: 1 }; // 用户 style if (sets.axisStyle) { Util.copyAttributesWithClip(axisSP.style, sets.axisStyle); } // 禁止事件 axisSP.clickable = false; axisSP.hoverable = false; // 创建坐标轴图形对象 var axisMain = [shapeFactory.createShape(axisSP)]; // Y 轴标签 var yLabels = []; if (sets.axisYLabels && sets.axisYLabels.length && sets.axisYLabels.length > 0) { var axisYLabels = sets.axisYLabels; let len = axisYLabels.length; // 标签偏移量 var ylOffset = [0, 0]; if (sets.axisYLabelsOffset && sets.axisYLabelsOffset.length) { ylOffset = sets.axisYLabelsOffset; } if (len == 1) { // 标签参数对象 let labelYSP = new Label(dvb[0] - 5 + ylOffset[0], dvb[3] + ylOffset[1], axisYLabels[0]); labelYSP.style = { labelAlign: "right" }; // 用户 style if (sets.axisYLabelsStyle) { Util.copyAttributesWithClip(labelYSP.style, sets.axisYLabelsStyle); } // 禁止事件 labelYSP.clickable = false; labelYSP.hoverable = false; // 制作标签 yLabels.push(shapeFactory.createShape(labelYSP)); } else { var labelY = dvb[3]; // y 轴标签单位距离 var yUnit = Math.abs(dvb[1] - dvb[3]) / (len - 1); for (var j = 0; j < len; j++) { // 标签参数对象 let labelYSP = new Label(dvb[0] - 5 + ylOffset[0], labelY + ylOffset[1], axisYLabels[j]); labelYSP.style = { labelAlign: "right" }; // 用户 style if (sets.axisYLabelsStyle) { Util.copyAttributesWithClip(labelYSP.style, sets.axisYLabelsStyle); } // 禁止事件 labelYSP.clickable = false; labelYSP.hoverable = false; // 制作标签 yLabels.push(shapeFactory.createShape(labelYSP)); // y 轴标签 y 方向增量 labelY += yUnit; } } } // X 轴标签 var xLabels = []; if (sets.axisXLabels && sets.axisXLabels.length && sets.axisXLabels.length > 0) { let axisXLabels = sets.axisXLabels; let len = axisXLabels.length; // 标签偏移量 let xlOffset = [0, 0]; if (sets.axisXLabelsOffset && sets.axisXLabelsOffset.length) { xlOffset = sets.axisXLabelsOffset; } // 标签个数与数据字段个数相等等时,标签在 x 轴均匀排列 if (xShapeInfo && xShapeInfo.xPositions && xShapeInfo.xPositions.length && xShapeInfo.xPositions.length == len) { let xsCenter = xShapeInfo.xPositions; for (let K = 0; K < len; K++) { // 标签参数对象 let labelXSP = new Label(xsCenter[K] + xlOffset[0], dvb[1] + xlOffset[1], axisXLabels[K]); // 默认 style labelXSP.style = { labelAlign: "center", labelBaseline: "top" }; // 用户 style if (sets.axisXLabelsStyle) { Util.copyAttributesWithClip(labelXSP.style, sets.axisXLabelsStyle); } // 禁止事件 labelXSP.clickable = false; labelXSP.hoverable = false; // 创建标签对象 xLabels.push(shapeFactory.createShape(labelXSP)); } } else { if (len == 1) { // 标签参数对象 let labelXSP = new Label(dvb[0] - 5 + xlOffset[0], dvb[1] + xlOffset[0], axisXLabels[0]); // 默认 style labelXSP.style = { labelAlign: "center", labelBaseline: "top" }; // 用户 style if (sets.axisXLabelsStyle) { Util.copyAttributesWithClip(labelXSP.style, sets.axisXLabelsStyle); } // 禁止事件 labelXSP.clickable = false; labelXSP.hoverable = false; // 创建标签对象 xLabels.push(shapeFactory.createShape(labelXSP)); } else { let labelX = dvb[0]; // x 轴标签单位距离 let xUnit = Math.abs(dvb[2] - dvb[0]) / (len - 1); for (let m = 0; m < len; m++) { // 标签参数对象 let labelXSP = new Label(labelX + xlOffset[0], dvb[1] + xlOffset[1], axisXLabels[m]); // 默认 style labelXSP.style = { labelAlign: "center", labelBaseline: "top" }; // 用户 style if (sets.axisXLabelsStyle) { Util.copyAttributesWithClip(labelXSP.style, sets.axisXLabelsStyle); } // 禁止事件 labelXSP.clickable = false; labelXSP.hoverable = false; // 创建标签对象 xLabels.push(shapeFactory.createShape(labelXSP)); // x 轴标签 x 方向增量 labelX += xUnit; } } } } // 组装并返回构成坐标轴的图形 return ((refLines.concat(axisMain)).concat(yLabels)).concat(xLabels).concat(arrows); } /** * @function FeatureShapeFactory.prototype.ShapeStyleTool * @description 一个图形 style 处理工具。此工具将指定的默认 style,通用 style,按 styleGroup 取得的 style 和按数据值 value 范围取得的 style 进行合并,得到图形最终的 style。 * @param {Object} defaultStyle - 默认style,此样式对象可设属性根据图形类型参考 <{@link ShapeParameters}> 子类对象的 style 属性。 * @param {Object} style - 图形对象基础 style,此参数控制图形的基础样式,可设属性根据图形类型参考 <{@link ShapeParameters}> 子类对象的 style 属性。优先级低于 styleGroup,styleByCodomain。 * @param {Array.} styleGroup - 一个 style 数组,优先级低于 styleByCodomain,高于 style。此数组每个元素是样式对象, * 其可设属性根据图形类型参考 <{@link ShapeParameters}> 子类对象的 style 属性。通过 index 参数从 styleGroup 中取 style。 * @param {Array.} styleByCodomain - 按数据(参数 value)所在值域范围控制数据的可视化对象样式。 * (start code) * // styleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,其可设属性根据图形类型参考 子类对象的 style 属性。 * // dataStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * (end) * @param {number} index - styleGroup 的索引值,用于取出 styleGroup 指定的 style。 * @param {number} value - 数据值,用于取出 styleByCodomain 指定的 style。 * @returns {Object} 合并后的样式 (style) 对象。 */ static ShapeStyleTool(defaultStyle, style, styleGroup, styleByCodomain, index, value) { // 用 defaultStyle 初始化 style 对象 var finalStyle = defaultStyle ? defaultStyle : {}; // 基础 style if (style) { Util.copyAttributesWithClip(finalStyle, style); } // 按索引赋 style if (styleGroup && styleGroup.length && typeof(index) !== "undefined" && !isNaN(index) && index >= 0) { if (styleGroup[index]) { Util.copyAttributesWithClip(finalStyle, styleGroup[index]); } } // 按值域赋 style if (styleByCodomain && styleByCodomain.length && typeof(value) !== "undefined") { var dsc = styleByCodomain; var dscLen = dsc.length; var v = parseFloat(value); for (var i = 0; i < dscLen; i++) { if (dsc[i].start <= v && v < dsc[i].end) { Util.copyAttributesWithClip(finalStyle, dsc[i].style); break; } } } return finalStyle; } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/Theme.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureTheme * @aliasclass Feature.Theme * @deprecatedclass SuperMap.Feature.Theme * @category Visualization Theme * @classdesc 专题要素基类。 * @param {Object} data - 用户数据,用于生成可视化 shape。 * @param {SuperMap.Layer.Theme} layer - 此专题要素所在图层。 * @usage */ class Theme_Theme { constructor(data, layer) { if (!data) { return; } // layer 必须已经添加到地图, 且已初始化渲染器 if (!layer || !layer.map || !layer.renderer) { return; } /** * @member {string} FeatureTheme.prototype.id * @description 专题要素唯一标识。 */ this.id = Util.createUniqueID(this.CLASS_NAME + "_"); /** * @member {LonLat} FeatureTheme.prototype.lonlat * @description 专题要素地理参考位置。子类中必须根据用户数据(或地理位置参数)对其赋值。 */ this.lonlat = null; /** * @member {Array.} FeatureTheme.prototype.location * @description 专题要素像素参考位置。通常由地理参考位置决定。长度为 2 的数组,第一个元素表示 x 坐标,第二个元素表示 y 坐标。 */ this.location = []; /** * @readonly * @member {Object} FeatureTheme.prototype.data * @description 用户数据,用于生成可视化 shape,可在子类中规定数据格式或类型,如:<{@link FeatureVector}>。 */ this.data = data; /** * @readonly * @member {Array.} FeatureTheme.prototype.shapes * @description 构成此专题要素的可视化图形对象数组,数组顺序控制渲染。 */ this.shapes = []; /** * @readonly * @member {SuperMap.Layer.Theme} FeatureTheme.prototype.layer * @description 此专题要素所在专题图层。 */ this.layer = layer; this.CLASS_NAME = "SuperMap.Feature.Theme"; } /** * @function FeatureTheme.prototype.destroy * @description 销毁专题要素。 */ destroy() { this.data = null; this.id = null; this.lonlat = null; this.location = null; this.shapes = null; this.layer = null; } /** * @function FeatureTheme.prototype.getLocalXY * @description 地理坐标转为像素坐标。 * @param {GeometryPoint|GeometryGeoText|LonLat} coordinate - 地理坐标点。 * @returns {Array.} 长度为 2 的数组,第一个元素表示 x 坐标,第二个元素表示 y 坐标。 */ getLocalXY(coordinate) { var resolution = this.layer.map.getResolution(); var extent = this.layer.map.getExtent(); if (coordinate instanceof Point || coordinate instanceof GeoText) { let x = (coordinate.x / resolution + (-extent.left / resolution)); let y = ((extent.top / resolution) - coordinate.y / resolution); return [x, y]; } else if (coordinate instanceof LonLat) { let x = (coordinate.lon / resolution + (-extent.left / resolution)); let y = ((extent.top / resolution) - coordinate.lat / resolution); return [x, y]; } else { return null; } } } ;// CONCATENATED MODULE: ./src/common/overlay/Graph.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemeGraph * @aliasclass Feature.Theme.Graph * @deprecatedclass SuperMap.Feature.Theme.Graph * @category Visualization Theme * @classdesc 统计专题要素基类。 * 此类定义了统计专题要素基础模型,具体的图表模型通过继承此类,在子类中实现 assembleShapes 方法。 * 统计专题要素模型采用了可视化图形大小自适应策略,用较少的参数控制着图表诸多图形,图表配置对象 的基础属性只有 7 个, * 它们控制着图表结构、值域范围、数据小数位等基础图表形态。构成图表的图形必须在图表结构里自适应大小。 * 此类不可实例化,此类的可实例化子类必须实现 assembleShapes() 方法。 * @extends FeatureTheme * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.Theme} layer - 此专题要素所在图层。 * @param {Array.} fields - data 中的参与此图表生成的字段名称。 * @param {Object} setting - 图表配置对象。 * @param {LonLat} [lonlat] - 专题要素地理位置。默认为 data 指代的地理要素 Bounds 中心。 * @usage */ class Graph extends Theme_Theme { constructor(data, layer, fields, setting, lonlat, options) { super(data, layer, fields, setting, lonlat, options); /** * @member {FeatureShapeFactory} FeatureThemeGraph.prototype.shapeFactory * @description 内置的图形工厂对象,调用其 createShape 方法创建图形。 */ this.shapeFactory = new ShapeFactory(); /** * @member {Object} FeatureThemeGraph.prototype.shapeParameters * @description 当前图形参数对象,<{@link ShapeParameters}> 的子类对象。 */ this.shapeParameters = null; /** * @member {boolean} [FeatureThemeGraph.prototype.RelativeCoordinate] * @description 图形是否已经计算了相对坐标。 */ this.RelativeCoordinate = false; /** * @member {Object} FeatureThemeGraph.prototype.setting * @description 图表配置对象,该对象控制着图表的可视化显示。 * @param {number} width - 专题要素(图表)宽度。 * @param {number} height - 专题要素(图表)高度。 * @param {Array.} codomain - 值域,长度为 2 的一维数组,第一个元素表示值域下限,第二个元素表示值域上限。 * @param {number} [XOffset] - 专题要素(图表)在 X 方向上的偏移值,单位像素。 * @param {number} [YOffset] - 专题要素(图表)在 Y 方向上的偏移值,单位像素。 * @param {Array.} [dataViewBoxParameter] - 数据视图框 dataViewBox 参数,它是指图表框 chartBox * (由图表位置、图表宽度、图表高度构成的图表范围框)在左、下,右,上四个方向上的内偏距值。 * @param {number} [decimalNumber] - 数据值数组 dataValues 元素值小数位数,数据的小数位处理参数,取值范围:[0, 16]。 * 如果不设置此参数,在取数据值时不对数据做小数位处理。 * */ this.setting = null; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.origonPoint * @description 专题要素(图表)原点,图表左上角点像素坐标,是长度为 2 的一维数组,第一个元素表示 x 坐标,第二个元素表示 y 坐标。 */ this.origonPoint = null; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.chartBox * @description 专题要素(图表)区域,即图表框,长度为 4 的一维数组,数组的 4 个元素依次表示图表框左端 x 坐标值、 * 下端 y坐标值、右端 x坐标值、上端 y 坐标值;[left, bottom, right, top]。 */ this.chartBox = null; /** * @readonly * @member {Bounds} FeatureThemeGraph.prototype.chartBounds * @description 图表 Bounds 随着 lonlat、XOffset、YOffset 更新,注意 chartBounds 是图表像素范围,不是地理范围。 */ this.chartBounds = null; /** * @readonly * @member {number} FeatureThemeGraph.prototype.width * @description 专题要素(图表)宽度 。 */ this.width = null; /** * @readonly * @member {number} FeatureThemeGraph.prototype.height * @description 专题要素(图表)高度 。 */ this.height = null; /** * @readonly * @member {number} FeatureThemeGraph.prototype.XOffset * @description 专题要素(图表)在 X 方向上的偏移值,单位像素。 */ this.XOffset = 0; /** * @readonly * @member {number} FeatureThemeGraph.prototype.YOffset * @description 专题要素(图表)在 Y 方向上的偏移值,单位像素。 */ this.YOffset = 0; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.DVBParameter * @description 数据视图框参数,长度为 4 的一维数组(数组元素值 >= 0),[leftOffset, bottomOffset, rightOffset, topOffset],chartBox 内偏距值。 * 此属性用于指定数据视图框 dataViewBox 的范围。 */ this.DVBParameter = null; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.dataViewBox * @description 数据视图框,长度为 4 的一维数组,[left, bottom, right, top]。 * dataViewBox 是统计专题要素最核心的内容,它负责解释数据在一个像素区域里的数据可视化含义, * 这种含义用可视化图形表达出来,这些表示数据的图形和一些辅助图形组合在一起构成统计专题图表。 */ this.dataViewBox = null; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.DVBCodomain * @description 数据视图框的内允许展示的数据值域,长度为 2 的一维数组,第一个元素表示值域下限,第二个元素表示值域上限。 * dataViewBox 中允许的数据范围,对数据溢出值域范围情况的处理需要在 assembleShapes 中进行。 */ this.DVBCodomain = null; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.DVBCenterPoint * @description 数据视图框中心点,长度为 2 的一维数组,第一个元素表示 x 坐标,第二个元素表示 y 坐标。 */ this.DVBCenterPoint = null; /** * @readonly * @member {string} FeatureThemeGraph.prototype.DVBUnitValue * @description 单位值。在 assembleShapes() 中初始化其具体意义,例如:饼图的 DVBUnitValue 可以定义为"360/数据总和", * 折线图的 DVBUnitValue 可以定义为 "DVBCodomain/DVBHeight"。 */ this.DVBUnitValue = null; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.DVBOrigonPoint * @description 数据视图框原点,数据视图框左上角点,长度为 2 的一维数组,第一个元素表示 x 坐标,第二个元素表示 y 坐标。 */ this.DVBOrigonPoint = null; /** * @readonly * @member {number} FeatureThemeGraph.prototype.DVBWidth * @description 数据视图框宽度。 */ this.DVBWidth = null; /** * @readonly * @member {number} FeatureThemeGraph.prototype.DVBHeight * @description 数据视图框高度。 */ this.DVBHeight = null; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.origonPointOffset * @description 数据视图框原点相对于图表框的原点偏移量,长度为 2 的一维数组,第一个元素表示 x 偏移量,第二个元素表示 y 偏移量。 */ this.origonPointOffset = null; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.fields * @description 数据{FeatureVector}属性字段。 */ this.fields = fields || []; /** * @readonly * @member {Array.} FeatureThemeGraph.prototype.dataValues * @description 图表展示的数据值,通过 fields 从数据 feature 属性中获得。 */ this.dataValues = null; // 图表位置 if (lonlat) { this.lonlat = lonlat; } else { // 默认使用 bounds 中心 this.lonlat = this.data.geometry.getBounds().getCenterLonLat(); } // 配置项检测与赋值 if (setting && setting.width && setting.height && setting.codomain) { this.setting = setting; } this.CLASS_NAME = "SuperMap.Feature.Theme.Graph"; } /** * @function FeatureThemeGraph.prototype.destroy * @description 销毁专题要素。 */ destroy() { this.shapeFactory = null; this.shapeParameters = null; this.width = null; this.height = null; this.origonPoint = null; this.chartBox = null; this.dataViewBox = null; this.chartBounds = null; this.DVBParameter = null; this.DVBOrigonPoint = null; this.DVBCenterPoint = null; this.DVBWidth = null; this.DVBHeight = null; this.DVBCodomain = null; this.DVBUnitValue = null; this.origonPointOffset = null; this.XOffset = null; this.YOffset = null; this.fields = null; this.dataValues = null; this.setting = null; super.destroy(); } /** * @function FeatureThemeGraph.prototype.initBaseParameter * @description 初始化专题要素(图表)基础参数。在调用此方法前,此类的图表模型相关属性都是不可用的 ,此方法在 assembleShapes 函数中调用。 * 调用此函数关系到 setting 对象的以下属性。 * @param {number} width - 专题要素(图表)宽度。 * @param {number} height - 专题要素(图表)高度。 * @param {Array.} codomain - 值域,长度为 2 的一维数组,第一个元素表示值域下限,第二个元素表示值域上限。 * @param {number} [XOffset] - 专题要素(图表)在 X 方向上的偏移值,单位像素。 * @param {number} [YOffset] - 专题要素(图表)在 Y 方向上的偏移值,单位像素。 * @param {Array.} [dataViewBoxParameter] - 数据视图框 dataViewBox 参数,它是指图表框 chartBox。 * (由图表位置、图表宽度、图表高度构成的图表范围框)在左、下,右,上四个方向上的内偏距值。 * @param {number} [decimalNumber] - 数据值数组 dataValues 元素值小数位数,数据的小数位处理参数,取值范围:[0, 16]。如果不设置此参数,在取数据值时不对数据做小数位处理。 * @returns {boolean} 初始化参数是否成功。 */ initBaseParameter() { // 参数初始化是否成功 var isSuccess = true; // setting 属性是否已成功赋值 if (!this.setting) { return false; } var sets = this.setting; // 检测 setting 的必设参数 if (!(sets.width && sets.height && sets.codomain)) { return false; } // 数据 var decimalNumber = (typeof(sets.decimalNumber) !== "undefined" && !isNaN(sets.decimalNumber)) ? sets.decimalNumber : -1; var dataEffective = Theme_Theme.getDataValues(this.data, this.fields, decimalNumber); this.dataValues = dataEffective ? dataEffective : []; // 基础参数 width, height, codomain this.width = parseFloat(sets.width); this.height = parseFloat(sets.height); this.DVBCodomain = sets.codomain; // 图表偏移 // if(sets.XOffset) {this.XOffset = sets.XOffset}; // if(sets.YOffset) {this.YOffset = sets.YOffset}; this.XOffset = sets.XOffset ? sets.XOffset : 0; this.YOffset = sets.YOffset ? sets.YOffset : 0; // 其他默认值 this.origonPoint = []; this.chartBox = []; this.dataViewBox = []; this.DVBParameter = sets.dataViewBoxParameter ? sets.dataViewBoxParameter : [0, 0, 0, 0]; this.DVBOrigonPoint = []; this.DVBCenterPoint = []; this.origonPointOffset = []; // 图表位置 this.resetLocation(); // 专题要素宽度 w var w = this.width; // 专题要素高度 h var h = this.height; // 专题要素像素位置 loc var loc = this.location; // 专题要素像素位置 loc this.origonPoint = [loc[0] - w / 2, loc[1] - h / 2]; // 专题要素原点(左上角) var op = this.origonPoint; // 图表框([left, bottom, right, top]) this.chartBox = [op[0], op[1] + h, op[0] + w, op[1]]; // 图表框 var cb = this.chartBox; // 数据视图框参数,它是图表框各方向对应的内偏距 var dbbP = this.DVBParameter; // 数据视图框 ([left, bottom, right, top]) this.dataViewBox = [cb[0] + dbbP[0], cb[1] - dbbP[1], cb[2] - dbbP[2], cb[3] + dbbP[3]]; // 数据视图框 var dvb = this.dataViewBox; //检查数据视图框是否合法 if (dvb[0] >= dvb[2] || dvb[1] <= dvb[3]) { return false; } // 数据视图框原点 this.DVBOrigonPoint = [dvb[0], dvb[3]]; // 数据视图框宽度 this.DVBWidth = Math.abs(dvb[2] - dvb[0]); // 数据视图框高度 this.DVBHeight = Math.abs(dvb[1] - dvb[3]); // 数据视图框中心点 this.DVBCenterPoint = [this.DVBOrigonPoint[0] + this.DVBWidth / 2, this.DVBOrigonPoint[1] + this.DVBHeight / 2] // 数据视图框原点与图表框的原点偏移量 this.origonPointOffset = [this.DVBOrigonPoint[0] - op[0], this.DVBOrigonPoint[1] - op[1]]; return isSuccess; } /** * @function FeatureThemeGraph.prototype.resetLocation * @description 根据地理位置 lonlat 重置专题要素(图表)位置。 * @param {LonLat} lonlat - 专题要素新的像素中心位置。 * @returns {Array.} 新专题要素像素参考位置。长度为 2 的数组,第一个元素表示 x 坐标,第二个元素表示 y 坐标。 */ resetLocation(lonlat) { if (lonlat) { this.lonlat = lonlat; } // 获取地理位置对应的像素坐标 newLocalLX var newLocalLX = this.getLocalXY(this.lonlat); // 处理偏移量 XOffset, YOffset newLocalLX[0] += this.XOffset; newLocalLX[1] += this.YOffset; // 将图形位置赋予 location 属性(注意 location 属性表示的是专题要素中心位置) this.location = newLocalLX; // 更新图表像素 Bounds var w = this.width; var h = this.height; var loc = this.location; this.chartBounds = new Bounds(loc[0] - w / 2, loc[1] + h / 2, loc[0] + w / 2, loc[1] - h / 2); //重新计算当前渐变色 this.resetLinearGradient(); return loc; } /** * @function FeatureThemeGraph.prototype.resetLinearGradient * @description resetLocation 中调用 图表的相对坐标存在的时候,重新计算渐变的颜色(目前用于二维柱状图渐变色 所以子类实现此方法)。 */ resetLinearGradient() { //子类实现此方法 } /** * @function FeatureThemeGraph.prototype.shapesConvertToRelativeCoordinate * @description 将(构成图表)图形的节点转为相对坐标表示,此函数必须且只能在 assembleShapes() 结束时调用。 */ shapesConvertToRelativeCoordinate() { var shapes = this.shapes; var shapeROP = this.location; for (var i = 0, len = shapes.length; i < len; i++) { shapes[i].refOriginalPosition = shapeROP; var style = shapes[i].style; for (var sty in style) { switch (sty) { case "pointList": var pl = style[sty]; for (var j = 0, len2 = pl.length; j < len2; j++) { pl[j][0] -= shapeROP[0]; pl[j][1] -= shapeROP[1]; } break; case "x": style[sty] -= shapeROP[0]; break; case "y": style[sty] -= shapeROP[1]; break; default: break; } } } this.RelativeCoordinate = true; } /** * @function FeatureThemeGraph.prototype.assembleShapes * @description 图形装配函数。抽象方法,可视化子类必须实现此方法。
* 重写此方法的步骤:
* 1. 图表的某些特殊配置项(setting)处理,例如多数图表模型需要重新指定 dataViewBoxParameter 的默认值。
* 2. 调用 initBaseParameter() 方法初始化模型属性值,此步骤必须执行,只有当 initBaseParameter 返回 true 时才可以允许进行后续步骤。
* 3. 计算图形参数,制作图形,图形组合。在组装图表过程中,应该特别注意数据视图框单位值的定义、数据值溢出值域范围的处理和图形大小自适应。
* 4. 调用 shapesConvertToRelativeCoordinate() 方法,将图形的坐标值转为相对坐标,此步骤必须执行。 * @example * //子类实现 assembleShapes() 接口的步骤示例: * assembleShapes: function(){ * // 第一步:图表的某些特殊配置项(setting)处理,例如多数图表模型需要重新指定 dataViewBoxParameter 的默认值。此步骤是非必须过程。 * * // 图表配置对象 * var sets = this.setting; * // 默认数据视图框,这里展示在使用坐标轴和不使用坐标轴情况下对数据视图框参数赋予不同的默认值 * if(!sets.dataViewBoxParameter){ * if(typeof(sets.useAxis) === "undefined" || sets.useAxis){ * sets.dataViewBoxParameter = [45, 15, 15, 15]; * } * else{ * sets.dataViewBoxParameter = [5, 5, 5, 5]; * } * } * * // 第二步:初始化图表模型基本参数,只有在图表模型基本参数初始化成功时才可模型相关属性,如 this.dataViewBox、 this.DVBCodomain等。此步骤是必须过程。 * if(!this.initBaseParameter()) return; * * // 第三步:用图形组装图表,在组装图表过程中,应该特别注意数据视图框单位值的定义、数据值溢出值域范围的处理和图形大小自适应。 * // 定义图表数据视图框中单位值的含义,下面行代码表示将数据视图框单位值定义为数据视图框高度上每像素代表的数据值 * this.DVBUnitValue = (this.codomain[1] - this.codomain[0])/this.DVBHeight; * var uv = this.DVBUnitValue; * * // 图形参数计算代码...... * * // 关于图形装配,实际上就是利用图形工程对象 this.shapeFactory 的 createShape() 方法通过图形参数对象创建可视化的图形对象,并把这些图形对象按序添加到模型的图形库(his.shapes)中。下面的代码演示创建一个面图形参数对象,并允许通过图形配置对象设置图形的 style 和 highlightStyle, * var barParams = new ShapeParametersPolygon(poiLists); * barParams.style = sets.barStyle? sets.barStyle:{fillColor: "lightblue"}; * barParams.highlightStyle = sets.barHoverStyle? sets.barHoverStyle:{fillColor: "blue"}; * // 图形携带数据ID信息 * barParams.refDataID = this.data.id; * // 创建图形并添加到图表图形数组中 * this.shapes.push(this.shapeFactory.createShape(barParams)); * * // 第四步:调用 shapesConvertToRelativeCoordinate() 方法,将图形库(his.shapes)中的图形转为由相对坐标表示的图形,客户端统计专题图模块从结构上要求可视化图形使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数。此步骤是必须过程。 * this.shapesConvertToRelativeCoordinate(); * }, */ assembleShapes() { //子类必须实现此方法 } /** * @function FeatureThemeGraph.prototype.getLocalXY * @description 地理坐标转为像素坐标。 * @param {LonLat} lonlat - 带转换的地理坐标。 * @returns 屏幕像素坐标。 */ getLocalXY(lonlat) { return this.layer.getLocalXY(lonlat); } } /** * @function FeatureTheme.getDataValues * @description 根据字段名数组获取指定数据(feature)的属性值数组。属性值类型必须为 Number。 * @param {FeatureVector} data - 数据。 * @param {Array.} [fields] - 字段名数组。 * @param {number} [decimalNumber] - 小数位处理参数,对获取到的属性数据值进行小数位处理。 * @returns {Array.} 字段名数组对应的属性数据值数组。 */ Theme_Theme.getDataValues = function (data, fields, decimalNumber) { if (!data.attributes) { return false; } var fieldsValue = []; var attrs = data.attributes; for (var i = 0; i < fields.length; i++) { for (var field in attrs) { if (field !== fields[i]) { continue } // 数字转换判断 try { if (!isNaN(decimalNumber) && decimalNumber >= 0) { fieldsValue.push(parseFloat(attrs[field].toString()).toFixed(decimalNumber)); } else { fieldsValue.push(parseFloat(attrs[field].toString())); } } catch (e) { throw new Error("not a number") } } } if (fieldsValue.length === fields.length) { return fieldsValue; } else { return false; } }; ;// CONCATENATED MODULE: ./src/common/overlay/Bar.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemeBar * @aliasclass Feature.Theme.Bar * @deprecatedclass SuperMap.Feature.Theme.Bar * @classdesc 柱状图 。 * @category Visualization Theme * @example * // barStyleByCodomain参数用法如下: * // barStyleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,这个样式对象的可设属性: 。 * // barStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * @extends FeatureThemeGraph * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.Graph} layer - 此专题要素所在图层。 * @param {Array.} fields - data 属性中的参与此图表生成的属性字段名称。 * @param {FeatureThemeBar.setting} setting - 图表配置对象。 * @param {LonLat} [lonlat] - 专题要素地理位置。默认为 data 指代的地理要素 Bounds 中心。 * @usage * @private */ class Bar extends Graph { constructor(data, layer, fields, setting, lonlat) { super(data, layer, fields, setting, lonlat); this.CLASS_NAME = "SuperMap.Feature.Theme.Bar"; } /** * @function FeatureThemeBar.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FeatureThemeBar.prototype.assembleShapes * @description 图表图形装配函数。 */ assembleShapes() { //默认渐变颜色数组 var deafaultColors = [["#00FF00", "#00CD00"], ["#00CCFF", "#5E87A2"], ["#00FF66", "#669985"], ["#CCFF00", "#94A25E"], ["#FF9900", "#A2945E"]]; //默认阴影 var deafaultShawdow = { showShadow: true, shadowBlur: 8, shadowColor: "rgba(100,100,100,0.8)", shadowOffsetX: 2, shadowOffsetY: 2 }; // 图表配置对象 var sets = this.setting; if (!sets.barLinearGradient) { sets.barLinearGradient = deafaultColors; } // 默认数据视图框 if (!sets.dataViewBoxParameter) { if (typeof(sets.useAxis) === "undefined" || sets.useAxis) { sets.dataViewBoxParameter = [45, 15, 15, 15]; } else { sets.dataViewBoxParameter = [5, 5, 5, 5]; } } // 重要步骤:初始化参数 if (!this.initBaseParameter()) { return; } // 值域 var codomain = this.DVBCodomain; // 重要步骤:定义图表 BaFeatureThemeBarr 数据视图框中单位值的含义 this.DVBUnitValue = (codomain[1] - codomain[0]) / this.DVBHeight; // 数据视图域 var dvb = this.dataViewBox; // 用户数据值 var fv = this.dataValues; if (fv.length < 1) { return; } // 没有数据 // 数据溢出值域范围处理 for (let i = 0, fvLen = fv.length; i < fvLen; i++) { if (fv[i] < codomain[0] || fv[i] > codomain[1]) { return; } } // 获取 x 轴上的图形信息 var xShapeInfo = this.calculateXShapeInfo(); if (!xShapeInfo) { return; } // 每个柱条 x 位置 var xsLoc = xShapeInfo.xPositions; // 柱条宽度 var xsWdith = xShapeInfo.width; // 背景框,默认启用 if (typeof(sets.useBackground) === "undefined" || sets.useBackground) { // 将背景框图形添加到模型的 shapes 数组,注意添加顺序,后添加的图形在先添加的图形之上。 this.shapes.push(ShapeFactory.Background(this.shapeFactory, this.chartBox, sets)); } // 坐标轴, 默认启用 if (typeof(sets.useAxis) === "undefined" || sets.useAxis) { // 添加坐标轴图形数组 this.shapes = this.shapes.concat(ShapeFactory.GraphAxis(this.shapeFactory, dvb, sets, xShapeInfo)); } for (var i = 0; i < fv.length; i++) { // 计算柱条 top 边的 y 轴坐标值 var yPx = dvb[1] - (fv[i] - codomain[0]) / this.DVBUnitValue; // 柱条节点数组 var poiLists = [ [xsLoc[i] - xsWdith / 2, dvb[1] - 1], [xsLoc[i] + xsWdith / 2, dvb[1] - 1], [xsLoc[i] + xsWdith / 2, yPx], [xsLoc[i] - xsWdith / 2, yPx] ]; // 柱条参数对象(一个面参数对象) var barParams = new Polygon_Polygon(poiLists); // 柱条 阴影 style if (typeof(sets.showShadow) === "undefined" || sets.showShadow) { if (sets.barShadowStyle) { var sss = sets.barShadowStyle; if (sss.shadowBlur) { deafaultShawdow.shadowBlur = sss.shadowBlur; } if (sss.shadowColor) { deafaultShawdow.shadowColor = sss.shadowColor; } if (sss.shadowOffsetX) { deafaultShawdow.shadowOffsetX = sss.shadowOffsetX; } if (sss.shadowOffsetY) { deafaultShawdow.shadowOffsetY = sss.shadowOffsetY; } } barParams.style = {}; Util.copyAttributesWithClip(barParams.style, deafaultShawdow); } // 图形携带的数据信息 barParams.refDataID = this.data.id; barParams.dataInfo = { field: this.fields[i], value: fv[i] }; // 柱条 hover click if (typeof(sets.barHoverAble) !== "undefined") { barParams.hoverable = sets.barHoverAble; } if (typeof(sets.barClickAble) !== "undefined") { barParams.clickable = sets.barClickAble; } // 创建柱条并添加到图表图形数组中 this.shapes.push(this.shapeFactory.createShape(barParams)); } // 重要步骤:将图形转为由相对坐标表示的图形,以便在地图平移缩放过程中快速重绘图形 // (统计专题图模块从结构上要求使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数) this.shapesConvertToRelativeCoordinate(); } /** * @function FeatureThemeBar.prototype.calculateXShapeInfo * @description 计算 X 轴方向上的图形信息,此信息是一个对象,包含两个属性, * 属性 xPositions 是一个一维数组,该数组元素表示图形在 x 轴方向上的像素坐标值, * 如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。 * width 表示图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 * 本函数中图形配置对象 setting 可设属性: * xShapeBlank - {Array.} 水平方向上的图形空白间隔参数。 * 长度为 3 的数组,第一元素表示第一个图形左端与数据视图框左端的空白间距,第二个元素表示图形间空白间距, * 第三个元素表示最后一个图形右端与数据视图框右端端的空白间距 。 * @returns {Object} 如果计算失败,返回 null;如果计算成功,返回 X 轴方向上的图形信息,此信息是一个对象,包含以下两个属性: * xPositions - {Array.} 表示图形在 x 轴方向上的像素坐标值,如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。 * width - {number} 表示图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 * */ calculateXShapeInfo() { var dvb = this.dataViewBox; // 数据视图框 var sets = this.setting; // 图表配置对象 var fvc = this.dataValues.length; // 数组值个数 if (fvc < 1) { return null; } var xBlank; // x 轴空白间隔参数 var xShapePositions = []; // x 轴上图形的位置 var xShapeWidth = 0; // x 轴上图形宽度(自适应) var dvbWidth = this.DVBWidth; // 数据视图框宽度 // x 轴空白间隔参数处理 if (sets.xShapeBlank && sets.xShapeBlank.length && sets.xShapeBlank.length == 3) { xBlank = sets.xShapeBlank; var xsLen = dvbWidth - (xBlank[0] + xBlank[2] + (fvc - 1) * xBlank[1]); if (xsLen <= fvc) { return null; } xShapeWidth = xsLen / fvc } else { // 默认使用等距离空白间隔,空白间隔为图形宽度 xShapeWidth = dvbWidth / (2 * fvc + 1); xBlank = [xShapeWidth, xShapeWidth, xShapeWidth]; } // 图形 x 轴上的位置计算 var xOffset = 0 for (var i = 0; i < fvc; i++) { if (i == 0) { xOffset = xBlank[0] + xShapeWidth / 2; } else { xOffset += (xShapeWidth + xBlank[1]); } xShapePositions.push(dvb[0] + xOffset); } return { "xPositions": xShapePositions, "width": xShapeWidth }; } /** * @function FeatureThemeBar.prototype.resetLinearGradient * @description 图表的相对坐标存在的时候,重新计算渐变的颜色(目前用于二维柱状图 所以子类实现此方法)。 */ resetLinearGradient() { if (this.RelativeCoordinate) { var shpelength = this.shapes.length; var barLinearGradient = this.setting.barLinearGradient; var index = -1; for (var i = 0; i < shpelength; i++) { var shape = this.shapes[i]; if (shape.CLASS_NAME === "SuperMap.LevelRenderer.Shape.SmicPolygon") { var style = shape.style; //计算出当前的绝对 x y var x1 = this.location[0] + style.pointList[0][0]; var x2 = this.location[0] + style.pointList[1][0]; //渐变颜色 index++; //以防定义的颜色数组不够用 if (index >= barLinearGradient.length) { index = index % barLinearGradient.length; } var color1 = barLinearGradient[index][0]; var color2 = barLinearGradient[index][1]; //颜色 var zcolor = new Color(); var linearGradient = zcolor.getLinearGradient(x1, 0, x2, 0, [[0, color1], [1, color2]]); //赋值 shape.style.color = linearGradient; } } } } } ;// CONCATENATED MODULE: ./src/common/overlay/Bar3D.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemeBar3D * @aliasclass Feature.Theme.Bar3D * @deprecatedclass SuperMap.Feature.Theme.Bar3D * @classdesc 三维柱状图 。 * @category Visualization Theme * @extends FeatureThemeGraph * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.Graph} layer - 此专题要素所在图层。 * @param {Array.} fields - data 中的参与此图表生成的字段名称。 * @param {FeatureThemeBar3D.setting} setting - 图表配置对象。 * @param {LonLat} [lonlat] - 专题要素地理位置,默认为 data 指代的地理要素 Bounds 中心。 * * * @example * // barFaceStyleByCodomain 用法示例如下: * // barFaceStyleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,这个样式对象的可设属性: 。 * // barFaceStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * * @example * // barSideStyleByCodomain 用法示例如下: * // barSideStyleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,这个样式对象的可设属性: 。 * // barSideStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * * @example * // barTopStyleByCodomain 用法示例如下: * // barTopStyleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,这个样式对象的可设属性: 。 * // barTopStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * @usage * @private */ class Bar3D extends Graph { constructor(data, layer, fields, setting, lonlat) { super(data, layer, fields, setting, lonlat); this.CLASS_NAME = "SuperMap.Feature.Theme.Bar3D"; } /** * @function FeatureThemeBar3D.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FeatureThemeBar3D.prototype.assembleShapes * @description 图形装配实现(扩展接口)。 */ assembleShapes() { // 图表配置对象 var sets = this.setting; // 默认数据视图框 if (!sets.dataViewBoxParameter) { if (typeof(sets.useAxis) === "undefined" || sets.useAxis) { sets.dataViewBoxParameter = [45, 25, 20, 20]; } else { sets.dataViewBoxParameter = [5, 5, 5, 5]; } } // 3d 柱图的坐标轴默认使用坐标轴箭头 sets.axisUseArrow = (typeof(sets.axisUseArrow) !== "undefined") ? sets.axisUseArrow : true; sets.axisXLabelsOffset = (typeof(sets.axisXLabelsOffset) !== "undefined") ? sets.axisXLabelsOffset : [-10, 10]; // 重要步骤:初始化参数 if (!this.initBaseParameter()) { return; } // 值域 var codomain = this.DVBCodomain; // 重要步骤:定义图表 FeatureThemeBar 数据视图框中单位值的含义 this.DVBUnitValue = (codomain[1] - codomain[0]) / this.DVBHeight; // 数据视图域 var dvb = this.dataViewBox; // 用户数据值 var fv = this.dataValues; if (fv.length < 1) { return; } // 没有数据 // 数据溢出值域范围处理 for (let i = 0, fvLen = fv.length; i < fvLen; i++) { if (fv[i] < codomain[0] || fv[i] > codomain[1]) { return; } } // 获取 x 轴上的图形信息 var xShapeInfo = this.calculateXShapeInfo(); if (!xShapeInfo) { return; } // 每个柱条 x 位置 var xsLoc = xShapeInfo.xPositions; // 柱条宽度 var xsWdith = xShapeInfo.width; // 坐标轴, 默认启用 if (typeof(sets.useBackground) === "undefined" || sets.useBackground) { this.shapes.push(ShapeFactory.Background(this.shapeFactory, this.chartBox, sets)); } // 坐标轴 if (!sets.axis3DParameter || isNaN(sets.axis3DParameter) || sets.axis3DParameter < 15) { sets.axis3DParameter = 20; } if (typeof(sets.useAxis) === "undefined" || sets.useAxis) { this.shapes = this.shapes.concat(ShapeFactory.GraphAxis(this.shapeFactory, dvb, sets, xShapeInfo)); } // 3d 偏移量, 默认值 10; var offset3d = (sets.bar3DParameter && !isNaN(sets.bar3DParameter)) ? sets.bar3DParameter : 10; for (let i = 0; i < fv.length; i++) { // 无 3d 偏移量时的柱面顶部 y 坐标 var yPx = dvb[1] - (fv[i] - codomain[0]) / this.DVBUnitValue; // 无 3d 偏移量时的柱面的左、右端 x 坐标 var iPoiL = xsLoc[i] - xsWdith / 2; var iPoiR = xsLoc[i] + xsWdith / 2; // 3d 柱顶面节点 var bar3DTopPois = [ [iPoiL, yPx], [iPoiR, yPx], [iPoiR - offset3d, yPx + offset3d], [iPoiL - offset3d, yPx + offset3d] ]; // 3d 柱侧面节点 var bar3DSidePois = [ [iPoiR, yPx], [iPoiR - offset3d, yPx + offset3d], [iPoiR - offset3d, dvb[1] + offset3d], [iPoiR, dvb[1]] ]; // 3d 柱正面节点 var bar3DFacePois = [ [iPoiL - offset3d, dvb[1] + offset3d], [iPoiR - offset3d, dvb[1] + offset3d], [iPoiR - offset3d, yPx + offset3d], [iPoiL - offset3d, yPx + offset3d] ]; if (offset3d <= 0) { // offset3d <= 0 时正面不偏移 bar3DFacePois = [ [iPoiL, dvb[1]], [iPoiR, dvb[1]], [iPoiR, yPx], [iPoiL, yPx] ]; } // 新建 3d 柱面顶面、侧面、正面图形参数对象 var polyTopSP = new Polygon_Polygon(bar3DTopPois); var polySideSP = new Polygon_Polygon(bar3DSidePois); var polyFaceSP = new Polygon_Polygon(bar3DFacePois); // 侧面、正面图形 style 默认值 sets.barSideStyle = sets.barSideStyle ? sets.barSideStyle : sets.barFaceStyle; sets.barSideStyleByFields = sets.barSideStyleByFields ? sets.barSideStyleByFields : sets.barFaceStyleByFields; sets.barSideStyleByCodomain = sets.barSideStyleByCodomain ? sets.barSideStyleByCodomain : sets.barFaceStyleByCodomain; sets.barTopStyle = sets.barTopStyle ? sets.barTopStyle : sets.barFaceStyle; sets.barTopStyleByFields = sets.barTopStyleByFields ? sets.barTopStyleByFields : sets.barFaceStyleByFields; sets.barTopStyleByCodomain = sets.barTopStyleByCodomain ? sets.barTopStyleByCodomain : sets.barFaceStyleByCodomain; // 顶面、侧面、正面图形 style polyFaceSP.style = ShapeFactory.ShapeStyleTool({ stroke: true, strokeColor: "#ffffff", fillColor: "#ee9900" }, sets.barFaceStyle, sets.barFaceStyleByFields, sets.barFaceStyleByCodomain, i, fv[i]); polySideSP.style = ShapeFactory.ShapeStyleTool({ stroke: true, strokeColor: "#ffffff", fillColor: "#ee9900" }, sets.barSideStyle, sets.barSideStyleByFields, sets.barSideStyleByCodomain, i, fv[i]); polyTopSP.style = ShapeFactory.ShapeStyleTool({ stroke: true, strokeColor: "#ffffff", fillColor: "#ee9900" }, sets.barTopStyle, sets.barTopStyleByFields, sets.barTopStyleByCodomain, i, fv[i]); // 3d 柱条高亮样式 sets.barSideHoverStyle = sets.barSideHoverStyle ? sets.barSideHoverStyle : sets.barFaceHoverStyle; sets.barTopHoverStyle = sets.barTopHoverStyle ? sets.barTopHoverStyle : sets.barFaceHoverStyle; polyFaceSP.highlightStyle = ShapeFactory.ShapeStyleTool({stroke: true}, sets.barFaceHoverStyle); polySideSP.highlightStyle = ShapeFactory.ShapeStyleTool({stroke: true}, sets.barSideHoverStyle); polyTopSP.highlightStyle = ShapeFactory.ShapeStyleTool({stroke: true}, sets.barTopHoverStyle); // 图形携带的数据 id 信息 & 高亮模式 polyTopSP.refDataID = polySideSP.refDataID = polyFaceSP.refDataID = this.data.id; // hover 模式(组合) polyTopSP.isHoverByRefDataID = polySideSP.isHoverByRefDataID = polyFaceSP.isHoverByRefDataID = true; // 高亮组(当鼠标 hover 到组内任何一个图形,整个组的图形都会高亮。refDataHoverGroup 在 isHoverByRefDataID 为 true 时有效) polyTopSP.refDataHoverGroup = polySideSP.refDataHoverGroup = polyFaceSP.refDataHoverGroup = Util.createUniqueID("lr_shg"); // 图形携带的数据信息 polyTopSP.dataInfo = polySideSP.dataInfo = polyFaceSP.dataInfo = { field: this.fields[i], value: fv[i] }; // 3d 柱条顶面、侧面、正面图形 hover click 设置 if (typeof(sets.barHoverAble) !== "undefined") { polyTopSP.hoverable = polySideSP.hoverable = polyFaceSP.hoverable = sets.barHoverAble; } if (typeof(sets.barClickAble) !== "undefined") { polyTopSP.clickable = polySideSP.clickable = polyFaceSP.clickable = sets.barClickAble; } // 创建3d 柱条的顶面、侧面、正面图形并添加到图表的图形列表数组 this.shapes.push(this.shapeFactory.createShape(polySideSP)); this.shapes.push(this.shapeFactory.createShape(polyTopSP)); this.shapes.push(this.shapeFactory.createShape(polyFaceSP)); } // 重要步骤:将图形转为由相对坐标表示的图形,以便在地图平移缩放过程中快速重绘图形 // (统计专题图模块从结构上要求使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数) this.shapesConvertToRelativeCoordinate(); } /** * @function FeatureThemeBar3D.prototype.calculateXShapeInfo * @description 计算 X 轴方向上的图形信息,此信息是一个对象,包含两个属性, * 属性 xPositions 是一个一维数组,该数组元素表示图形在 x 轴方向上的像素坐标值, * 如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。 * width 表示图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 * 本函数中图形配置对象 setting 可设属性: * xShapeBlank - {Array.} 水平方向上的图形空白间隔参数。 * 长度为 3 的数组,第一元素表示第一个图形左端与数据视图框左端的空白间距,第二个元素表示图形间空白间距, * 第三个元素表示最后一个图形右端与数据视图框右端端的空白间距 。 * @returns {Object} 如果计算失败,返回 null;如果计算成功,返回 X 轴方向上的图形信息,此信息是一个对象,包含以下两个属性: * xPositions - {Array.} 表示图形在 x 轴方向上的像素坐标值,如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。 * width - {number} 表示图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 */ calculateXShapeInfo() { var dvb = this.dataViewBox; // 数据视图框 var sets = this.setting; // 图表配置对象 var fvc = this.dataValues.length; // 数组值个数 if (fvc < 1) { return null; } var xBlank; // x 轴空白间隔参数 var xShapePositions = []; // x 轴上图形的位置 var xShapeWidth = 0; // x 轴上图形宽度(自适应) var dvbWidth = this.DVBWidth; // 数据视图框宽度 // x 轴空白间隔参数处理 if (sets.xShapeBlank && sets.xShapeBlank.length && sets.xShapeBlank.length == 3) { xBlank = sets.xShapeBlank; var xsLen = dvbWidth - (xBlank[0] + xBlank[2] + (fvc - 1) * xBlank[1]) if (xsLen <= fvc) { return null; } xShapeWidth = xsLen / fvc } else { // 默认使用等距离空白间隔,空白间隔为图形宽度 xShapeWidth = dvbWidth / (2 * fvc + 1); xBlank = [xShapeWidth, xShapeWidth, xShapeWidth]; } // 图形 x 轴上的位置计算 var xOffset = 0 for (var i = 0; i < fvc; i++) { if (i == 0) { xOffset = xBlank[0] + xShapeWidth / 2; } else { xOffset += (xShapeWidth + xBlank[1]); } xShapePositions.push(dvb[0] + xOffset); } return { "xPositions": xShapePositions, "width": xShapeWidth }; } } ;// CONCATENATED MODULE: ./src/common/overlay/RankSymbol.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemeRankSymbol * @aliasclass Feature.Theme.RankSymbol * @deprecatedclass SuperMap.Feature.Theme.RankSymbol * @category Visualization Theme * @classdesc 符号专题要素基类。此类定义了符号专题要素基础模型,具体的图表模型通过继承此类,在子类中实现 assembleShapes 方法。 * 符号专题要素模型采用了可视化图形大小自适应策略,用较少的参数控制着图表诸多图形,图表配置对象 的基础属性只有 5 个, * 它们控制着图表结构、值域范围、数据小数位等基础图表形态。构成图表的图形必须在图表结构里自适应大小。 * 此类不可实例化,此类的可实例化子类必须实现 assembleShapes() 方法。 * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.RankSymbol} layer - 此专题要素所在图层。 * @param {Array.} fields - data 中的参与此图表生成的字段名称。 * @param {LonLat} [lonlat] - 专题要素地理位置。默认为 data 指代的地理要素 Bounds 中心。 * @param {Object} setting - 图表配置对象。除了以下 5 个基础属性,此对象的可设属性在不同子类中有较大差异,不同子类中对同一属性的解释也可能不同,请在此类的子类中查看 setting 对象的可设属性和属性含义。 * @param {Array.} setting.codomain - 值域,长度为 2 的一维数组,第一个元素表示值域下限,第二个元素表示值域上限。 * @param {number} [setting.XOffset] - 专题要素(图表)在 X 方向上的偏移值,单位像素。 * @param {number} [setting.YOffset] - 专题要素(图表)在 Y 方向上的偏移值,单位像素。 * @param {Array.} [setting.dataViewBoxParameter] - 数据视图框 dataViewBox 参数,它是指图表框 chartBox (由图表位置、图表宽度、图表高度构成的图表范围框)在左、下,右,上四个方向上的内偏距值。 * @param {number} [setting.decimalNumber] - 数据值数组 dataValues 元素值小数位数,数据的小数位处理参数,取值范围:[0, 16]。如果不设置此参数,在取数据值时不对数据做小数位处理。 * @extends FeatureThemeGraph * @usage */ class RankSymbol extends Graph { constructor(data, layer, fields, setting, lonlat, options) { super(data, layer, fields, setting, lonlat, options); /** * @member {Object} FeatureThemeRankSymbol.prototype.setting * @description 符号配置对象,该对象控制着图表的可视化显示。 */ this.setting = null; // 配置项检测与赋值 if (setting && setting.codomain) { this.setting = setting; this.DVBCodomain = this.setting.codomain; } this.CLASS_NAME = "SuperMap.Feature.Theme.RankSymbol"; } /** * @function FeatureThemeRankSymbol.prototype.destroy * @description 销毁专题要素。 */ destroy() { this.setting = null; super.destroy(); } /** * @function FeatureThemeRankSymbol.prototype.initBaseParameter * @description 初始化专题要素(图形)基础参数。 * 在调用此方法前,此类的图表模型相关属性都是不可用的 ,此方法在 assembleShapes 函数中调用。 * 调用此函数关系到 setting 对象的以下属性。 * @param {Array.} codomain - 值域,长度为 2 的一维数组,第一个元素表示值域下限,第二个元素表示值域上限。 * @param {number} [XOffset] - 专题要素(图形)在 X 方向上的偏移值,单位像素。 * @param {number} [YOffset] - 专题要素(图形)在 Y 方向上的偏移值,单位像素。 * @param {Array.} [dataViewBoxParameter] - 数据视图框 dataViewBox 参数,它是指图形框 chartBox (由图表位置、图表宽度、图表高度构成的图表范围框)在左、下,右,上四个方向上的内偏距值。 * @param {number} [decimalNumber] - 数据值数组 dataValues 元素值小数位数,数据的小数位处理参数,取值范围:[0, 16]。如果不设置此参数,在取数据值时不对数据做小数位处理。 * @returns {boolean} 初始化参数是否成功。 */ initBaseParameter() { // 参数初始化是否成功 var isSuccess = true; // setting 属性是否已成功赋值 if (!this.setting) { return false; } var sets = this.setting; // 图表偏移 if (sets.XOffset) { this.XOffset = sets.XOffset; } if (sets.YOffset) { this.YOffset = sets.YOffset; } this.XOffset = sets.XOffset ? sets.XOffset : 0; this.YOffset = sets.YOffset ? sets.YOffset : 0; // 其他默认值 this.origonPoint = []; this.chartBox = []; this.dataViewBox = []; this.DVBParameter = sets.dataViewBoxParameter ? sets.dataViewBoxParameter : [0, 0, 0, 0]; this.DVBOrigonPoint = []; this.DVBCenterPoint = []; this.origonPointOffset = []; // 图表位置 this.resetLocation(); // 专题要素宽度 w var w = this.width; // 专题要素高度 h var h = this.height; // 专题要素像素位置 loc var loc = this.location; // 专题要素像素位置 loc this.origonPoint = [loc[0] - w / 2, loc[1] - h / 2]; // 专题要素原点(左上角) var op = this.origonPoint; // 图表框([left, bottom, right, top]) this.chartBox = [op[0], op[1] + h, op[0] + w, op[1]]; // 图表框 var cb = this.chartBox; // 数据视图框参数,它是图表框各方向对应的内偏距 var dbbP = this.DVBParameter; // 数据视图框 ([left, bottom, right, top]) this.dataViewBox = [cb[0] + dbbP[0], cb[1] - dbbP[1], cb[2] - dbbP[2], cb[3] + dbbP[3]]; // 数据视图框 var dvb = this.dataViewBox; //检查数据视图框是否合法 if (dvb[0] >= dvb[2] || dvb[1] <= dvb[3]) { return false; } // 数据视图框原点 this.DVBOrigonPoint = [dvb[0], dvb[3]]; // 数据视图框宽度 this.DVBWidth = Math.abs(dvb[2] - dvb[0]); // 数据视图框高度 this.DVBHeight = Math.abs(dvb[1] - dvb[3]); // 数据视图框中心点 this.DVBCenterPoint = [this.DVBOrigonPoint[0] + this.DVBWidth / 2, this.DVBOrigonPoint[1] + this.DVBHeight / 2]; // 数据视图框原点与图表框的原点偏移量 this.origonPointOffset = [this.DVBOrigonPoint[0] - op[0], this.DVBOrigonPoint[1] - op[1]]; return isSuccess; } } ;// CONCATENATED MODULE: ./src/common/overlay/Circle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemeCircle * @aliasclass Feature.Theme.Circle * @deprecatedclass SuperMap.Feature.Theme.Circle * @classdesc 圆类。 * @category Visualization Theme * @extends FeatureThemeRankSymbol * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.RankSymbol} layer - 此专题要素所在图层。 * @param {Array.} fields - data 中的参与此图表生成的字段名称。 * @param {FeatureThemeCircle.setting} setting - 图表配置对象。 * @param {LonLat} [lonlat] - 专题要素地理位置,默认为 data 指代的地理要素 Bounds 中心。 * @usage * @private */ class Circle extends RankSymbol { constructor(data, layer, fields, setting, lonlat) { super(data, layer, fields, setting, lonlat); this.CLASS_NAME = "SuperMap.Feature.Theme.Circle"; } /** * @function FeatureThemeCircle.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FeatureThemeCircle.prototype.assembleShapes * @description 装配图形(扩展接口)。 */ assembleShapes() { //默认填充颜色 var defaultFillColor = "#ff9277"; // setting 属性是否已成功赋值 if (!this.setting) { return false; } var sets = this.setting; // 检测 setting 的必设参数 if (!(sets.codomain)) { return false; } // 数据 var decimalNumber = (typeof(sets.decimalNumber) !== "undefined" && !isNaN(sets.decimalNumber)) ? sets.decimalNumber : -1; var dataEffective = Theme_Theme.getDataValues(this.data, this.fields, decimalNumber); this.dataValues = dataEffective ? dataEffective : []; // 数据值数组 var fv = this.dataValues; //if(fv.length != 1) return; // 没有数据 或者数据不唯一 //if(fv[0] < 0) return; //数据为负值 //用户应该定义最大 最小半径 默认最大半径MaxR:100 最小半径MinR:0; if (!sets.maxR) { sets.maxR = 100; } if (!sets.minR) { sets.minR = 0; } // 值域范围 var codomain = this.DVBCodomain; // 重要步骤:定义Circle数据视图框中单位值的含义,单位值:1所代表的长度 // 用户定义了值域范围 if (codomain && codomain[1] - codomain[0] > 0) { this.DVBUnitValue = sets.maxR / (codomain[1] - codomain[0]); } else { //this.DVBUnitValue = sets.maxR / maxValue; this.DVBUnitValue = sets.maxR; } var uv = this.DVBUnitValue; //圆半径 var r = fv[0] * uv + sets.minR; this.width = 2 * r; this.height = 2 * r; // 重要步骤:初始化参数 if (!this.initBaseParameter()) { return; } //假如用户设置了值域范围 没有在值域范围直接返回 if (codomain) { if (fv[0] < codomain[0] || fv[0] > codomain[1]) { return; } } var dvbCenter = this.DVBCenterPoint; // 数据视图框中心作为圆心 //圆形对象参数 var circleSP = new Circle_Circle(dvbCenter[0], dvbCenter[1], r); //circleSP.sytle 初始化 circleSP.style = ShapeFactory.ShapeStyleTool(null, sets.circleStyle, null, null, 0); //图形的填充颜色 if (typeof (sets.fillColor) !== "undefined") { //用户自定义 circleSP.style.fillColor = sets.fillColor; } else { //当前默认 circleSP.style.fillColor = defaultFillColor; } //圆形 Hover样式 circleSP.highlightStyle = ShapeFactory.ShapeStyleTool(null, sets.circleHoverStyle); //圆形 Hover 与 click 设置 if (typeof(sets.circleHoverAble) !== "undefined") { circleSP.hoverable = sets.circleHoverAble; } if (typeof(sets.circleClickAble) !== "undefined") { circleSP.clickable = sets.circleClickAble; } //图形携带的数据信息 circleSP.refDataID = this.data.id; circleSP.dataInfo = { field: this.fields[0], r: r, value: fv[0] }; // 创建扇形并把此扇形添加到图表图形数组 this.shapes.push(this.shapeFactory.createShape(circleSP)); // 重要步骤:将图形转为由相对坐标表示的图形,以便在地图平移缩放过程中快速重绘图形 // (统计专题图模块从结构上要求使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数) this.shapesConvertToRelativeCoordinate(); } } ;// CONCATENATED MODULE: ./src/common/overlay/Line.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemeLine * @aliasclass Feature.Theme.Line * @deprecatedclass SuperMap.Feature.Theme.Line * @classdesc 折线图。 * @category Visualization Theme * @example * // pointStyleByCodomain 参数用法示例 * // pointStyleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,这个样式对象的可设属性: 。 * // pointStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * * @extends FeatureThemeGraph * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.Graph} layer - 此专题要素所在图层。 * @param {Array.} fields - data 中的参与此图表生成的字段名称。 * @param {FeatureThemeLine.setting} setting - 图表配置对象。 * @param {LonLat} [lonlat] - 专题要素地理位置。默认为 data 指代的地理要素 Bounds 中心。 * @usage * @private */ class Line extends Graph { constructor(data, layer, fields, setting, lonlat, options) { super(data, layer, fields, setting, lonlat, options); this.CLASS_NAME = "SuperMap.Feature.Theme.Line"; } /** * @function FeatureThemeLine.prototype.destroy * @override */ destroy() { super.destroy(); } /** * @function FeatureThemeLine.prototype.assembleShapes * @description 装配图形(扩展接口)。 */ assembleShapes() { // 图表配置对象 var sets = this.setting; // 默认数据视图框 if (!sets.dataViewBoxParameter) { if (typeof(sets.useAxis) === "undefined" || sets.useAxis) { sets.dataViewBoxParameter = [45, 15, 15, 15]; } else { sets.dataViewBoxParameter = [5, 5, 5, 5]; } } // 重要步骤:初始化参数 if (!this.initBaseParameter()) { return; } var dvb = this.dataViewBox; // 值域 var codomain = this.DVBCodomain; // 重要步骤:定义图表 FeatureThemeBar 数据视图框中单位值的含义 this.DVBUnitValue = (codomain[1] - codomain[0]) / this.DVBHeight; var uv = this.DVBUnitValue; // 数据值数组 var fv = this.dataValues; if (fv.length < 1) { return; } // 没有数据 // 获取 x 轴上的图形信息 var xShapeInfo = this.calculateXShapeInfo(); if (!xShapeInfo) { return; } // 折线每个节点的 x 位置 var xsLoc = xShapeInfo.xPositions; // 背景框,默认启用 if (typeof(sets.useBackground) === "undefined" || sets.useBackground) { // 将背景框图形添加到模型的 shapes 数组,注意添加顺序,后添加的图形在先添加的图形之上。 this.shapes.push(ShapeFactory.Background(this.shapeFactory, this.chartBox, sets)); } // 折线图必须使用坐标轴 this.shapes = this.shapes.concat(ShapeFactory.GraphAxis(this.shapeFactory, dvb, sets, xShapeInfo)); // var isDataEffective = true; var xPx; // 折线节点 x 坐标 var yPx; // 折线节点 y 坐标 var poiLists = []; // 折线节点数组 var shapePois = []; // 折线节点图形数组 for (var i = 0, len = fv.length; i < len; i++) { // 数据溢出值域检查 if (fv[i] < codomain[0] || fv[i] > codomain[1]) { // isDataEffective = false; return null; } xPx = xsLoc[i]; yPx = dvb[1] - (fv[i] - codomain[0]) / uv; // 折线节点参数对象 var poiSP = new Point_Point(xPx, yPx); // 折线节点 style poiSP.style = ShapeFactory.ShapeStyleTool({fillColor: "#ee9900"}, sets.pointStyle, sets.pointStyleByFields, sets.pointStyleByCodomain, i, fv[i]); // 折线节点 hover 样式 poiSP.highlightStyle = ShapeFactory.ShapeStyleTool(null, sets.pointHoverStyle); // 折线节点 hover click if (typeof(sets.pointHoverAble) !== "undefined") { poiSP.hoverable = sets.pointHoverAble; } if (typeof(sets.pointClickAble) !== "undefined") { poiSP.clickable = sets.pointClickAble; } // 图形携带的数据信息 poiSP.refDataID = this.data.id; poiSP.dataInfo = { field: this.fields[i], value: fv[i] }; // 创建图形并把此图形添加到折线节点图形数组 shapePois.push(this.shapeFactory.createShape(poiSP)); // 添加折线节点到折线节点数组 var poi = [xPx, yPx]; poiLists.push(poi); } // 折线参数对象 var lineSP = new Line_Line(poiLists); lineSP.style = ShapeFactory.ShapeStyleTool({strokeColor: "#ee9900"}, sets.lineStyle); // 禁止事件响应 lineSP.clickable = false; lineSP.hoverable = false; var shapeLine = this.shapeFactory.createShape(lineSP); this.shapes.push(shapeLine); // 添加节点到图表图形数组 this.shapes = this.shapes.concat(shapePois); // // 数据范围检测未通过,清空图形 // if (isDataEffective === false) { // this.shapes = []; // } // 重要步骤:将图形转为由相对坐标表示的图形,以便在地图平移缩放过程中快速重绘图形 // (统计专题图模块从结构上要求使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数) this.shapesConvertToRelativeCoordinate(); } /** * @function FeatureThemeLine.prototype.calculateXShapeInfo * @description 计算 X 轴方向上的图形信息,此信息是一个对象,包含两个属性, * 属性 xPositions 是一个一维数组,该数组元素表示图形在 x 轴方向上的像素坐标值, * 如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。 * width 表示图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 * 本函数中图形配置对象 setting 可设属性:
* xShapeBlank - {Array.} 水平方向上的图形空白间隔参数。 * 长度为 2 的数组,第一元素表示第折线左端点与数据视图框左端的空白间距,第二个元素表示折线右端点右端与数据视图框右端端的空白间距 。 * @returns {Object} 如果计算失败,返回 null;如果计算成功,返回 X 轴方向上的图形信息,此信息是一个对象,包含以下两个属性:
* xPositions - {Array.} 表示图形在 x 轴方向上的像素坐标值,如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。
* width - {number} 表示图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 */ calculateXShapeInfo() { var dvb = this.dataViewBox; // 数据视图框 var sets = this.setting; // 图表配置对象 var fvc = this.dataValues.length; // 数组值个数 if (fvc < 1) { return null; } var xBlank; // x 轴空白间隔参数 var xShapePositions = []; // x 轴上图形的位置 var xShapeWidth = 0; // x 轴上图形宽度(自适应) var dvbWidth = this.DVBWidth; // 数据视图框宽度 var unitOffset = 0; // 单位偏移量 // x 轴空白间隔参数处理 if (sets.xShapeBlank && sets.xShapeBlank.length && sets.xShapeBlank.length == 2) { xBlank = sets.xShapeBlank; var xsLen = dvbWidth - (xBlank[0] + xBlank[1]); if (xsLen <= fvc) { return null; } unitOffset = xsLen / (fvc - 1); } else { // 默认使用等距离空白间隔,空白间隔为图形宽度 unitOffset = dvbWidth / (fvc + 1); xBlank = [unitOffset, unitOffset, unitOffset]; } // 图形 x 轴上的位置计算 var xOffset = 0 for (var i = 0; i < fvc; i++) { if (i == 0) { xOffset = xBlank[0]; } else { xOffset += unitOffset; } xShapePositions.push(dvb[0] + xOffset); } return { "xPositions": xShapePositions, "width": xShapeWidth }; } } ;// CONCATENATED MODULE: ./src/common/overlay/Pie.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemePie * @aliasclass Feature.Theme.Pie * @deprecatedclass SuperMap.Feature.Theme.Pie * @classdesc 饼图。 * @category Visualization Theme * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.Graph} layer - 此专题要素所在图层。 * @param {Array.} fields - data 中的参与此图表生成的字段名称。 * @param {FeatureThemePoint.setting} setting - 图表配置对象。 * @param {LonLat} [lonlat] - 专题要素地理位置。默认为 data 指代的地理要素 Bounds 中心。 * @extends FeatureThemeGraph * @example * // sectorStyleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,这个样式对象的可设属性: 。 * // sectorStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * @usage * @private */ class Pie extends Graph { constructor(data, layer, fields, setting, lonlat) { super(data, layer, fields, setting, lonlat); this.CLASS_NAME = "SuperMap.Feature.Theme.Pie"; } /** * @function FeatureThemePie.prototype.destroy * @description 销毁此专题要素。调用 destroy 后此对象所以属性置为 null。 */ destroy() { super.destroy(); } /** * @function FeatureThemePie.prototype.assembleShapes * @description 装配图形(扩展接口)。 */ assembleShapes() { // 图表配置对象 var sets = this.setting; // 一个默认 style 组 var defaultStyleGroup = [ {fillColor: "#ff9277"}, {fillColor: "#dddd00"}, {fillColor: "#ffc877"}, {fillColor: "#bbe3ff"}, {fillColor: "#d5ffbb"}, {fillColor: "#bbbbff"}, {fillColor: "#ddb000"}, {fillColor: "#b0dd00"}, {fillColor: "#e2bbff"}, {fillColor: "#ffbbe3"}, {fillColor: "#ff7777"}, {fillColor: "#ff9900"}, {fillColor: "#83dd00"}, {fillColor: "#77e3ff"}, {fillColor: "#778fff"}, {fillColor: "#c877ff"}, {fillColor: "#ff77ab"}, {fillColor: "#ff6600"}, {fillColor: "#aa8800"}, {fillColor: "#77c7ff"}, {fillColor: "#ad77ff"}, {fillColor: "#ff77ff"}, {fillColor: "#dd0083"}, {fillColor: "#777700"}, {fillColor: "#00aa00"}, {fillColor: "#0088aa"}, {fillColor: "#8400dd"}, {fillColor: "#aa0088"}, {fillColor: "#dd0000"}, {fillColor: "#772e00"} ]; // 重要步骤:初始化参数 if (!this.initBaseParameter()) { return; } // 背景框,默认不启用 if (sets.useBackground) { this.shapes.push(ShapeFactory.Background(this.shapeFactory, this.chartBox, sets)); } // 数据值数组 var fv = this.dataValues; if (fv.length < 1) { return; } // 没有数据 // 值域范围 var codomain = this.DVBCodomain; // 值域范围检测 for (let i = 0; i < fv.length; i++) { if (fv[i] < codomain[0] || fv[i] > codomain[1]) { return; } } // 值的绝对值总和 var valueSum = 0; for (let i = 0; i < fv.length; i++) { valueSum += Math.abs(fv[i]); } // 重要步骤:定义图表 FeatureThemePie 数据视图框中单位值的含义,单位值:每度代表的数值 this.DVBUnitValue = 360 / valueSum; var uv = this.DVBUnitValue; var dvbCenter = this.DVBCenterPoint; // 数据视图框中心作为扇心 var startAngle = 0; // 扇形起始边角度 var endAngle = 0; // 扇形终止边角度 var startAngleTmp = startAngle; // 扇形临时起始边角度 // 扇形(自适应)半径 var r = this.DVBHeight < this.DVBWidth ? this.DVBHeight / 2 : this.DVBWidth / 2; for (var i = 0; i < fv.length; i++) { var fvi = Math.abs(fv[i]); //计算终止角 if (i === 0) { endAngle = startAngle + fvi * uv; } else if (i === fvi.length - 1) { endAngle = startAngleTmp; } else { endAngle = startAngle + fvi * uv; } //矫正误差计算 if ((endAngle - startAngle) >= 360) { endAngle = 359.9999999; } // 扇形参数对象 var sectorSP = new Sector(dvbCenter[0], dvbCenter[1], r, startAngle, endAngle); // 扇形样式 if (typeof(sets.sectorStyleByFields) === "undefined") { // 使用默认 style 组 var colorIndex = i % defaultStyleGroup.length; sectorSP.style = ShapeFactory.ShapeStyleTool(null, sets.sectorStyle, defaultStyleGroup, null, colorIndex); } else { sectorSP.style = ShapeFactory.ShapeStyleTool(null, sets.sectorStyle, sets.sectorStyleByFields, sets.sectorStyleByCodomain, i, fv[i]); } // 扇形 hover 样式 sectorSP.highlightStyle = ShapeFactory.ShapeStyleTool(null, sets.sectorHoverStyle); // 扇形 hover 与 click 设置 if (typeof(sets.sectorHoverAble) !== "undefined") { sectorSP.hoverable = sets.sectorHoverAble; } if (typeof(sets.sectorClickAble) !== "undefined") { sectorSP.clickable = sets.sectorClickAble; } // 图形携带的数据信息 sectorSP.refDataID = this.data.id; sectorSP.dataInfo = { field: this.fields[i], value: fv[i] }; // 创建扇形并把此扇形添加到图表图形数组 this.shapes.push(this.shapeFactory.createShape(sectorSP)); // 把上一次的结束角度作为下一次的起始角度 startAngle = endAngle; } // 重要步骤:将图形转为由相对坐标表示的图形,以便在地图平移缩放过程中快速重绘图形 // (统计专题图模块从结构上要求使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数) this.shapesConvertToRelativeCoordinate(); } } ;// CONCATENATED MODULE: ./src/common/overlay/Point.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemePoint * @aliasclass Feature.Theme.Point * @deprecatedclass SuperMap.Feature.Theme.Point * @classdesc 点状图。 * @category Visualization Theme * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.Graph} layer - 此专题要素所在图层。 * @param {Array.} fields - data 中的参与此图表生成的字段名称。 * @param {FeatureThemePoint.setting} setting - 图表配置对象。 * @param {LonLat} [lonlat] - 专题要素地理位置。默认为 data 指代的地理要素 Bounds 中心。 * @example * // pointStyleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,这个样式对象的可设属性: 。 * // pointStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * @extends FeatureThemeGraph * @usage * @private */ class overlay_Point_Point extends Graph { constructor(data, layer, fields, setting, lonlat, options) { super(data, layer, fields, setting, lonlat, options); this.CLASS_NAME = "SuperMap.Feature.Theme.Point"; } /** * @function FeatureThemePoint.prototype.destroy * @description 销毁此专题要素。调用 destroy 后此对象所以属性置为 null。 */ destroy() { super.destroy(); } /** * @function FeatureThemePoint.prototype.Point.assembleShapes * @description 装配图形(扩展接口)。 */ assembleShapes() { // 图表配置对象 var sets = this.setting; // 默认数据视图框 if (!sets.dataViewBoxParameter) { if (typeof(sets.useAxis) === "undefined" || sets.useAxis) { sets.dataViewBoxParameter = [45, 15, 15, 15]; } else { sets.dataViewBoxParameter = [5, 5, 5, 5]; } } // 重要步骤:初始化参数 if (!this.initBaseParameter()) { return; } var dvb = this.dataViewBox; // 值域 var codomain = this.DVBCodomain; // 重要步骤:定义图表 FeatureThemeBar 数据视图框中单位值的含义 this.DVBUnitValue = (codomain[1] - codomain[0]) / this.DVBHeight; var uv = this.DVBUnitValue; var fv = this.dataValues; // 获取 x 轴上的图形信息 var xShapeInfo = this.calculateXShapeInfo(); if (!xShapeInfo) { return; } // 折线每个节点的 x 位置 var xsLoc = xShapeInfo.xPositions; // 背景框,默认启用 if (typeof(sets.useBackground) === "undefined" || sets.useBackground) { // 将背景框图形添加到模型的 shapes 数组,注意添加顺序,后添加的图形在先添加的图形之上。 this.shapes.push(ShapeFactory.Background(this.shapeFactory, this.chartBox, sets)); } // 点状图必须使用坐标轴 this.shapes = this.shapes.concat(ShapeFactory.GraphAxis(this.shapeFactory, dvb, sets, xShapeInfo)); var xPx; // 图形点 x 坐标 var yPx; // 图形点 y 坐标 for (var i = 0, len = fv.length; i < len; i++) { // 数据溢出值域检查 if (fv[i] < codomain[0] || fv[i] > codomain[1]) { //isDataEffective = false; return null; } xPx = xsLoc[i]; yPx = dvb[1] - (fv[i] - codomain[0]) / uv; // 图形点参数对象 var poiSP = new Point_Point(xPx, yPx); // 图形点 style poiSP.style = ShapeFactory.ShapeStyleTool({fillColor: "#ee9900"}, sets.pointStyle, sets.pointStyleByFields, sets.pointStyleByCodomain, i, fv[i]); // 图形点 hover 样式 poiSP.highlightStyle = ShapeFactory.ShapeStyleTool(null, sets.pointHoverStyle); // 图形点 hover click if (typeof(sets.pointHoverAble) !== "undefined") { poiSP.hoverable = sets.pointHoverAble; } if (typeof(sets.pointClickAble) !== "undefined") { poiSP.clickable = sets.pointClickAble; } // 图形携带的数据信息 poiSP.refDataID = this.data.id; poiSP.dataInfo = { field: this.fields[i], value: fv[i] }; // 创建图形点并把此图形添加到图表图形数组 this.shapes.push(this.shapeFactory.createShape(poiSP)); } // 数据范围检测未通过,清空图形 // if (isDataEffective === false) { // this.shapes = []; // } // 重要步骤:将图形转为由相对坐标表示的图形,以便在地图平移缩放过程中快速重绘图形 // (统计专题图模块从结构上要求使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数) this.shapesConvertToRelativeCoordinate(); } /** * @function FeatureThemePoint.prototype.calculateXShapeInfo * @description 计算 X 轴方向上的图形信息,此信息是一个对象,包含两个属性, * 属性 xPositions 是一个一维数组,该数组元素表示图形在 x 轴方向上的像素坐标值, * 如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。 * width 表示图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 * 本函数中图形配置对象 setting 可设属性:
* xShapeBlank - {Array.} 水平方向上的图形空白间隔参数。 * 长度为 2 的数组,第一元素表示第折线左端点与数据视图框左端的空白间距,第二个元素表示折线右端点右端与数据视图框右端端的空白间距 。 * @returns {Object} 如果计算失败,返回 null;如果计算成功,返回 X 轴方向上的图形信息,此信息是一个对象,包含以下两个属性:
* xPositions - {Array.} 表示图形在 x 轴方向上的像素坐标值,如果图形在 x 方向上有一定宽度,通常取图形在 x 方向上的中心点为图形在 x 方向上的坐标值。 * width - {number}表示图形的宽度(特别注意:点的宽度始终为 0,而不是其直径)。 */ calculateXShapeInfo() { var dvb = this.dataViewBox; // 数据视图框 var sets = this.setting; // 图表配置对象 var fvc = this.dataValues.length; // 数组值个数 if (fvc < 1) { return null; } var xBlank; // x 轴空白间隔参数 var xShapePositions = []; // x 轴上图形的位置 var xShapeWidth = 0; // x 轴上图形宽度(自适应) var dvbWidth = this.DVBWidth; // 数据视图框宽度 var unitOffset = 0; // 单位偏移量 // x 轴空白间隔参数处理 if (sets.xShapeBlank && sets.xShapeBlank.length && sets.xShapeBlank.length == 2) { xBlank = sets.xShapeBlank; var xsLen = dvbWidth - (xBlank[0] + xBlank[1]); if (xsLen <= fvc) { return null; } unitOffset = xsLen / (fvc - 1); } else { // 默认使用等距离空白间隔,空白间隔为图形宽度 unitOffset = dvbWidth / (fvc + 1); xBlank = [unitOffset, unitOffset, unitOffset]; } // 图形 x 轴上的位置计算 var xOffset = 0 for (var i = 0; i < fvc; i++) { if (i == 0) { xOffset = xBlank[0]; } else { xOffset += unitOffset; } xShapePositions.push(dvb[0] + xOffset); } return { "xPositions": xShapePositions, "width": xShapeWidth }; } } ;// CONCATENATED MODULE: ./src/common/overlay/Ring.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemeRing * @aliasclass Feature.Theme.Ring * @deprecatedclass SuperMap.Feature.Theme.Ring * @classdesc 环状图。 * @category Visualization Theme * @description 基于路由对象计算指定点 M 值操作的参数类。通过该类提供参数信息。 * @param {FeatureVector} data - 用户数据。 * @param {SuperMap.Layer.Graph} layer - 此专题要素所在图层。 * @param {Array.} fields - data 中的参与此图表生成的字段名称。 * @param {FeatureThemeRing.setting} setting - 图表配置对象。 * @param {LonLat} [lonlat] - 专题要素地理位置。默认为 data 指代的地理要素 Bounds 中心。 * @example * // sectorStyleByCodomain 的每个元素是个包含值域信息和与值域对应样式信息的对象,该对象(必须)有三个属性: * // start: 值域值下限(包含); * // end: 值域值上限(不包含); * // style: 数据可视化图形的 style,这个样式对象的可设属性: 。 * // sectorStyleByCodomain 数组形如: * [ * { * start:0, * end:250, * style:{ * fillColor:"#00CD00" * } * }, * { * start:250, * end:500, * style:{ * fillColor:"#00EE00" * } * }, * { * start:500, * end:750, * style:{ * fillColor:"#00FF7F" * } * }, * { * start:750, * end:1500, * style:{ * fillColor:"#00FF00" * } * } * ] * @param {Object} [sectorHoverStyle=true] - 环状图扇形 hover 状态时的样式,sectorHoverAble 为 true 时有效。 * @param {boolean} [sectorHoverAble=true] - 是否允许环状图扇形使用 hover 状态。同时设置 sectorHoverAble 和 sectorClickAble 为 false,可以直接屏蔽环状图扇形对专题图层事件的响应。 * @param {boolean} [sectorClickAble=true] - 是否允许环状图扇形被点击。同时设置 sectorHoverAble 和 sectorClickAble 为 false,可以直接屏蔽环状图扇形对专题图层事件的响应。 * * @extends FeatureThemeGraph * @usage * @private */ class Ring extends Graph { constructor(data, layer, fields, setting, lonlat) { super(data, layer, fields, setting, lonlat); this.CLASS_NAME = "SuperMap.Feature.Theme.Ring"; } /** * @function FeatureThemeRing.prototype.destroy * @description 销毁此专题要素。调用 destroy 后此对象所以属性置为 null。 */ destroy() { super.destroy(); } /** * @function FeatureThemeRing.prototype.assembleShapes * @description 装配图形(扩展接口)。 */ assembleShapes() { // 重要步骤:初始化参数 if (!this.initBaseParameter()) { return; } // 一个默认 style 组 var defaultStyleGroup = [ {fillColor: "#ff9277"}, {fillColor: "#dddd00"}, {fillColor: "#ffc877"}, {fillColor: "#bbe3ff"}, {fillColor: "#d5ffbb"}, {fillColor: "#bbbbff"}, {fillColor: "#ddb000"}, {fillColor: "#b0dd00"}, {fillColor: "#e2bbff"}, {fillColor: "#ffbbe3"}, {fillColor: "#ff7777"}, {fillColor: "#ff9900"}, {fillColor: "#83dd00"}, {fillColor: "#77e3ff"}, {fillColor: "#778fff"}, {fillColor: "#c877ff"}, {fillColor: "#ff77ab"}, {fillColor: "#ff6600"}, {fillColor: "#aa8800"}, {fillColor: "#77c7ff"}, {fillColor: "#ad77ff"}, {fillColor: "#ff77ff"}, {fillColor: "#dd0083"}, {fillColor: "#777700"}, {fillColor: "#00aa00"}, {fillColor: "#0088aa"}, {fillColor: "#8400dd"}, {fillColor: "#aa0088"}, {fillColor: "#dd0000"}, {fillColor: "#772e00"} ]; // 图表配置对象 var sets = this.setting; // 背景框,默认不启用 if (sets.useBackground) { this.shapes.push(ShapeFactory.Background(this.shapeFactory, this.chartBox, sets)); } // 数据值数组 var fv = this.dataValues; if (fv.length < 1) { return; } // 没有数据 // 值域范围 var codomain = this.DVBCodomain; // 值域范围检测 for (let i = 0; i < fv.length; i++) { if (fv[i] < codomain[0] || fv[i] > codomain[1]) { return; } } // 值的绝对值总和 var valueSum = 0; for (let i = 0; i < fv.length; i++) { valueSum += Math.abs(fv[i]); } // 重要步骤:定义图表 FeatureThemeRing 数据视图框中单位值的含义,单位值:每度代表的数值 this.DVBUnitValue = 360 / valueSum; var uv = this.DVBUnitValue; var dvbCenter = this.DVBCenterPoint; // 数据视图框中心作为扇心 var startAngle = 0; // 扇形起始边角度 var endAngle = 0; // 扇形终止边角度 var startAngleTmp = startAngle; // 扇形临时起始边角度 // 扇形外环(自适应)半径 var r = this.DVBHeight < this.DVBWidth ? this.DVBHeight / 2 : this.DVBWidth / 2; // 扇形内环(自适应)半径 var isInRange = sets.innerRingRadius >= 0 && sets.innerRingRadius < r; var r0 = ( typeof(sets.innerRingRadius) !== "undefined" && !isNaN(sets.innerRingRadius) && isInRange ) ? sets.innerRingRadius : 0; for (var i = 0; i < fv.length; i++) { var fvi = Math.abs(fv[i]); // 计算结束角度 if (i === 0) { endAngle = startAngle + fvi * uv; } else if (i === fvi.length - 1) { endAngle = startAngleTmp; } else { endAngle = startAngle + fvi * uv; } // 扇形参数对象 var sectorSP = new Sector(dvbCenter[0], dvbCenter[1], r, startAngle, endAngle, r0); // 扇形样式 if (typeof(sets.sectorStyleByFields) === "undefined") { // 使用默认 style 组 var colorIndex = i % defaultStyleGroup.length; sectorSP.style = ShapeFactory.ShapeStyleTool(null, sets.sectorStyle, defaultStyleGroup, null, colorIndex); } else { sectorSP.style = ShapeFactory.ShapeStyleTool(null, sets.sectorStyle, sets.sectorStyleByFields, sets.sectorStyleByCodomain, i, fv[i]); } // 扇形 hover 样式 sectorSP.highlightStyle = ShapeFactory.ShapeStyleTool(null, sets.sectorHoverStyle); // 扇形 hover 与 click 设置 if (typeof(sets.sectorHoverAble) !== "undefined") { sectorSP.hoverable = sets.sectorHoverAble; } if (typeof(sets.sectorClickAble) !== "undefined") { sectorSP.clickable = sets.sectorClickAble; } // 图形携带的数据信息 sectorSP.refDataID = this.data.id; sectorSP.dataInfo = { field: this.fields[i], value: fv[i] }; // 创建扇形并把此扇形添加到图表图形数组 this.shapes.push(this.shapeFactory.createShape(sectorSP)); // 把上一次的结束角度作为下一次的起始角度 startAngle = endAngle; } // 重要步骤:将图形转为由相对坐标表示的图形,以便在地图平移缩放过程中快速重绘图形 // (统计专题图模块从结构上要求使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数) this.shapesConvertToRelativeCoordinate(); } } ;// CONCATENATED MODULE: ./src/common/overlay/ThemeVector.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureThemeVector * @aliasclass Feature.Theme.ThemeVector * @deprecatedclass SuperMap.Feature.Theme.ThemeVector * @classdesc 矢量专题要素类。 * @category Visualization Theme * @extends FeatureTheme * @param {FeatureVector} data - 用户数据,的类型为矢量数据 feature。 * @param {SuperMap.Layer} layer - 此专题要素所在图层。 * @param {Object} style - 样式。 * @param {Object} options - 创建专题要素时的可选参数。 * @param {number} [options.nodesClipPixel=2] - 节点抽稀像素距离,单位:像素。 * @param {boolean} [options.isHoverAble=true] - 图形是否可 hover。 * @param {boolean} [options.isMultiHover=true] - 是否使用多图形高亮,isHoverAble 为 true 时生效。 * @param {boolean} [options.isClickAble=true] - 图形是否可点击。 * @param {Object} [options.highlightStyle] - 高亮样式。 * @usage */ class ThemeVector extends Theme_Theme { constructor(data, layer, style, options, shapeOptions) { super(data, layer); //数据的 geometry 属性必须存在且类型是 Geometry 或其子类的类型 if (!data.geometry) { return; } if (!(data.geometry instanceof Geometry_Geometry)) { return; } /** * @member {Bounds} [FeatureThemeVector.prototype.dataBounds] * @description 用户数据的(feature.geometry)地理范围。 */ this.dataBounds = data.geometry.getBounds(); /** * @member {number} [FeatureThemeVector.prototype.nodesClipPixel=2] * @description 节点抽稀像素距离。 */ this.nodesClipPixel = 2; /** * @member {boolean} [FeatureThemeVector.prototype.isHoverAble=true] * @description 图形是否可 hover。 */ this.isHoverAble = true; /** * @member {boolean} [FeatureThemeVector.prototype.isMultiHover=true] * @description 是否使用多图形高亮,isHoverAble 为 true 时生效。 */ this.isMultiHover = true; /** * @member {boolean} [FeatureThemeVector.prototype.isClickAble=true] * @description 图形是否可点击。 */ this.isClickAble = true; /** * @member {Object} [FeatureThemeVector.prototype.highlightStyle] * @description 高亮样式。 */ this.highlightStyle = null; /** * @member {Object} [FeatureThemeVector.prototype.shapeOptions] * @description 添加到渲染器前修改 shape 的一些属性,非特殊情况通常不允许这么做。 */ this.shapeOptions = {}; /** * @member {Object} [FeatureThemeVector.prototype.style] * @description 可视化图形的 style。在子类中规定其对象结构和默认属性值。 */ this.style = style || {}; this.CLASS_NAME = "SuperMap.Feature.Theme.Vector"; this.style = style ? style : {}; if (options) { Util.copyAttributesWithClip(this, options, ["shapeOptions", "dataBounds"]) } if (shapeOptions) { Util.copyAttributesWithClip(this.shapeOptions, shapeOptions); } //设置基础参数 dataBounds、lonlat、location var geometry = data.geometry; this.lonlat = this.dataBounds.getCenterLonLat(); this.location = this.getLocalXY(this.lonlat); //将地理要素转为专题要素 if (geometry instanceof LinearRing) { this.lineToTF(geometry); } else if (geometry instanceof LineString) { this.lineToTF(geometry); } else if (geometry instanceof Curve) { //独立几何体 } else if (geometry instanceof MultiPoint) { this.multiPointToTF(geometry); } else if (geometry instanceof MultiLineString) { this.multiLineStringToTF(geometry); } else if (geometry instanceof MultiPolygon) { this.multiPolygonToTF(geometry); } else if (geometry instanceof Polygon) { this.polygonToTF(geometry); } else if (geometry instanceof Collection) { //独立几何体 } else if (geometry instanceof Point) { this.pointToTF(geometry); } else if (geometry instanceof Rectangle) { this.rectangleToTF(geometry); } else if (geometry instanceof GeoText) { this.geoTextToTF(geometry); } } /** * @function FeatureThemeVector.prototype.destroy * @override */ destroy() { this.style = null; this.dataBounds = null; this.nodesClipPixel = null; this.isHoverAble = null; this.isMultiHover = null; this.isClickAble = null; this.highlightStyle = null; this.shapeOptions = null; super.destroy(); } /** * @function FeatureThemeVector.prototype.lineToTF * @description 转换线和线环要素。 * @param {Geometry} geometry - 用户数据几何地理信息,这里必须是 GeometryLineString 或 GeometryLineRing。 */ lineToTF(geometry) { var components = geometry.components; //节点像素坐标 var localLX = []; //参考位置,参考中心为 var refLocal = []; var location = this.location; var pointList = []; //节点抽稀距离 var nCPx = this.nodesClipPixel; for (var i = 0; i < components.length; i++) { var components_i = components[i]; refLocal = []; localLX = this.getLocalXY(components_i); refLocal[0] = localLX[0] - location[0]; refLocal[1] = localLX[1] - location[1]; //抽稀 - 2 px if (pointList.length > 0) { var lastLocalXY = pointList[pointList.length - 1]; if ((Math.abs(lastLocalXY[0] - refLocal[0]) <= nCPx) && (Math.abs(lastLocalXY[1] - refLocal[1]) <= nCPx)) { continue; } } //使用参考点 pointList.push(refLocal); } if (pointList.length < 2) { return null; } //赋 style var style = new Object(); style = Util.copyAttributesWithClip(style, this.style, ['pointList']); style.pointList = pointList; //创建图形 var shape = new SmicBrokenLine({ style: style, clickable: this.isClickAble, hoverable: this.isHoverAble }); //设置高亮样式 if (this.highlightStyle) { shape.highlightStyle = this.highlightStyle; } //设置参考中心,指定图形位置 shape.refOriginalPosition = this.location; //储存数据 id 属性,用于事件 shape.refDataID = this.data.id; //储存数据 id 属性,用于事件-多图形同时高亮 shape.isHoverByRefDataID = this.isMultiHover; //添加到渲染器前修改 shape 的一些属性,非特殊情况通常不允许这么做 if (this.shapeOptions) { Util.copyAttributesWithClip(shape, this.shapeOptions); } this.shapes.push(shape); } /** * @function FeatureThemeVector.prototype.multiPointToTF * @description 转多点要素。 * @param {Geometry} geometry - 用户数据几何地理信息,这里必须是 MultiPoint。 */ multiPointToTF(geometry) { /* //-- 不抽稀 var components = geometry.components; for(var i = 0; i < components.length; i++){ var components_i = components[i]; this.pointToTF(components_i); } */ var components = geometry.components; //节点像素坐标 var localLX = []; //参考位置,参考中心为 var refLocal = []; var location = this.location; var pointList = []; //节点抽稀距离 var nCPx = this.nodesClipPixel; for (var i = 0; i < components.length; i++) { var components_i = components[i]; refLocal = []; localLX = this.getLocalXY(components_i); refLocal[0] = localLX[0] - location[0]; refLocal[1] = localLX[1] - location[1]; //抽稀 if (pointList.length > 0) { var lastLocalXY = pointList[pointList.length - 1]; if ((Math.abs(lastLocalXY[0] - refLocal[0]) <= nCPx) && (Math.abs(lastLocalXY[1] - refLocal[1]) <= nCPx)) { continue; } } //使用参考点 pointList.push(refLocal); //赋 style var style = new Object(); style.r = 6; //防止漏设此参数,默认 6 像素 style = Util.copyAttributesWithClip(style, this.style); style.x = refLocal[0]; style.y = refLocal[1]; //创建图形 var shape = new SmicPoint({ style: style, clickable: this.isClickAble, hoverable: this.isHoverAble }); //设置高亮样式 if (this.highlightStyle) { shape.highlightStyle = this.highlightStyle; } //设置参考中心,指定图形位置 shape.refOriginalPosition = location; //储存数据 id 属性,用于事件 shape.refDataID = this.data.id; //储存数据 id 属性,用于事件-多图形同时高亮 shape.isHoverByRefDataID = this.isMultiHover; //修改一些 shape 可选属性,通常不需要这么做 if (this.shapeOptions) { Util.copyAttributesWithClip(shape, this.shapeOptions); } this.shapes.push(shape); } } /** * @function FeatureThemeVector.prototype.multiLineStringToTF * @description 转换多线要素。 * @param {Geometry} geometry - 用户数据几何地理信息,这里必须是 MultiLineString。 */ multiLineStringToTF(geometry) { var components = geometry.components; for (var i = 0; i < components.length; i++) { var components_i = components[i]; this.lineToTF(components_i); } } /** * @function FeatureThemeVector.prototype.multiPolygonToTF * @description 转换多面要素。 * @param {Geometry} geometry - 用户数据几何地理信息,这里必须是 MultiPolygon。 */ multiPolygonToTF(geometry) { var components = geometry.components; for (var i = 0; i < components.length; i++) { var components_i = components[i]; this.polygonToTF(components_i); } } /** * @function FeatureThemeVector.prototype.pointToTF * @description 转换点要素。 * @param {Geometry} geometry - 用户数据几何地理信息,这里必须是 Point。 */ pointToTF(geometry) { //参考位置,参考中心为 var location = this.location; //geometry 像素坐标 var localLX = this.getLocalXY(geometry); //赋 style var style = new Object(); style.r = 6; //防止漏设此参数,默认 6 像素 style = Util.copyAttributesWithClip(style, this.style); style.x = localLX[0] - location[0]; style.y = localLX[1] - location[1]; //创建图形 var shape = new SmicPoint({ style: style, clickable: this.isClickAble, hoverable: this.isHoverAble }); //设置高亮样式 if (this.highlightStyle) { shape.highlightStyle = this.highlightStyle; } //设置参考中心,指定图形位置 shape.refOriginalPosition = location; //储存数据 id 属性,用于事件 shape.refDataID = this.data.id; //储存数据 id 属性,用于事件-多图形同时高亮 shape.isHoverByRefDataID = this.isMultiHover; //修改一些 shape 可选属性,通常不需要这么做 if (this.shapeOptions) { Util.copyAttributesWithClip(shape, this.shapeOptions); } this.shapes.push(shape); } /** * @function FeatureThemeVector.prototype.polygonToThemeFeature * @description 转换面要素。 * @param {Geometry} geometry - 用户数据几何地理信息,这里必须是 Polygon。 */ polygonToTF(geometry) { var components = geometry.components; //节点像素坐标 var localLX = []; //参考位置,参考中心为 var refLocal = []; var location = this.location; var pointList = []; //岛洞 var holePolygonPointList = []; var holePolygonPointLists = []; //节点抽稀距离 var nCPx = this.nodesClipPixel; for (var i = 0; i < components.length; i++) { var components_i = components[i].components; if (i === 0) { // 第一个 component 正常绘制 pointList = []; for (var j = 0; j < components_i.length; j++) { refLocal = []; localLX = this.getLocalXY(components_i[j]); refLocal[0] = localLX[0] - location[0]; refLocal[1] = localLX[1] - location[1]; //抽稀 - 2 px if (pointList.length > 0) { var lastLocalXY = pointList[pointList.length - 1]; if ((Math.abs(lastLocalXY[0] - refLocal[0]) <= nCPx) && (Math.abs(lastLocalXY[1] - refLocal[1]) <= nCPx)) { continue; } } //使用参考点 pointList.push(refLocal); } } else { // 其它 component 作为岛洞 holePolygonPointList = []; for (var k = 0; k < components_i.length; k++) { refLocal = []; localLX = this.getLocalXY(components_i[k]); refLocal[0] = localLX[0] - location[0]; refLocal[1] = localLX[1] - location[1]; //抽稀 - 2 px if (holePolygonPointList.length > 0) { var lastXY = holePolygonPointList[holePolygonPointList.length - 1]; if ((Math.abs(lastXY[0] - refLocal[0]) <= nCPx) && (Math.abs(lastXY[1] - refLocal[1]) <= nCPx)) { continue; } } //使用参考点 holePolygonPointList.push(refLocal); } } if (holePolygonPointList.length < 2) { continue; } holePolygonPointLists.push(holePolygonPointList); } if (pointList.length < 2) { return; } //赋 style var style = {}; style = Util.copyAttributesWithClip(style, this.style, ['pointList']); style.pointList = pointList; //创建图形 var shape = new SmicPolygon({ style: style, clickable: this.isClickAble, hoverable: this.isHoverAble }); //设置高亮样式 if (this.highlightStyle) { shape.highlightStyle = this.highlightStyle; } //设置参考中心,指定图形位置 shape.refOriginalPosition = this.location; //储存数据 id 属性,用于事件 shape.refDataID = this.data.id; //储存数据 id 属性,用于事件-多图形同时高亮 shape.isHoverByRefDataID = this.isMultiHover; //岛洞面 if (holePolygonPointLists.length > 0) { shape.holePolygonPointLists = holePolygonPointLists; } //修改一些 shape 可选属性,通常不需要这么做 if (this.shapeOptions) { Util.copyAttributesWithClip(shape, this.shapeOptions); } this.shapes.push(shape); } /** * @function FeatureThemeVector.prototype.rectangleToTF * @description 转换矩形要素。 * @param {Geometry} geometry - 用户数据几何地理信息,这里必须是 Rectangle。 */ rectangleToTF(geometry) { //参考位置,参考中心为 var location = this.location; var ll = new LonLat(geometry.x, geometry.y); //地图分辨率 var res = this.layer.map.getResolution(); //geometry 像素坐标 var localLX = this.getLocalXY(ll); //赋 style var style = new Object(); style.r = 6; //防止漏设此参数,默认 6 像素 style = Util.copyAttributesWithClip(style, this.style); style.x = localLX[0] - location[0]; // Rectangle 使用左下角定位, SmicRectangle 使用左上角定位,需要转换 style.y = (localLX[1] - location[1]) - 2 * geometry.width / res; style.width = geometry.width / res; style.height = geometry.height / res; //创建图形 var shape = new SmicRectangle({ style: style, clickable: this.isClickAble, hoverable: this.isHoverAble }); //设置高亮样式 if (this.highlightStyle) { shape.highlightStyle = this.highlightStyle; } //设置参考中心,指定图形位置 shape.refOriginalPosition = location; //储存数据 id 属性,用于事件 shape.refDataID = this.data.id; //储存数据 id 属性,用于事件-多图形同时高亮 shape.isHoverByRefDataID = this.isMultiHover; //修改一些 shape 可选属性,通常不需要这么做 if (this.shapeOptions) { Util.copyAttributesWithClip(shape, this.shapeOptions); } this.shapes.push(shape); } /** * @function FeatureThemeVector.prototype.geoTextToTF * @description 转换文本要素。 * @param {Geometry} geometry - 用户数据几何地理信息,这里必须是 GeoText。 */ geoTextToTF(geometry) { //参考位置,参考中心为 var location = this.location; //geometry 像素坐标 var localLX = this.getLocalXY(geometry); //赋 style var style = new Object(); style.r = 6; //防止漏设此参数,默认 6 像素 style = Util.copyAttributesWithClip(style, this.style, ["x", "y", "text"]); style.x = localLX[0] - location[0]; style.y = localLX[1] - location[1]; style.text = geometry.text; //创建图形 var shape = new SmicText({ style: style, clickable: this.isClickAble, hoverable: this.isHoverAble }); //设置高亮样式 if (this.highlightStyle) { shape.highlightStyle = this.highlightStyle; } //设置参考中心,指定图形位置 shape.refOriginalPosition = location; //储存数据 id 属性,用于事件 shape.refDataID = this.data.id; //储存数据 id 属性,用于事件-多图形同时高亮 shape.isHoverByRefDataID = this.isMultiHover; //修改一些 shape 可选属性,通常不需要这么做 if (this.shapeOptions) { Util.copyAttributesWithClip(shape, this.shapeOptions); } this.shapes.push(shape); } /** * @function FeatureThemeVector.prototype.updateAndAddShapes * @description 修改位置,针对地图平移操作,地图漫游操作后调用此函数。 */ updateAndAddShapes() { var newLocalLX = this.getLocalXY(this.lonlat); this.location = newLocalLX; var render = this.layer.renderer; for (var i = 0, len = this.shapes.length; i < len; i++) { var shape = this.shapes[i]; //设置参考中心,指定图形位置 shape.refOriginalPosition = newLocalLX; render.addShape(shape); } } /** * @function FeatureThemeVector.prototype.getShapesCount * @description 获得专题要素中可视化图形的数量。 * @returns {number} 可视化图形的数量。 */ getShapesCount() { return this.shapes.length; } /** * @function FeatureThemeVector.prototype.getLocalXY * @description 地理坐标转为像素坐标。 * @param {LonLat} lonlat - 专题要素地理位置。 */ getLocalXY(lonlat) { return this.layer.getLocalXY(lonlat); } } ;// CONCATENATED MODULE: ./src/common/overlay/feature/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Group.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Group * @category Visualization Theme * @private * @classdesc Group 是一个容器,可以插入子节点,Group 的变换也会被应用到子节点上。 * @extends {LevelRenderer.Transformable} * (code) * var g = new LevelRenderer.Group(); * var Circle = new LevelRenderer.Shape.Circle(); * g.position[0] = 100; * g.position[1] = 100; * g.addChild(new Circle({ * style: { * x: 100, * y: 100, * r: 20, * brushType: 'fill' * } * })); * LR.addGroup(g); * (end) * @param {Array} options - Group 的配置(options)项,可以是 Group 的自有属性,也可以是自定义的属性。 */ class Group extends mixinExt(Eventful, Transformable) { constructor(options) { super(options) options = options || {}; /** * @member {string} LevelRenderer.Group.prototype.id * @description Group 的唯一标识。 */ this.id = null; /** * @readonly * @member {string} [LevelRenderer.Group.prototype.type='group'] * @description 类型。 */ this.type = 'group'; //http://www.w3.org/TR/2dcontext/#clipping-region /** * @member {string} LevelRenderer.Group.prototype.clipShape * @description 用于裁剪的图形(shape),所有 Group 内的图形在绘制时都会被这个图形裁剪,该图形会继承 Group 的变换。 */ this.clipShape = null; /** * @member {Array} LevelRenderer.Group.prototype._children * @description _children。 */ this._children = []; /** * @member {Array} LevelRenderer.Group.prototype._storage * @description _storage。 */ this._storage = null; /** * @member {boolean} [LevelRenderer.Group.prototype.__dirty=true] * @description __dirty。 */ this.__dirty = true; /** * @member {boolean} [LevelRenderer.Group.prototype.ignore=false] * @description 是否忽略该 Group 及其所有子节点。 */ this.ignore = false; Util.extend(this, options); this.id = this.id || Util.createUniqueID("smShapeGroup_"); this.CLASS_NAME = "SuperMap.LevelRenderer.Group"; } /** * @function LevelRenderer.Group.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.id = null; this.type = null; this.clipShape = null; this._children = null; this._storage = null; this.__dirty = null; this.ignore = null; super.destroy(); } /** * @function LevelRenderer.Group.prototype.children * @description 复制并返回一份新的包含所有儿子节点的数组。 * @returns {Array.} 图形数组。 */ children() { return this._children.slice(); } /** * @function LevelRenderer.Group.prototype.childAt * @description 获取指定 index 的儿子节点 * @param {number} idx - 节点索引。 * @returns {LevelRenderer.Shape} 图形。 */ childAt(idx) { return this._children[idx]; } /** * @function LevelRenderer.Group.prototype.addChild * @description 添加子节点,可以是 Shape 或者 Group。 * @param {(LevelRenderer.Shape|LevelRenderer.Group)} child - 节点图形。 */ // TODO Type Check addChild(child) { if (child == this) { return; } if (child.parent == this) { return; } if (child.parent) { child.parent.removeChild(child); } this._children.push(child); child.parent = this; if (this._storage && this._storage !== child._storage) { this._storage.addToMap(child); if (child instanceof Group) { child.addChildrenToStorage(this._storage); } } } /** * @function LevelRenderer.Group.prototype.removeChild * @description 移除子节点。 * @param {LevelRenderer.Shape} child - 需要移除的子节点图形。 */ removeChild(child) { var idx = Util.indexOf(this._children, child); this._children.splice(idx, 1); child.parent = null; if (this._storage) { this._storage.delFromMap(child.id); if (child instanceof Group) { child.delChildrenFromStorage(this._storage); } } } /** * @function LevelRenderer.Group.prototype.eachChild * @description 遍历所有子节点。 * @param {function} cb - 回调函数。 * @param {Object} context - 上下文。 */ eachChild(cb, context) { var haveContext = !!context; for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; if (haveContext) { cb.call(context, child); } else { cb(child); } } } /** * @function LevelRenderer.Group.prototype.traverse * @description 深度优先遍历所有子孙节点。 * @param {function} cb - 回调函数。 * @param {Object} context - 上下文。 */ traverse(cb, context) { var haveContext = !!context; for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; if (haveContext) { cb.call(context, child); } else { cb(child); } if (child.type === 'group') { child.traverse(cb, context); } } } /** * @function LevelRenderer.Group.prototype.addChildrenToStorage * @description 把子图形添加到仓库。 * @param {LevelRenderer.Storage} storage - 图形仓库。 */ addChildrenToStorage(storage) { for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; storage.addToMap(child); if (child.type === 'group') { child.addChildrenToStorage(storage); } } } /** * @function LevelRenderer.Group.prototype.delChildrenFromStorage * @description 从仓库把子图形删除。 * @param {LevelRenderer.Storage} storage - 图形仓库。 */ delChildrenFromStorage(storage) { for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; storage.delFromMap(child.id); if (child.type === 'group') { child.delChildrenFromStorage(storage); } } } /** * @function LevelRenderer.Group.prototype.modSelf * @description 是否修改。 */ modSelf() { this.__dirty = true; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Storage.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Storage * @category Visualization Theme * @classdesc 内容(图像)仓库 (M) 。 */ class Storage { constructor() { /** * @member {Object} LevelRenderer.Storage.prototype._elements * @description 所有常规形状,id 索引的 map。 */ this._elements = {}; /** * @member {Array} LevelRenderer.Storage.prototype._hoverElements * @description 高亮层形状,不稳定,动态增删,数组位置也是 z 轴方向,靠前显示在下方。 * */ this._hoverElements = []; /** * @member {Array} LevelRenderer.Storage.prototype._roots * @description _roots。 * */ this._roots = []; /** * @member {Array} LevelRenderer.Storage.prototype._shapeList * @description _shapeList。 * */ this._shapeList = []; /** * @member {number} LevelRenderer.Storage.prototype._shapeListOffset * @description _shapeListOffset。默认值:0。 * */ this._shapeListOffset = 0; this.CLASS_NAME = "SuperMap.LevelRenderer.Storage"; } /** * @function LevelRenderer.Storage.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.dispose(); this._shapeList = null; this._shapeListOffset = null; } /** * @function LevelRenderer.Storage.prototype.iterShape * @description 遍历迭代器。 * * @param {function} fun - 迭代回调函数,return true终止迭代。 * @param {Object} option - 迭代参数,缺省为仅降序遍历普通层图形。 * @param {boolean} [hover=true] - 是否是高亮层图形。 * @param {string} [normal='down'] - 是否是普通层图形,迭代时是否指定及z轴顺序。可设值:'down' ,'up'。 * @param {boolean} [update=false] - 是否在迭代前更新形状列表。 * @return {LevelRenderer.Storage} this。 */ iterShape(fun, option) { if (!option) { var defaultIterateOption = { hover: false, normal: 'down', update: false }; option = defaultIterateOption; } if (option.hover) { // 高亮层数据遍历 for (var i = 0, l = this._hoverElements.length; i < l; i++) { var el = this._hoverElements[i]; el.updateTransform(); if (fun(el)) { return this; } } } if (option.update) { this.updateShapeList(); } // 遍历: 'down' | 'up' switch (option.normal) { case 'down': { // 降序遍历,高层优先 let l = this._shapeList.length; while (l--) { if (fun(this._shapeList[l])) { return this; } } break; } // case 'up': default: { // 升序遍历,底层优先 for (let i = 0, l = this._shapeList.length; i < l; i++) { if (fun(this._shapeList[i])) { return this; } } break; } } return this; } /** * @function LevelRenderer.Storage.prototype.getHoverShapes * @param {boolean} [update=false] - 是否在返回前更新图形的变换。 * @return {Array.} 图形数组。 */ getHoverShapes(update) { // hoverConnect var hoverElements = [], len = this._hoverElements.length; for (let i = 0; i < len; i++) { hoverElements.push(this._hoverElements[i]); var target = this._hoverElements[i].hoverConnect; if (target) { var shape; target = target instanceof Array ? target : [target]; for (var j = 0, k = target.length; j < k; j++) { shape = target[j].id ? target[j] : this.get(target[j]); if (shape) { hoverElements.push(shape); } } } } hoverElements.sort(Storage.shapeCompareFunc); if (update) { for (let i = 0, l = hoverElements.length; i < l; i++) { hoverElements[i].updateTransform(); } } return hoverElements; } /** * @function LevelRenderer.Storage.prototype.getShapeList * @description 返回所有图形的绘制队列。 * * @param {boolean} [update=false] - 是否在返回前更新该数组。详见: updateShapeList。 * @return {LevelRenderer.Shape} 图形。 */ getShapeList(update) { if (update) { this.updateShapeList(); } return this._shapeList; } /** * @function LevelRenderer.Storage.prototype.updateShapeList * @description 更新图形的绘制队列。每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列。 */ updateShapeList() { this._shapeListOffset = 0; var rootsLen = this._roots.length; for (let i = 0; i < rootsLen; i++) { let root = this._roots[i]; this._updateAndAddShape(root); } this._shapeList.length = this._shapeListOffset; var shapeListLen = this._shapeList.length; for (let i = 0; i < shapeListLen; i++) { this._shapeList[i].__renderidx = i; } this._shapeList.sort(Storage.shapeCompareFunc); } /** * @function LevelRenderer.Storage.prototype._updateAndAddShape * @description 更新并添加图形。 * */ _updateAndAddShape(el, clipShapes) { if (el.ignore) { return; } el.updateTransform(); if (el.type == 'group') { if (el.clipShape) { // clipShape 的变换是基于 group 的变换 el.clipShape.parent = el; el.clipShape.updateTransform(); // PENDING 效率影响 if (clipShapes) { clipShapes = clipShapes.slice(); clipShapes.push(el.clipShape); } else { clipShapes = [el.clipShape]; } } for (var i = 0; i < el._children.length; i++) { var child = el._children[i]; // Force to mark as dirty if group is dirty child.__dirty = el.__dirty || child.__dirty; this._updateAndAddShape(child, clipShapes); } // Mark group clean here el.__dirty = false; } else { el.__clipShapes = clipShapes; this._shapeList[this._shapeListOffset++] = el; } } /** * @function LevelRenderer.Storage.prototype.mod * @description 修改图形(Shape)或者组(Group)。 * * @param {string} elId - 唯一标识。 * @param {Object} params - 参数。 * @return {LevelRenderer.Storage} this。 */ mod(elId, params) { var el = this._elements[elId]; if (el) { el.modSelf(); if (params) { // 如果第二个参数直接使用 shape // parent, _storage, __startClip 三个属性会有循环引用 // 主要为了向 1.x 版本兼容,2.x 版本不建议使用第二个参数 if (params.parent || params._storage || params.__startClip) { var target = {}; for (var name in params) { if ( name == 'parent' || name == '_storage' || name == '__startClip' ) { continue; } if (params.hasOwnProperty(name)) { target[name] = params[name]; } } new Util_Util().merge(el, target, true); } else { new Util_Util().merge(el, params, true); } } } return this; } /** * @function LevelRenderer.Storage.prototype.drift * @description 移动指定的图形(Shape)的位置。 * @param {string} shapeId - 唯一标识。 * @param {number} dx * @param {number} dy * @return {LevelRenderer.Storage} this。 */ drift(shapeId, dx, dy) { var shape = this._elements[shapeId]; if (shape) { shape.needTransform = true; if (shape.draggable === 'horizontal') { dy = 0; } else if (shape.draggable === 'vertical') { dx = 0; } if (!shape.ondrift // ondrift // 有onbrush并且调用执行返回false或undefined则继续 || (shape.ondrift && !shape.ondrift(dx, dy)) ) { shape.drift(dx, dy); } } return this; } /** * @function LevelRenderer.Storage.prototype.addHover * @description 添加高亮层数据。 * @param {LevelRenderer.Shape} shape - 图形。 * @return {LevelRenderer.Storage} this。 */ addHover(shape) { shape.updateNeedTransform(); this._hoverElements.push(shape); return this; } /** * @function LevelRenderer.Storage.prototype.delHover * @description 清空高亮层数据。 * @return {LevelRenderer.Storage} this。 */ delHover() { this._hoverElements = []; return this; } /** * @function LevelRenderer.Storage.prototype.hasHoverShape * @description 是否有图形在高亮层里。 * @return {boolean} 是否有图形在高亮层里。 */ hasHoverShape() { return this._hoverElements.length > 0; } /** * @function LevelRenderer.Storage.prototype.addRoot * @description 添加图形(Shape)或者组(Group)到根节点。 * * @param {(LevelRenderer.Shape/LevelRenderer.Group)} el - 图形。 * */ addRoot(el) { if (el instanceof Group) { el.addChildrenToStorage(this); } this.addToMap(el); this._roots.push(el); } /** * @function LevelRenderer.Storage.prototype.delRoot * @description 删除指定的图形(Shape)或者组(Group)。 * * @param {Array.} elId - 删除图形(Shape)或者组(Group)的 ID 数组。如果为空清空整个Storage。 * */ delRoot(elId) { if (typeof(elId) == 'undefined') { // 不指定elId清空 for (var i = 0; i < this._roots.length; i++) { var root = this._roots[i]; if (root instanceof Group) { root.delChildrenFromStorage(this); } } this._elements = {}; this._hoverElements = []; this._roots = []; return; } if (elId instanceof Array) { var elIdLen = elId.length; for (let i = 0; i < elIdLen; i++) { this.delRoot(elId[i]); } return; } var el; if (typeof(elId) == 'string') { el = this._elements[elId]; } else { el = elId; } var idx = new Util_Util().indexOf(this._roots, el); if (idx >= 0) { this.delFromMap(el.id); this._roots.splice(idx, 1); if (el instanceof Group) { el.delChildrenFromStorage(this); } } } /** * @function LevelRenderer.Storage.prototype.addToMap * @description 添加图形到 map。 * * @param {LevelRenderer.Shape} el - 图形。 * @return {LevelRenderer.Storage} this。 */ addToMap(el) { if (el instanceof Group) { el._storage = this; } el.modSelf(); this._elements[el.id] = el; return this; } /** * @function LevelRenderer.Storage.prototype.get * @description 获取指定图形。 * * @param {string} elId - 图形 id。 * @return {LevelRenderer.Shape} 图形。 */ get(elId) { return this._elements[elId]; } /** * @function LevelRenderer.Storage.prototype.delFromMap * @description 从 map 中删除指定图形。 * * @param {string} elId - 图形id。 * @return {LevelRenderer.Storage} this。 */ delFromMap(elId) { var el = this._elements[elId]; if (el) { delete this._elements[elId]; if (el instanceof Group) { el._storage = null; } } return this; } /** * @function LevelRenderer.Storage.prototype.dispose * @description 清空并且释放 Storage。 */ dispose() { this._elements = null; // this._renderList = null; this._roots = null; this._hoverElements = null; } static shapeCompareFunc(a, b) { if (a.zlevel == b.zlevel) { if (a.z == b.z) { return a.__renderidx - b.__renderidx; } return a.z - b.z; } return a.zlevel - b.zlevel; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Painter.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Painter * @category Visualization Theme * @classdesc Painter 绘图模块。 * @param {HTMLElement} root - 绘图区域(DIV)。 * @param {LevelRenderer.Storage} storage - Storage 实例。 */ class Painter { constructor(root, storage) { /** * @member {HTMLElement} LevelRenderer.Painter.prototype.root * @description 绘图容器。 * */ this.root = root; /** * @member {Array} LevelRenderer.Painter.prototype.storage * @description 图形仓库。 * */ this.storage = storage; /** * @member {HTMLElement} LevelRenderer.Painter.prototype._domRoot * @description 容器根 dom 对象。 * */ this._domRoot = null; /** * @member {Object} LevelRenderer.Painter.prototype._layers * @description 绘制层对象。 * */ this._layers = {}; /** * @member {Array} LevelRenderer.Painter.prototype._zlevelList * @description 层列表。 * */ this._zlevelList = []; /** * @member {Object} LevelRenderer.Painter.prototype._layerConfig * @description 绘制层配置对象。 * */ this._layerConfig = {}; /** * @member {Object} LevelRenderer.Painter.prototype._bgDom * @description 背景层 Canvas (Dom)。 * */ this._bgDom = null; /** * @member {function} LevelRenderer.Painter.prototype.shapeToImage * @description 形状转图像函数。 * */ this.shapeToImage = null; // retina 屏幕优化 Painter.devicePixelRatio = Math.max((window.devicePixelRatio || 1), 1); this.CLASS_NAME = "SuperMap.LevelRenderer.Painter"; this.root.innerHTML = ''; this._width = this._getWidth(); // 宽,缓存记录 this._height = this._getHeight(); // 高,缓存记录 var domRoot = document.createElement('div'); this._domRoot = domRoot; // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬 domRoot.style.position = 'relative'; domRoot.style.overflow = 'hidden'; domRoot.style.width = this._width + 'px'; domRoot.style.height = this._height + 'px'; this.root.appendChild(domRoot); this.shapeToImage = this._createShapeToImageProcessor(); // 创建各层canvas // 背景 //this._bgDom = Painter.createDom('bg', 'div', this); this._bgDom = Painter.createDom(Util.createUniqueID("SuperMap.Theme_background_"), 'div', this); domRoot.appendChild(this._bgDom); this._bgDom.onselectstart = returnFalse; this._bgDom.style['-webkit-user-select'] = 'none'; this._bgDom.style['user-select'] = 'none'; this._bgDom.style['-webkit-touch-callout'] = 'none'; // 高亮 //var hoverLayer = new PaintLayer('_hoverLayer_', this); var hoverLayer = new PaintLayer(Util.createUniqueID("_highLightLayer_"), this); this._layers['hover'] = hoverLayer; domRoot.appendChild(hoverLayer.dom); hoverLayer.initContext(); hoverLayer.dom.onselectstart = returnFalse; hoverLayer.dom.style['-webkit-user-select'] = 'none'; hoverLayer.dom.style['user-select'] = 'none'; hoverLayer.dom.style['-webkit-touch-callout'] = 'none'; var me = this; this.updatePainter = function (shapeList, callback) { me.refreshShapes(shapeList, callback); }; // 返回false的方法,用于避免页面被选中 function returnFalse() { return false; } /* eslint-disable */ // 什么都不干的空方法 function doNothing() { //NOSONAR } /* eslint-enable */ } /** * @function LevelRenderer.Painter.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.dispose(); this._zlevelList = null; this._layerConfig = null; this._bgDom = null; this.shapeToImage = null; } /** * @function LevelRenderer.Painter.prototype.render * @description 渲染。首次绘图,创建各种 dom 和 context。 * * @param {function} callback - 绘画结束后的回调函数。 * @return {LevelRenderer.Painter} this。 */ render(callback) { // TODO this.refresh(callback, true); return this; } /** * @function LevelRenderer.Painter.prototype.refresh * @description 刷新。 * * @param {function} callback - 刷新结束后的回调函数。 * @param {boolean} paintAll - 强制绘制所有 shape。 * @return {LevelRenderer.Painter} this。 */ refresh(callback, paintAll) { var list = this.storage.getShapeList(true); this._paintList(list, paintAll); if (typeof callback == 'function') { callback(); } return this; } /** * Method: _paintList * 按列表绘制图形。 */ _paintList(list, paintAll) { if (typeof(paintAll) == 'undefined') { paintAll = false; } this._updateLayerStatus(list); var currentLayer; var currentZLevel; var ctx; for (var id in this._layers) { if (id !== 'hover') { this._layers[id].unusedCount++; this._layers[id].updateTransform(); } } var invTransform = []; for (var i = 0, l = list.length; i < l; i++) { var shape = list[i]; if (currentZLevel !== shape.zlevel) { if (currentLayer && currentLayer.needTransform) { ctx.restore(); } currentLayer = this.getLayer(shape.zlevel); ctx = currentLayer.ctx; currentZLevel = shape.zlevel; // Reset the count currentLayer.unusedCount = 0; if (currentLayer.dirty || paintAll) { currentLayer.clear(); } if (currentLayer.needTransform) { ctx.save(); currentLayer.setTransform(ctx); } } // Start group clipping if (ctx && shape.__startClip) { var clipShape = shape.__startClip; ctx.save(); // Set transform if (clipShape.needTransform) { let m = clipShape.transform; SUtil_SUtil.Util_matrix.invert(invTransform, m); ctx.transform( m[0], m[1], m[2], m[3], m[4], m[5] ); } ctx.beginPath(); clipShape.buildPath(ctx, clipShape.style); ctx.clip(); // Transform back if (clipShape.needTransform) { let m = invTransform; ctx.transform( m[0], m[1], m[2], m[3], m[4], m[5] ); } } if (((currentLayer && currentLayer.dirty) || paintAll) && !shape.invisible) { if ( !shape.onbrush || (shape.onbrush && !shape.onbrush(ctx, false)) ) { if (Config.catchBrushException) { try { shape.brush(ctx, false, this.updatePainter); } catch (error) { SUtil_SUtil.Util_log( error, 'brush error of ' + shape.type, shape ); } } else { shape.brush(ctx, false, this.updatePainter); } } } // Stop group clipping if (ctx && shape.__stopClip) { ctx.restore(); } shape.__dirty = false; } if (ctx && currentLayer && currentLayer.needTransform) { ctx.restore(); } for (let id in this._layers) { if (id !== 'hover') { var layer = this._layers[id]; layer.dirty = false; // 删除过期的层 // PENDING // if (layer.unusedCount >= 500) { // this.delLayer(id); // } if (layer.unusedCount == 1) { layer.clear(); } } } } /** * @function LevelRenderer.Painter.prototype.getLayer * @description 获取 zlevel 所在层,如果不存在则会创建一个新的层。 * * @param {number} zlevel - zlevel。 * @return {LevelRenderer.Painter} this。 */ getLayer(zlevel) { // Change draw layer var currentLayer = this._layers[zlevel]; if (!currentLayer) { var len = this._zlevelList.length; var prevLayer = null; var i = -1; if (len > 0 && zlevel > this._zlevelList[0]) { for (i = 0; i < len - 1; i++) { if ( this._zlevelList[i] < zlevel && this._zlevelList[i + 1] > zlevel ) { break; } } prevLayer = this._layers[this._zlevelList[i]]; } this._zlevelList.splice(i + 1, 0, zlevel); // Create a new layer //currentLayer = new PaintLayer(zlevel, this); currentLayer = new PaintLayer(Util.createUniqueID("_levelLayer_" + zlevel), this); var prevDom = prevLayer ? prevLayer.dom : this._bgDom; if (prevDom.nextSibling) { prevDom.parentNode.insertBefore( currentLayer.dom, prevDom.nextSibling ); } else { prevDom.parentNode.appendChild( currentLayer.dom ); } currentLayer.initContext(); this._layers[zlevel] = currentLayer; if (this._layerConfig[zlevel]) { new Util_Util().merge(currentLayer, this._layerConfig[zlevel], true); } currentLayer.updateTransform(); } return currentLayer; } /** * @function LevelRenderer.Painter.prototype.getLayers * @description 获取所有已创建的层。 * @return {Array.} 已创建的层 */ getLayers() { return this._layers; } /** * Method: _updateLayerStatus * 更新绘制层状态。 */ _updateLayerStatus(list) { var layers = this._layers; var elCounts = {}; for (let z in layers) { if (z !== 'hover') { elCounts[z] = layers[z].elCount; layers[z].elCount = 0; } } for (let i = 0; i < list.length; i++) { var shape = list[i]; var zlevel = shape.zlevel; var layer = layers[zlevel]; if (layer) { layer.elCount++; // 已经被标记为需要刷新 if (layer.dirty) { continue; } layer.dirty = shape.__dirty; } } // 层中的元素数量有发生变化 for (let z in layers) { if (z !== 'hover') { if (elCounts[z] !== layers[z].elCount) { layers[z].dirty = true; } } } } /** * @function LevelRenderer.Painter.prototype.refreshShapes * @description 更新的图形元素列表。 * * @param {number} shapeList - 需要更新的图形元素列表。 * @param {number} callback - 视图更新后回调函数。 * @return {LevelRenderer.Painter} this。 */ refreshShapes(shapeList, callback) { for (var i = 0, l = shapeList.length; i < l; i++) { var shape = shapeList[i]; this.storage.mod(shape.id); } this.refresh(callback); return this; } /** * @function LevelRenderer.Painter.prototype.clear * @description 清除 hover 层外所有内容。 * @return {LevelRenderer.Painter} this。 */ clear() { for (var k in this._layers) { if (k == 'hover') { continue; } this._layers[k].clear(); } return this; } /** * @function LevelRenderer.Painter.prototype.modLayer * @description 修改指定 zlevel 的绘制参数。 * * @param {string} zlevel - zlevel。 * @param {Object} config - 配置对象。 * @param {string} [config.clearColor=0] - 每次清空画布的颜色。 * @param {boolean} [config.motionBlur=false] - 是否开启动态模糊。 * @param {number} [config.lastFrameAlpha=0.7] - 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显。默认值:0.7。 * @param {Array.} config.position - 层的平移。 * @param {Array.} config.rotation - 层的旋转。 * @param {Array.} config.scale - 层的缩放。 * @param {boolean} config.zoomable - 层是否支持鼠标缩放操作。默认值:false。 * @param {boolean} config.panable - 层是否支持鼠标平移操作。默认值:false。 * */ modLayer(zlevel, config) { if (config) { if (!this._layerConfig[zlevel]) { this._layerConfig[zlevel] = config; } else { new Util_Util().merge(this._layerConfig[zlevel], config, true); } var layer = this._layers[zlevel]; if (layer) { new Util_Util().merge(layer, this._layerConfig[zlevel], true); } } } /** * @function LevelRenderer.Painter.prototype.delLayer * @description 删除指定层。 * * @param {string} zlevel - 层所在的 zlevel。 */ delLayer(zlevel) { var layer = this._layers[zlevel]; if (!layer) { return; } // Save config this.modLayer(zlevel, { position: layer.position, rotation: layer.rotation, scale: layer.scale }); layer.dom.parentNode.removeChild(layer.dom); delete this._layers[zlevel]; this._zlevelList.splice(new Util_Util().indexOf(this._zlevelList, zlevel), 1); } /** * @function LevelRenderer.Painter.prototype.refreshHover * @description 刷新 hover 层。 * @return {LevelRenderer.Painter} this。 */ refreshHover() { this.clearHover(); var list = this.storage.getHoverShapes(true); for (var i = 0, l = list.length; i < l; i++) { this._brushHover(list[i]); } this.storage.delHover(); return this; } /** * @function LevelRenderer.Painter.prototype.clearHover * @description 清除 hover 层所有内容。 * @return {LevelRenderer.Painter} this。 */ clearHover() { var hover = this._layers.hover; hover && hover.clear(); return this; } /** * @function LevelRenderer.Painter.prototype.resize * @description 区域大小变化后重绘。 * @return {LevelRenderer.Painter} this。 */ resize() { var domRoot = this._domRoot; domRoot.style.display = 'none'; var width = this._getWidth(); var height = this._getHeight(); domRoot.style.display = ''; // 优化没有实际改变的resize if (this._width != width || height != this._height) { this._width = width; this._height = height; domRoot.style.width = width + 'px'; domRoot.style.height = height + 'px'; for (var id in this._layers) { this._layers[id].resize(width, height); } this.refresh(null, true); } return this; } /** * @function LevelRenderer.Painter.prototype.clearLayer * @description 清除指定的一个层。 * @param {number} zLevel - 层。 */ clearLayer(zLevel) { var layer = this._layers[zLevel]; if (layer) { layer.clear(); } } /** * @function LevelRenderer.Painter.prototype.dispose * @description 释放。 * */ dispose() { this.root.innerHTML = ''; this.root = null; this.storage = null; this._domRoot = null; this._layers = null; } /** * @function LevelRenderer.Painter.prototype.getDomHover * @description 获取 Hover 层的 Dom。 */ getDomHover() { return this._layers.hover.dom; } /** * @function LevelRenderer.Painter.prototype.toDataURL * @description 图像导出。 * @param {string} type - 图片类型。 * @param {string} backgroundColor - 背景色。默认值:'#fff'。 * @param {Object} args * @return {string} 图片的Base64 url。 */ toDataURL(type, backgroundColor, args) { //var imageDom = Painter.createDom('image', 'canvas', this); var imageDom = Painter.createDom(Util.createUniqueID("SuperMap.Theme.image_"), 'canvas', this); this._bgDom.appendChild(imageDom); var ctx = imageDom.getContext('2d'); Painter.devicePixelRatio != 1 && ctx.scale(Painter.devicePixelRatio, Painter.devicePixelRatio); ctx.fillStyle = backgroundColor || '#fff'; ctx.rect( 0, 0, this._width * Painter.devicePixelRatio, this._height * Painter.devicePixelRatio ); ctx.fill(); var self = this; // 升序遍历,shape上的zlevel指定绘画图层的z轴层叠 this.storage.iterShape( function (shape) { if (!shape.invisible) { if (!shape.onbrush // 没有onbrush // 有onbrush并且调用执行返回false或undefined则继续粉刷 || (shape.onbrush && !shape.onbrush(ctx, false)) ) { if (Config.catchBrushException) { try { shape.brush(ctx, false, self.updatePainter); } catch (error) { SUtil_SUtil.Util_log( error, 'brush error of ' + shape.type, shape ); } } else { shape.brush(ctx, false, self.updatePainter); } } } }, {normal: 'up', update: true} ); var image = imageDom.toDataURL(type, args); ctx = null; this._bgDom.removeChild(imageDom); return image; } /** * @function LevelRenderer.Painter.prototype.getWidth * @description 获取绘图区域宽度。 * @return {number} 绘图区域宽度。 */ getWidth() { return this._width; } /** * @function LevelRenderer.Painter.prototype.getHeight * @description 获取绘图区域高度。 * @return {number} 绘图区域高度。 */ getHeight() { return this._height; } /** * Method: _getWidth * */ _getWidth() { var root = this.root; var stl = root.currentStyle || document.defaultView.getComputedStyle(root); return ((root.clientWidth || parseInt(stl.width, 10)) - parseInt(stl.paddingLeft, 10) // 请原谅我这比较粗暴 - parseInt(stl.paddingRight, 10)).toFixed(0) - 0; } /** * Method: _getHeight * */ _getHeight() { var root = this.root; var stl = root.currentStyle || document.defaultView.getComputedStyle(root); return ((root.clientHeight || parseInt(stl.height, 10)) - parseInt(stl.paddingTop, 10) // 请原谅我这比较粗暴 - parseInt(stl.paddingBottom, 10)).toFixed(0) - 0; } /** * Method: _brushHover * */ _brushHover(shape) { var ctx = this._layers.hover.ctx; if (!shape.onbrush // 没有onbrush // 有onbrush并且调用执行返回false或undefined则继续粉刷 || (shape.onbrush && !shape.onbrush(ctx, true)) ) { var layer = this.getLayer(shape.zlevel); if (layer.needTransform) { ctx.save(); layer.setTransform(ctx); } // Retina 优化 if (Config.catchBrushException) { try { shape.brush(ctx, true, this.updatePainter); } catch (error) { SUtil_SUtil.Util_log( error, 'hoverBrush error of ' + shape.type, shape ); } } else { shape.brush(ctx, true, this.updatePainter); } if (layer.needTransform) { ctx.restore(); } } } /** * Method: _shapeToImage * */ _shapeToImage(id, shape, width, height, devicePixelRatio) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var _devicePixelRatio = devicePixelRatio || window.devicePixelRatio || 1; canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; canvas.setAttribute('width', width * _devicePixelRatio); canvas.setAttribute('height', height * _devicePixelRatio); ctx.clearRect(0, 0, width * _devicePixelRatio, height * _devicePixelRatio); var shapeTransform = { position: shape.position, rotation: shape.rotation, scale: shape.scale }; shape.position = [0, 0, 0]; shape.rotation = 0; shape.scale = [1, 1]; if (shape) { shape.brush(ctx, false); } var imgShape = new SmicImage({ id: id, style: { x: 0, y: 0, image: canvas } }); if (shapeTransform.position != null) { imgShape.position = shape.position = shapeTransform.position; } if (shapeTransform.rotation != null) { imgShape.rotation = shape.rotation = shapeTransform.rotation; } if (shapeTransform.scale != null) { imgShape.scale = shape.scale = shapeTransform.scale; } return imgShape; } /** * Method: _createShapeToImageProcessor * */ _createShapeToImageProcessor() { var me = this; return function (id, e, width, height) { return me._shapeToImage( id, e, width, height, Painter.devicePixelRatio ); }; } // SMIC-方法扩展 - start /** * @function LevelRenderer.Painter.prototype.updateHoverLayer * @description 更新设置显示高亮图层。 * @param {Array} shapes - 图形数组。 */ updateHoverLayer(shapes) { if (!(shapes instanceof Array)) { return this; } //清除高亮 this.clearHover(); this.storage.delHover(); for (var i = 0; i < shapes.length; i++) { this.storage.addHover(shapes[i]); this._brushHover(shapes[i]); } } /** * @function LevelRenderer.Painter.prototype.createDom * @description 创建 Dom。 * * @param {string} id - Dom id * @param {string} type - Dom type * @param {LevelRenderer.Painter} painter - Painter 实例。 * @return {Object} Dom */ static createDom(id, type, painter) { var newDom = document.createElement(type); var width = painter._width; var height = painter._height; // 没append呢,请原谅我这样写,清晰~ newDom.style.position = 'absolute'; newDom.style.left = 0; newDom.style.top = 0; newDom.style.width = width + 'px'; newDom.style.height = height + 'px'; newDom.setAttribute('width', width * Painter.devicePixelRatio); newDom.setAttribute('height', height * Painter.devicePixelRatio); // id不作为索引用,避免可能造成的重名,定义为私有属性 //newDom.setAttribute('data-zr-dom-id', id); newDom.setAttribute('id', id); return newDom; } } /** * @private * @class Painter.Layer * @classdesc 绘制层类。 * @extends LevelRenderer.Transformable */ class PaintLayer extends Transformable { /** * @function Painter.Layer.constructor * @description 构造函数。 * * @param {string} id - id。 * @param {LevelRenderer.Painter} painter - Painter 实例。 * */ constructor(id, painter) { super(id, painter); /** * @member {Object} Painter.Layer.prototype.dom * @description dom。 */ this.dom = null; /** * @member {Object} Painter.Layer.prototype.domBack * @description domBack。 */ this.domBack = null; /** * @member {Object} Painter.Layer.prototype.ctxBack * @description ctxBack。 */ this.ctxBack = null; /** * @member {LevelRenderer.Painter} Painter.Layer.prototype.painter * @description painter。 */ this.painter = painter; /** * @member {number} Painter.Layer.prototype.unusedCount * @description unusedCount。 */ this.unusedCount = 0; /** * @member {Object} Painter.Layer.prototype.config * @description config。 */ this.config = null; /** * @member {boolean} Painter.Layer.prototype.dirty * @description dirty。 */ this.dirty = true; /** * @member {number} Painter.Layer.prototype.elCount * @description elCount。 */ this.elCount = 0; // Configs /** * @member {string} Painter.Layer.prototype.clearColor * @description 每次清空画布的颜色。默认值:0; */ this.clearColor = 0; /** * @member {boolean} Painter.Layer.prototype.motionBlur * @description 是否开启动态模糊。默认值:false; */ this.motionBlur = false; /** * @member {number} Painter.Layer.prototype.lastFrameAlpha * @description 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显 */ this.lastFrameAlpha = 0.7; /** * @member {boolean} Painter.Layer.prototype.zoomable * @description 层是否支持鼠标平移操作。默认值:false; */ this.zoomable = false; /** * @member {boolean} Painter.Layer.prototype.panable * @description 层是否支持鼠标缩放操作。默认值:false; */ this.panable = false; /** * @member {number} Painter.Layer.prototype.maxZoom * @description maxZoom。默认值:Infinity。 */ this.maxZoom = Infinity; /** * @member {number} Painter.Layer.prototype.minZoom * @description minZoom。默认值:0。 */ this.minZoom = 0; /** * @member {number} Painter.Layer.prototype.ctx * @description Canvas 上下文。 */ this.ctx = null; this.dom = Painter.createDom(Util.createUniqueID("SuperMap.Theme" + id), 'canvas', painter); this.dom.onselectstart = returnFalse; // 避免页面选中的尴尬 this.dom.style['-webkit-user-select'] = 'none'; this.dom.style['user-select'] = 'none'; this.dom.style['-webkit-touch-callout'] = 'none'; // Function // 返回false的方法,用于避免页面被选中 function returnFalse() { return false; } this.CLASS_NAME = "SuperMap.LevelRenderer.Painter.Layer"; } /** * @function Painter.Layer.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.dom = null; this.domBack = null; this.ctxBack = null; this.painter = null; this.unusedCount = null; this.config = null; this.dirty = null; this.elCount = null; this.clearColor = null; this.motionBlur = null; this.lastFrameAlpha = null; this.zoomable = null; this.panable = null; this.maxZoom = null; this.minZoom = null; this.ctx = null; Transformable.destroy.apply(this, arguments); } /** * @function Painter.Layer.prototype.initContext * @description 初始化 Canvan 2D 上下文。 */ initContext() { this.ctx = this.dom.getContext('2d'); if (Painter.devicePixelRatio != 1) { this.ctx.scale(Painter.devicePixelRatio, Painter.devicePixelRatio); } } /** * @function Painter.Layer.prototype.createBackBuffer * @description 创建备份缓冲。 */ createBackBuffer() { this.domBack = Painter.createDom(Util.createUniqueID("SuperMap.Theme.back-" + this.id), 'canvas', this.painter); this.ctxBack = this.domBack.getContext('2d'); if (Painter.devicePixelRatio != 1) { this.ctxBack.scale(Painter.devicePixelRatio, Painter.devicePixelRatio); } } /** * @function Painter.Layer.prototype.resize * @description 改变大小。 * * @param {number} width - 宽。 * @param {number} height - 高。 */ resize(width, height) { this.dom.style.width = width + 'px'; this.dom.style.height = height + 'px'; this.dom.setAttribute('width', width * Painter.devicePixelRatio); this.dom.setAttribute('height', height * Painter.devicePixelRatio); if (Painter.devicePixelRatio != 1) { this.ctx.scale(Painter.devicePixelRatio, Painter.devicePixelRatio); } if (this.domBack) { this.domBack.setAttribute('width', width * Painter.devicePixelRatio); this.domBack.setAttribute('height', height * Painter.devicePixelRatio); if (Painter.devicePixelRatio != 1) { this.ctxBack.scale(Painter.devicePixelRatio, Painter.devicePixelRatio); } } } /** * @function Painter.Layer.prototype.clear * @description 清空该层画布。 */ clear() { var dom = this.dom; var ctx = this.ctx; var width = dom.width; var height = dom.height; var haveClearColor = this.clearColor; var haveMotionBLur = this.motionBlur; var lastFrameAlpha = this.lastFrameAlpha; if (haveMotionBLur) { if (!this.domBack) { this.createBackBuffer(); } this.ctxBack.globalCompositeOperation = 'copy'; this.ctxBack.drawImage( dom, 0, 0, width / Painter.devicePixelRatio, height / Painter.devicePixelRatio ); } if (haveClearColor) { ctx.save(); ctx.fillStyle = this.config.clearColor; ctx.fillRect( 0, 0, width / Painter.devicePixelRatio, height / Painter.devicePixelRatio ); ctx.restore(); } else { ctx.clearRect( 0, 0, width / Painter.devicePixelRatio, height / Painter.devicePixelRatio ); } if (haveMotionBLur) { var domBack = this.domBack; ctx.save(); ctx.globalAlpha = lastFrameAlpha; ctx.drawImage( domBack, 0, 0, width / Painter.devicePixelRatio, height / Painter.devicePixelRatio ); ctx.restore(); } } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Handler.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Handler * @category Visualization Theme * @classdesc Handler控制模块。 * @extends {LevelRenderer.Eventful} * @param {HTMLElement} root - 绘图区域。 * @param {LevelRenderer.Storage} storage - Storage 实例。 * @param {LevelRenderer.Painter} painter - Painter 实例。 */ class Handler extends Eventful { constructor(root, storage, painter) { super(root, storage, painter); /** * @member {HTMLElement} LevelRenderer.Handler.prototype.root * @description 绘图区域 */ this.root = root; /** * @member {LevelRenderer.Storage} LevelRenderer.Handler.prototype.storage * @description Storage 实例 */ this.storage = storage; /** * @member {LevelRenderer.Painter} LevelRenderer.Handler.prototype.Painter * @description Painter 实例 */ this.painter = painter; /** * @member {number} [LevelRenderer.Handler.prototype._lastX=0] * @description 上一次鼠标位置x坐标值 */ this._lastX = 0; /** * @member {number} [LevelRenderer.Handler.prototype._lastY=0] * @description 上一次鼠标位置y坐标值 */ this._lastY = 0; /** * @member {number} [LevelRenderer.Handler.prototype._mouseX=0] * @description 当前鼠标位置x坐标值 */ this._mouseX = 0; /** * @member {number} [LevelRenderer.Handler.prototype._mouseY=0] * @description 当前鼠标位置y坐标值 */ this._mouseY = 0; /** * @member {function} LevelRenderer.Handler.prototype._findHover * @description 查找 Hover 图形 */ this._findHover = null; /** * @member {Object} LevelRenderer.Handler.prototype._domHover * @description 高亮 DOM */ this._domHover = null; // 各种事件标识的私有变量 // this._hasfound = false; // 是否找到 hover 图形元素 // this._lastHover = null; // 最后一个 hover 图形元素 // this._mouseDownTarget = null; // this._draggingTarget = null; // 当前被拖拽的图形元素 // this._isMouseDown = false; // this._isDragging = false; // this._lastMouseDownMoment; // this._lastTouchMoment; // this._lastDownButton; this._findHover = bind3Arg(findHover, this); this._domHover = painter.getDomHover(); this.CLASS_NAME = "SuperMap.LevelRenderer.Handler"; var domHandlers = { /** * Method: resize * 窗口大小改变响应函数。 * * Parameters: * event - {Event} event。 * */ resize: function (event) { event = event || window.event; this._lastHover = null; this._isMouseDown = 0; // 分发SuperMap.LevelRenderer.Config.EVENT.RESIZE事件,global this.dispatch(Config.EVENT.RESIZE, event); }, /** * Method: click * 点击响应函数。 * * Parameters: * event - {Event} event。 * */ click: function (event) { event = this._zrenderEventFixed(event); // 分发SuperMap.LevelRenderer.Config.EVENT.CLICK事件 var _lastHover = this._lastHover; if ((_lastHover && _lastHover.clickable) || !_lastHover ) { // 判断没有发生拖拽才触发click事件 if (this._clickThreshold < 10) { this._dispatchAgency(_lastHover, Config.EVENT.CLICK, event); } } this._mousemoveHandler(event); }, /** * Method: dblclick * 双击响应函数。 * * Parameters: * event - {Event} event。 * */ dblclick: function (event) { event = event || window.event; event = this._zrenderEventFixed(event); // 分发SuperMap.LevelRenderer.Config.EVENT.DBLCLICK事件 var _lastHover = this._lastHover; if ((_lastHover && _lastHover.clickable) || !_lastHover ) { // 判断没有发生拖拽才触发dblclick事件 if (this._clickThreshold < 5) { this._dispatchAgency(_lastHover, Config.EVENT.DBLCLICK, event); } } this._mousemoveHandler(event); }, /** * Method: mousewheel * 鼠标滚轮响应函数。 * * Parameters: * event - {Event} event。 * */ mousewheel: function (event) { event = this._zrenderEventFixed(event); // http://www.sitepoint.com/html5-javascript-mouse-wheel/ // https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference/mousewheel var delta = event.wheelDelta // Webkit || -event.detail; // Firefox var scale = delta > 0 ? 1.1 : 1 / 1.1; var layers = this.painter.getLayers(); var needsRefresh = false; for (var z in layers) { if (z !== 'hover') { var layer = layers[z]; var pos = layer.position; if (layer.zoomable) { layer.__zoom = layer.__zoom || 1; var newZoom = layer.__zoom; newZoom *= scale; newZoom = Math.max( Math.min(layer.maxZoom, newZoom), layer.minZoom ); scale = newZoom / layer.__zoom; layer.__zoom = newZoom; // Keep the mouse center when scaling pos[0] -= (this._mouseX - pos[0]) * (scale - 1); pos[1] -= (this._mouseY - pos[1]) * (scale - 1); layer.scale[0] *= scale; layer.scale[1] *= scale; layer.dirty = true; needsRefresh = true; } } } if (needsRefresh) { this.painter.refresh(); } // 分发SuperMap.LevelRenderer.Config.EVENT.MOUSEWHEEL事件 this._dispatchAgency(this._lastHover, Config.EVENT.MOUSEWHEEL, event); this._mousemoveHandler(event); }, /** * Method: mousemove * 鼠标(手指)移动响应函数。 * * Parameters: * event - {Event} event。 * */ mousemove: function (event) { // 拖拽不触发click事件 this._clickThreshold++; event = this._zrenderEventFixed(event); this._lastX = this._mouseX; this._lastY = this._mouseY; this._mouseX = SUtil_SUtil.Util_event.getX(event); this._mouseY = SUtil_SUtil.Util_event.getY(event); var dx = this._mouseX - this._lastX; var dy = this._mouseY - this._lastY; // 可能出现SuperMap.LevelRenderer.Config.EVENT.DRAGSTART事件 // 避免手抖点击误认为拖拽 // if (this._mouseX - this._lastX > 1 || this._mouseY - this._lastY > 1) { this._processDragStart(event); // } this._hasfound = 0; this._event = event; this._iterateAndFindHover(); // 找到的在迭代函数里做了处理,没找到得在迭代完后处理 if (!this._hasfound) { // 过滤首次拖拽产生的mouseout和dragLeave if (!this._draggingTarget || (this._lastHover && this._lastHover != this._draggingTarget) ) { // 可能出现SuperMap.LevelRenderer.Config.EVENT.MOUSEOUT事件 this._processOutShape(event); // 可能出现SuperMap.LevelRenderer.Config.EVENT.DRAGLEAVE事件 this._processDragLeave(event); } this._lastHover = null; this.storage.delHover(); this.painter.clearHover(); } // set cursor for root element var cursor = ''; // 如果存在拖拽中元素,被拖拽的图形元素最后addHover if (this._draggingTarget) { this.storage.drift(this._draggingTarget.id, dx, dy); this._draggingTarget.modSelf(); this.storage.addHover(this._draggingTarget); } else if (this._isMouseDown) { // Layer dragging var layers = this.painter.getLayers(); var needsRefresh = false; for (var z in layers) { if (z !== 'hover') { var layer = layers[z]; if (layer.panable) { // PENDING cursor = 'move'; // Keep the mouse center when scaling layer.position[0] += dx; layer.position[1] += dy; needsRefresh = true; layer.dirty = true; } } } if (needsRefresh) { this.painter.refresh(); } } if (this._draggingTarget || (this._hasfound && this._lastHover.draggable)) { cursor = 'move'; } else if (this._hasfound && this._lastHover.clickable) { cursor = 'pointer'; } this.root.style.cursor = cursor; // 分发SuperMap.LevelRenderer.Config.EVENT.MOUSEMOVE事件 this._dispatchAgency(this._lastHover, Config.EVENT.MOUSEMOVE, event); if (this._draggingTarget || this._hasfound || this.storage.hasHoverShape()) { this.painter.refreshHover(); } }, /** * Method: mouseout * 鼠标(手指)离开响应函数。 * * Parameters: * event - {Event} event。 * */ mouseout: function (event) { event = this._zrenderEventFixed(event); var element = event.toElement || event.relatedTarget; if (element != this.root) { while (element && element.nodeType != 9) { // 忽略包含在root中的dom引起的mouseOut if (element == this.root) { this._mousemoveHandler(event); return; } element = element.parentNode; } } event.zrenderX = this._lastX; event.zrenderY = this._lastY; this.root.style.cursor = ''; this._isMouseDown = 0; this._processOutShape(event); this._processDrop(event); this._processDragEnd(event); this.painter.refreshHover(); this.dispatch(Config.EVENT.GLOBALOUT, event); }, /** * Method: mousedown * 鼠标(手指)按下响应函数。 * * Parameters: * event - {Event} event。 * */ mousedown: function (event) { // 重置 clickThreshold this._clickThreshold = 0; if (this._lastDownButton == 2) { this._lastDownButton = event.button; this._mouseDownTarget = null; // 仅作为关闭右键菜单使用 return; } this._lastMouseDownMoment = new Date(); event = this._zrenderEventFixed(event); this._isMouseDown = 1; // 分发SuperMap.LevelRenderer.Config.EVENT.MOUSEDOWN事件 this._mouseDownTarget = this._lastHover; this._dispatchAgency(this._lastHover, Config.EVENT.MOUSEDOWN, event); this._lastDownButton = event.button; }, /** * Method: mouseup * 鼠标(手指)抬起响应函数。 * * Parameters: * event - {Event} event。 * */ mouseup: function (event) { event = this._zrenderEventFixed(event); this.root.style.cursor = ''; this._isMouseDown = 0; this._mouseDownTarget = null; // 分发SuperMap.LevelRenderer.Config.EVENT.MOUSEUP事件 this._dispatchAgency(this._lastHover, Config.EVENT.MOUSEUP, event); this._processDrop(event); this._processDragEnd(event); }, /** * Method: touchstart * Touch 开始响应函数。 * * Parameters: * event - {Event} event。 * */ touchstart: function (event) { // SUtil.Util_event.stop(event);// 阻止浏览器默认事件,重要 event = this._zrenderEventFixed(event, true); this._lastTouchMoment = new Date(); // 平板补充一次findHover this._mobildFindFixed(event); this._mousedownHandler(event); }, /** * Method: touchmove * Touch 移动响应函数。 * * Parameters: * event - {Event} event。 * */ touchmove: function (event) { event = this._zrenderEventFixed(event, true); this._mousemoveHandler(event); if (this._isDragging) { SUtil_SUtil.Util_event.stop(event);// 阻止浏览器默认事件,重要 } }, /** * Method: touchend * Touch 结束响应函数。 * * Parameters: * event - {Event} event。 * */ touchend: function (event) { // SUtil.Util_event.stop(event);// 阻止浏览器默认事件,重要 event = this._zrenderEventFixed(event, true); this._mouseupHandler(event); var now = new Date(); if (now - this._lastTouchMoment < Config.EVENT.touchClickDelay) { this._mobildFindFixed(event); this._clickHandler(event); if (now - this._lastClickMoment < Config.EVENT.touchClickDelay / 2) { this._dblclickHandler(event); if (this._lastHover && this._lastHover.clickable) { SUtil_SUtil.Util_event.stop(event);// 阻止浏览器默认事件,重要 } } this._lastClickMoment = now; } this.painter.clearHover(); } }; initDomHandler(this); // 初始化,事件绑定,支持的所有事件都由如下原生事件计算得来 if (window.addEventListener) { window.addEventListener('resize', this._resizeHandler); if (SUtil_SUtil.Util_env.os.tablet || SUtil_SUtil.Util_env.os.phone) { // mobile支持 root.addEventListener('touchstart', this._touchstartHandler); root.addEventListener('touchmove', this._touchmoveHandler); root.addEventListener('touchend', this._touchendHandler); } else { // mobile的click/move/up/down自己模拟 root.addEventListener('click', this._clickHandler); root.addEventListener('dblclick', this._dblclickHandler); root.addEventListener('mousewheel', this._mousewheelHandler); root.addEventListener('mousemove', this._mousemoveHandler); root.addEventListener('mousedown', this._mousedownHandler); root.addEventListener('mouseup', this._mouseupHandler); } root.addEventListener('DOMMouseScroll', this._mousewheelHandler); root.addEventListener('mouseout', this._mouseoutHandler); } else { window.attachEvent('onresize', this._resizeHandler); root.attachEvent('onclick', this._clickHandler); //root.attachEvent('ondblclick ', this._dblclickHandler); root.ondblclick = this._dblclickHandler; root.attachEvent('onmousewheel', this._mousewheelHandler); root.attachEvent('onmousemove', this._mousemoveHandler); root.attachEvent('onmouseout', this._mouseoutHandler); root.attachEvent('onmousedown', this._mousedownHandler); root.attachEvent('onmouseup', this._mouseupHandler); } // 辅助函数 start /** * Method: bind1Arg * bind 一个参数的 function。 * * Parameters: * handler - {function} 要 bind 的 function。 * context - {Object} 运行时 this 环境。 * * Returns: * {function} */ function bind1Arg(handler, context) { return function (e) { return handler.call(context, e); }; } /* // bind 两个参数的 function function bind2Arg(handler, context) { return function (arg1, arg2) { return handler.call(context, arg1, arg2); }; } */ // bind 三个参数的 function function bind3Arg(handler, context) { return function (arg1, arg2, arg3) { return handler.call(context, arg1, arg2, arg3); }; } /** * Method: initDomHandler * 为控制类实例初始化 dom 事件处理函数。 * * Parameters: * instance - {} 控制类实例 。 * * Returns: * {function} */ function initDomHandler(instance) { var domHandlerNames = [ 'resize', 'click', 'dblclick', 'mousewheel', 'mousemove', 'mouseout', 'mouseup', 'mousedown', 'touchstart', 'touchend', 'touchmove' ]; var len = domHandlerNames.length; while (len--) { var name = domHandlerNames[len]; instance['_' + name + 'Handler'] = bind1Arg(domHandlers[name], instance); } } /** * Method: findHover * 迭代函数,查找 hover 到的图形元素并即时做些事件分发。 * * Parameters: * shape - {Object} 图形。 * x - {number} 鼠标 x。 * y - {number} 鼠标 y。 * * Returns: * {boolean} 是否找到图形。 * */ function findHover(shape, x, y) { var me = this; if ( (me._draggingTarget && me._draggingTarget.id == shape.id) // 迭代到当前拖拽的图形上 || shape.isSilent() // 打酱油的路过,啥都不响应的shape~ ) { return false; } var event = me._event; if (shape.isCover(x, y)) { if (shape.hoverable) { // SMIC-修改 - start if (shape.isHoverByRefDataID && shape.isHoverByRefDataID === true) { if (shape.refDataID) { var fid = shape.refDataID; //me.painter.clearHover(); //me.storage.delHover(); var hoverGroup = null; if (shape.refDataHoverGroup) { hoverGroup = shape.refDataHoverGroup; } //查找同一个用户数据 feature 的所有图形 var shapeList = me.storage._shapeList; for (var i = 0, len = shapeList.length; i < len; i++) { var si = shapeList[i]; if (si.refDataID && fid === si.refDataID) { if (hoverGroup) { if (si.refDataHoverGroup && hoverGroup === si.refDataHoverGroup) { me.storage.addHover(si); } } else { me.storage.addHover(si); } } } } } else { me.storage.addHover(shape); } //初始代码: // me.storage.addHover(shape); // SMIC-修改 - end } // 查找是否在 clipShape 中 var p = shape.parent; while (p) { if (p.clipShape && !p.clipShape.isCover(me._mouseX, me._mouseY)) { // 已经被祖先 clip 掉了 return false; } p = p.parent; } if (me._lastHover != shape) { me._processOutShape(event); // 可能出现SuperMap.LevelRenderer.Config.EVENT.DRAGLEAVE事件 me._processDragLeave(event); me._lastHover = shape; // 可能出现SuperMap.LevelRenderer.Config.EVENT.DRAGENTER事件 me._processDragEnter(event); } me._processOverShape(event); // 可能出现SuperMap.LevelRenderer.Config.EVENT.DRAGOVER me._processDragOver(event); me._hasfound = 1; return true; // 找到则中断迭代查找 } return false; } // 辅助函数 end } /** * @function LevelRenderer.Handler.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为null。 */ destroy() { this.dispose(); this._lastX = null; this._lastY = null; this._mouseX = null; this._mouseY = null; this._findHover = null; Eventful.prototype.destroy.apply(this, arguments); } /** * @function LevelRenderer.Handler.prototype.on * @description 自定义事件绑定。 * @param {string} eventName - 事件名称,resize、hover、drag等。 * @param {function} handler - 响应函数。 * @returns {LevelRenderer.Handler} this。 */ on(eventName, handler) { this.bind(eventName, handler); return this; } /** * @function LevelRenderer.Handler.prototype.un * @description 自定义事件解除绑定。 * @param {string} eventName - 事件名称,resize、hover、drag等。 * @param {function} handler - 响应函数。 * @returns {LevelRenderer.Handler} this。 */ un(eventName, handler) { this.unbind(eventName, handler); return this; } /** * @function LevelRenderer.Handler.prototype.trigger * @description 事件触发。 * @param {string} eventName - 事件名称,resize、hover、drag等。 * @param {event} eventArgs - dom事件对象。 */ trigger(eventName, eventArgs) { var EVENT = Config.EVENT; switch (eventName) { case EVENT.RESIZE: case EVENT.CLICK: case EVENT.DBLCLICK: case EVENT.MOUSEWHEEL: case EVENT.MOUSEMOVE: case EVENT.MOUSEDOWN: case EVENT.MOUSEUP: case EVENT.MOUSEOUT: this['_' + eventName + 'Handler'](eventArgs); break; } } /** * @function LevelRenderer.Handler.prototype.dispose * @description 释放,解绑所有事件。 */ dispose() { var root = this.root; if (window.removeEventListener) { window.removeEventListener('resize', this._resizeHandler); if (SUtil_SUtil.Util_env.os.tablet || SUtil_SUtil.Util_env.os.phone) { // mobile支持 root.removeEventListener('touchstart', this._touchstartHandler); root.removeEventListener('touchmove', this._touchmoveHandler); root.removeEventListener('touchend', this._touchendHandler); } else { // mobile的click自己模拟 root.removeEventListener('click', this._clickHandler); root.removeEventListener('dblclick', this._dblclickHandler); root.removeEventListener('mousewheel', this._mousewheelHandler); root.removeEventListener('mousemove', this._mousemoveHandler); root.removeEventListener('mousedown', this._mousedownHandler); root.removeEventListener('mouseup', this._mouseupHandler); } root.removeEventListener('DOMMouseScroll', this._mousewheelHandler); root.removeEventListener('mouseout', this._mouseoutHandler); } else { window.detachEvent('onresize', this._resizeHandler); root.detachEvent('onclick', this._clickHandler); root.detachEvent('dblclick', this._dblclickHandler); root.detachEvent('onmousewheel', this._mousewheelHandler); root.detachEvent('onmousemove', this._mousemoveHandler); root.detachEvent('onmouseout', this._mouseoutHandler); root.detachEvent('onmousedown', this._mousedownHandler); root.detachEvent('onmouseup', this._mouseupHandler); } this.root = null; this._domHover = null; this.storage = null; this.painter = null; this.un(); } /** * Method: _processDragStart * 拖拽开始。 * * Parameters: * event - {Object} 事件对象。 * */ _processDragStart(event) { var _lastHover = this._lastHover; if (this._isMouseDown && _lastHover && _lastHover.draggable && !this._draggingTarget && this._mouseDownTarget == _lastHover ) { // 拖拽点击生效时长阀门,某些场景需要降低拖拽敏感度 if (_lastHover.dragEnableTime && new Date() - this._lastMouseDownMoment < _lastHover.dragEnableTime ) { return; } var _draggingTarget = _lastHover; this._draggingTarget = _draggingTarget; this._isDragging = 1; _draggingTarget.invisible = true; this.storage.mod(_draggingTarget.id); // 分发 Config.EVENT.DRAGSTART事件 this._dispatchAgency( _draggingTarget, Config.EVENT.DRAGSTART, event ); this.painter.refresh(); } } /** * Method: _processDragEnter * 拖拽进入目标元素。 * * Parameters: * event - {Object} 事件对象。 * */ _processDragEnter(event) { if (this._draggingTarget) { // 分发SuperMap.LevelRenderer.Config.EVENT.DRAGENTER事件 this._dispatchAgency( this._lastHover, Config.EVENT.DRAGENTER, event, this._draggingTarget ); } } /** * Method: _processDragOver * 拖拽在目标元素上移动。 * * Parameters: * event - {Object} 事件对象。 * */ _processDragOver(event) { if (this._draggingTarget) { // 分发SuperMap.LevelRenderer.Config.EVENT.DRAGOVER事件 this._dispatchAgency( this._lastHover, Config.EVENT.DRAGOVER, event, this._draggingTarget ); } } /** * Method: _processDragLeave * 拖拽离开目标元素。 * * Parameters: * event - {Object} 事件对象。 * */ _processDragLeave(event) { if (this._draggingTarget) { // 分发SuperMap.LevelRenderer.Config.EVENT.DRAGLEAVE事件 this._dispatchAgency( this._lastHover, Config.EVENT.DRAGLEAVE, event, this._draggingTarget ); } } /** * Method: _processDrop * 拖拽在目标元素上完成。 * * Parameters: * event - {Object} 事件对象。 * */ _processDrop(event) { if (this._draggingTarget) { this._draggingTarget.invisible = false; this.storage.mod(this._draggingTarget.id); this.painter.refresh(); // 分发SuperMap.LevelRenderer.Config.EVENT.DROP事件 this._dispatchAgency( this._lastHover, Config.EVENT.DROP, event, this._draggingTarget ); } } /** * Method: _processDragEnd * 拖拽结束。 * * Parameters: * event - {Object} 事件对象。 * */ _processDragEnd(event) { if (this._draggingTarget) { // 分发SuperMap.LevelRenderer.Config.EVENT.DRAGEND事件 this._dispatchAgency( this._draggingTarget, Config.EVENT.DRAGEND, event ); this._lastHover = null; } this._isDragging = 0; this._draggingTarget = null; } /** * Method: _processOverShape * 鼠标在某个图形元素上移动。 * * Parameters: * event - {Object} 事件对象。 * */ _processOverShape(event) { // 分发SuperMap.LevelRenderer.Config.EVENT.MOUSEOVER事件 this._dispatchAgency(this._lastHover, Config.EVENT.MOUSEOVER, event); } /** * Method: _processOutShape * 鼠标离开某个图形元素。 * * Parameters: * event - {Object} 事件对象。 * */ _processOutShape(event) { // 分发SuperMap.LevelRenderer.Config.EVENT.MOUSEOUT事件 this._dispatchAgency(this._lastHover, Config.EVENT.MOUSEOUT, event); } /** * Method: _dispatchAgency * 鼠标离开某个图形元素。 * * Parameters: * targetShape - {Object} 目标图形元素。 * eventName - {Object} 事件名称。 * event - {Object} 事件对象。 * draggedShape - {Object} 拖拽事件特有,当前被拖拽图形元素。 * */ _dispatchAgency(targetShape, eventName, event, draggedShape) { var eventHandler = 'on' + eventName; var eventPacket = { type: eventName, event: event, target: targetShape, cancelBubble: false }; var el = targetShape; if (draggedShape) { eventPacket.dragged = draggedShape; } while (el) { el[eventHandler] && (eventPacket.cancelBubble = el[eventHandler](eventPacket)); el.dispatch(eventName, eventPacket); el = el.parent; if (eventPacket.cancelBubble) { break; } } if (targetShape) { // 冒泡到顶级 zrender 对象 if (!eventPacket.cancelBubble) { this.dispatch(eventName, eventPacket); } } else if (!draggedShape) { // 无hover目标,无拖拽对象,原生事件分发 this.dispatch(eventName, { type: eventName, event: event }); } } /** * Method: _iterateAndFindHover * 迭代寻找 hover shape。 * */ _iterateAndFindHover() { var invTransform = SUtil_SUtil.Util_matrix.create(); var list = this.storage.getShapeList(); var currentZLevel; var currentLayer; var tmp = [0, 0]; for (var i = list.length - 1; i >= 0; i--) { var shape = list[i]; if (currentZLevel !== shape.zlevel) { currentLayer = this.painter.getLayer(shape.zlevel, currentLayer); tmp[0] = this._mouseX; tmp[1] = this._mouseY; if (currentLayer.needTransform) { SUtil_SUtil.Util_matrix.invert(invTransform, currentLayer.transform); SUtil_SUtil.Util_vector.applyTransform(tmp, tmp, invTransform); } } if (this._findHover(shape, tmp[0], tmp[1])) { break; } } } /** * Method: _mobildFindFixed * touch 有指尖错觉,四向尝试,让touch上的点击更好触发事件。 * * Parameters: * event - {Object} 事件对象。 * */ _mobildFindFixed(event) { // touch指尖错觉的尝试偏移量配置 var MOBILE_TOUCH_OFFSETS = [ {x: 10}, {x: -20}, {x: 10, y: 10}, {y: -20} ]; this._lastHover = null; this._mouseX = event.zrenderX; this._mouseY = event.zrenderY; this._event = event; this._iterateAndFindHover(); for (var i = 0; !this._lastHover && i < MOBILE_TOUCH_OFFSETS.length; i++) { var offset = MOBILE_TOUCH_OFFSETS[i]; offset.x && (this._mouseX += offset.x); offset.y && (this._mouseX += offset.y); this._iterateAndFindHover(); } if (this._lastHover) { event.zrenderX = this._mouseX; event.zrenderY = this._mouseY; } } /** * Method: _zrenderEventFixed * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标 。 * * Parameters: * event - {Object} 事件。 * isTouch - {boolean} 是否触摸。 * */ _zrenderEventFixed(event, isTouch) { if (event.zrenderFixed) { return event; } if (!isTouch) { event = event || window.event; // 进入对象优先~ var target = event.toElement || event.relatedTarget || event.srcElement || event.target; if (target && target != this._domHover) { event.zrenderX = (typeof event.offsetX != 'undefined' ? event.offsetX : event.layerX) + target.offsetLeft; event.zrenderY = (typeof event.offsetY != 'undefined' ? event.offsetY : event.layerY) + target.offsetTop; } } else { var touch = event.type != 'touchend' ? event.targetTouches[0] : event.changedTouches[0]; if (touch) { var rBounding = this.root.getBoundingClientRect(); // touch事件坐标是全屏的~ event.zrenderX = touch.clientX - rBounding.left; event.zrenderY = touch.clientY - rBounding.top; } } event.zrenderFixed = 1; return event; } // SMIC-方法扩展 - start /** * @function LevelRenderer.Handler.prototype.getLastHoverOne * @description 获取单个高亮图形 */ getLastHoverOne() { if (this._lastHover) { return this._lastHover; } return null; } // SMIC-方法扩展 - end } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Easing.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Animation.easing * @category Visualization Theme * @classdesc 缓动 * @private */ // 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js // http://sole.github.io/tween.js/examples/03_graphs.html class Easing { constructor() { this.CLASS_NAME = "SuperMap.LevelRenderer.Animation.easing"; } /** * @function LevelRenderer.Animation.easing.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { } /** * @function LevelRenderer.Animation.easing.Linear * @description 线性缓动 * @param {number} k - 参数 * @return {number} 输入值 */ Linear(k) { return k; } /** * @function LevelRenderer.Animation.easing.QuadraticIn * @description 二次方的缓动(t^2) * @param {number} k - 参数 * @return {number} 二次方的缓动的值 */ QuadraticIn(k) { return k * k; } /** * @function LevelRenderer.Animation.easing.QuadraticOut * @description 返回按二次方缓动退出的值 * @param {number} k - 参数 * @return {number} 按二次方缓动退出的值 */ QuadraticOut(k) { return k * (2 - k); } /** * @function LevelRenderer.Animation.easing.QuadraticInOut * @description 返回按二次方缓动进入和退出的值 * @param {number} k - 参数 * @return {number} 按二次方缓动进入和退出的值 */ QuadraticInOut(k) { if ((k *= 2) < 1) { return 0.5 * k * k; } return -0.5 * (--k * (k - 2) - 1); } /** * @function LevelRenderer.Animation.easing.CubicIn * @description 三次方的缓动(t^3) * @param {number} k - 参数 * @return {number} 按三次方缓动的值 */ CubicIn(k) { return k * k * k; } /** * @function LevelRenderer.Animation.easing.CubicOut * @description 返回按三次方缓动退出的值 * @param {number} k - 参数 * @return {number} 按三次方缓动退出的值 */ CubicOut(k) { return --k * k * k + 1; } /** * @function LevelRenderer.Animation.easing.CubicInOut * @description 返回按三次方缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按三次方缓动进入退出的值 */ CubicInOut(k) { if ((k *= 2) < 1) { return 0.5 * k * k * k; } return 0.5 * ((k -= 2) * k * k + 2); } /** * @function LevelRenderer.Animation.easing.QuarticIn * @description 返回按四次方缓动进入的值 * @param {number} k - 参数 * @return {number} 按四次方缓动进入的值 */ QuarticIn(k) { return k * k * k * k; } /** * @function LevelRenderer.Animation.easing.QuarticOut * @description 返回按四次方缓动退出的值 * @param {number} k - 参数 * @return {number} 按四次方缓动退出的值 */ QuarticOut(k) { return 1 - (--k * k * k * k); } /** * @function LevelRenderer.Animation.easing.QuarticInOut * @description 返回按四次方缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按四次方缓动进入退出的值 */ QuarticInOut(k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k; } return -0.5 * ((k -= 2) * k * k * k - 2); } // 五次方的缓动(t^5) /** * @function LevelRenderer.Animation.easing.QuinticIn * @description 返回按五次方缓动的值 * @param {number} k - 参数 * @return {number} 按五次方缓动的值 */ QuinticIn(k) { return k * k * k * k * k; } /** * @function LevelRenderer.Animation.easing.QuinticOut * @description 返回按五次方缓动退出的值 * @param {number} k - 参数 * @return {number} 按五次方缓动退出的值 */ QuinticOut(k) { return --k * k * k * k * k + 1; } /** * @function LevelRenderer.Animation.easing.QuinticInOut * @description 返回按五次方缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按五次方缓动进入退出的值 */ QuinticInOut(k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; } return 0.5 * ((k -= 2) * k * k * k * k + 2); } // 正弦曲线的缓动(sin(t)) /** * @function LevelRenderer.Animation.easing.SinusoidalIn * @description 返回按正弦曲线的缓动进入的值 * @param {number} k - 参数 * @return {number} 按正弦曲线的缓动进入的值 */ SinusoidalIn(k) { return 1 - Math.cos(k * Math.PI / 2); } /** * @function LevelRenderer.Animation.easing.SinusoidalOut * @description 返回按正弦曲线的缓动退出的值 * @param {number} k - 参数 * @return {number} 按正弦曲线的缓动退出的值 */ SinusoidalOut(k) { return Math.sin(k * Math.PI / 2); } /** * @function LevelRenderer.Animation.easing.SinusoidalInOut * @description 返回按正弦曲线的缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按正弦曲线的缓动进入退出的值 */ SinusoidalInOut(k) { return 0.5 * (1 - Math.cos(Math.PI * k)); } // 指数曲线的缓动(2^t) /** * @function LevelRenderer.Animation.easing.ExponentialIn * @description 返回按指数曲线的缓动进入的值 * @param {number} k - 参数 * @return {number} 按指数曲线的缓动进入的值 */ ExponentialIn(k) { return k === 0 ? 0 : Math.pow(1024, k - 1); } /** * @function LevelRenderer.Animation.easing.ExponentialOut * @description 返回按指数曲线的缓动退出的值 * @param {number} k - 参数 * @return {number} 按指数曲线的缓动退出的值 */ ExponentialOut(k) { return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); } /** * @function LevelRenderer.Animation.easing.ExponentialInOut * @description 返回按指数曲线的缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按指数曲线的缓动进入退出的值 */ ExponentialInOut(k) { if (k === 0) { return 0; } if (k === 1) { return 1; } if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); } return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2); } // 圆形曲线的缓动(sqrt(1-t^2)) /** * @function LevelRenderer.Animation.easing.CircularIn * @description 返回按圆形曲线的缓动进入的值 * @param {number} k - 参数 * @return {number} 按圆形曲线的缓动进入的值 */ CircularIn(k) { return 1 - Math.sqrt(1 - k * k); } /** * @function LevelRenderer.Animation.easing.CircularOut * @description 返回按圆形曲线的缓动退出的值 * @param {number} k - 参数 * @return {number} 按圆形曲线的缓动退出的值 */ CircularOut(k) { return Math.sqrt(1 - (--k * k)); } /** * @function LevelRenderer.Animation.easing.CircularInOut * @description 返回按圆形曲线的缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按圆形曲线的缓动进入退出的值 */ CircularInOut(k) { if ((k *= 2) < 1) { return -0.5 * (Math.sqrt(1 - k * k) - 1); } return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); } // 创建类似于弹簧在停止前来回振荡的动画 /** * @function LevelRenderer.Animation.easing.ElasticIn * @description 返回按类似于弹簧在停止前来回振荡的动画的缓动进入的值 * @param {number} k - 参数 * @return {number} 按类似于弹簧在停止前来回振荡的动画的缓动进入的值 */ ElasticIn(k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); } /** * @function LevelRenderer.Animation.easing.ElasticOut * @description 返回按类似于弹簧在停止前来回振荡的动画的缓动退出的值 * @param {number} k - 参数 * @return {number} 按类似于弹簧在停止前来回振荡的动画的缓动退出的值 */ ElasticOut(k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } return (a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); } /** * @function LevelRenderer.Animation.easing.ElasticInOut * @description 返回按类似于弹簧在停止前来回振荡的动画的缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按类似于弹簧在停止前来回振荡的动画的缓动进入退出的值 */ ElasticInOut(k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } if ((k *= 2) < 1) { return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); } return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1; } // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动 /** * @function LevelRenderer.Animation.easing.BackIn * @description 返回按在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动的缓动进入的值 * @param {number} k - 参数 * @return {number} 按在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动的缓动进入的值 */ BackIn(k) { var s = 1.70158; return k * k * ((s + 1) * k - s); } /** * @function LevelRenderer.Animation.easing.BackOut * @description 返回按在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动的缓动退出的值 * @param {number} k - 参数 * @return {number} 按在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动的缓动退出的值 */ BackOut(k) { var s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; } /** * @function LevelRenderer.Animation.easing.BackInOut * @description 返回按在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动的缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动的缓动进入退出的值 */ BackInOut(k) { var s = 1.70158 * 1.525; if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); } return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); } // 创建弹跳效果 /** * @function LevelRenderer.Animation.easing.BounceIn * @description 返回按弹跳效果的缓动进入的值 * @param {number} k - 参数 * @return {number} 按弹跳效果的缓动进入的值 */ BounceIn(k) { return 1 - this.BounceOut(1 - k); } /** * @function LevelRenderer.Animation.easing.BounceOut * @description 返回按弹跳效果的缓动退出的值 * @param {number} k - 参数 * @return {number} 按弹跳效果的缓动退出的值 */ BounceOut(k) { if (k < (1 / 2.75)) { return 7.5625 * k * k; } else if (k < (2 / 2.75)) { return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; } else if (k < (2.5 / 2.75)) { return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; } else { return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; } } /** * @function LevelRenderer.Animation.easing.BounceInOut * @description 返回按弹跳效果的缓动进入退出的值 * @param {number} k - 参数 * @return {number} 按弹跳效果的缓动进入退出的值 */ BounceInOut(k) { if (k < 0.5) { return this.BounceIn(k * 2) * 0.5; } return this.BounceOut(k * 2 - 1) * 0.5 + 0.5; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Clip.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Animation.Clip * @category Visualization Theme * @classdesc 动画片段 * @param {Object} options - 参数。 * @param {Object} options.target - 动画对象,可以是数组,如果是数组的话会批量分发 onframe 等事件。 * @param {number} [options.life=1000] - 动画时长。 * @param {number} [options.delay=0] - 动画延迟时间。 * @param {boolean} [options.loop=true] - 是否循环。 * @param {number} [options.gap=0] - 循环的间隔时间。 * @param {Object} options.onframe - 帧。 * @param {boolean} options.easing - 是否消除。 * @param {boolean} options.ondestroy - 是否销毁。 * @param {boolean} options.onrestart - 是否重播。 * @private */ class Clip { constructor(options) { this._targetPool = options.target || {}; if (!(this._targetPool instanceof Array)) { this._targetPool = [this._targetPool]; } // 生命周期 this._life = options.life || 1000; // 延时 this._delay = options.delay || 0; // 开始时间 this._startTime = new Date().getTime() + this._delay;// 单位毫秒 // 结束时间 this._endTime = this._startTime + this._life * 1000; // 是否循环 this.loop = typeof options.loop == 'undefined' ? false : options.loop; this.gap = options.gap || 0; this.easing = options.easing || 'Linear'; this.onframe = options.onframe; this.ondestroy = options.ondestroy; this.onrestart = options.onrestart; this.CLASS_NAME = "SuperMap.LevelRenderer.Animation.Clip"; } /** * @function LevelRenderer.Animation.Clip.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { } step(time) { var easing = new Easing(); var percent = (time - this._startTime) / this._life; // 还没开始 if (percent < 0) { return; } percent = Math.min(percent, 1); var easingFunc = typeof this.easing == 'string' ? easing[this.easing] : this.easing; var schedule = typeof easingFunc === 'function' ? easingFunc(percent) : percent; this.fire('frame', schedule); // 结束 if (percent == 1) { if (this.loop) { this.restart(); // 重新开始周期 // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件 return 'restart'; } // 动画完成将这个控制器标识为待删除 // 在Animation.update中进行批量删除 this._needsRemove = true; return 'destroy'; } return null; } restart() { var time = new Date().getTime(); var remainder = (time - this._startTime) % this._life; this._startTime = new Date().getTime() - remainder + this.gap; } fire(eventType, arg) { for (var i = 0, len = this._targetPool.length; i < len; i++) { if (this['on' + eventType]) { this['on' + eventType](this._targetPool[i], arg); } } } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Animation.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer.Animation * @classdesc 动画主类, 调度和管理所有动画控制器 * @category Visualization Theme * @extends {LevelRenderer.Eventful} * @param {Object} options - 动画参数。 * @param {Object} options.onframe - onframe。 * @param {Object} options.stage - stage。 * @example 例如: * (start code) * var animation = new LevelRenderer.Animation(); * var obj = { * x: 100, * y: 100 * }; * animation.animate(node.position) * .when(1000, { * x: 500, * y: 500 * }) * .when(2000, { * x: 100, * y: 100 * }) * .start('spline'); * (end) * @private */ class Animation extends Eventful { constructor(options) { super(options); options = options || {}; /** * @member {Object} LevelRenderer.Animation.prototype.stage * @description stage。 */ this.stage = {}; /** * @member {Object} LevelRenderer.Animation.prototype.onframe * @description onframe。 */ this.onframe = function () { }; /** * @member {Array} LevelRenderer.Animation.prototype._clips * @description _clips。 */ this._clips = []; /** * @member {boolean} LevelRenderer.Animation.prototype._running * @description _running。 */ this._running = false; /** * @member {number} LevelRenderer.Animation.prototype._time * @description _time。 */ this._time = 0; Util.extend(this, options); this.CLASS_NAME = "SuperMap.LevelRenderer.Animation"; } /** * @function LevelRenderer.Animation.prototype.add * @description 添加动画片段。 * @param {LevelRenderer.Animation.Clip} clip - 动画片段。 */ add(clip) { this._clips.push(clip); } /** * @function LevelRenderer.Animation.prototype.remove * @description 删除动画片段。 * @param {LevelRenderer.Animation.Clip} clip - 动画片段。 */ remove(clip) { var idx = new Util_Util().indexOf(this._clips, clip); if (idx >= 0) { this._clips.splice(idx, 1); } } /** * @function LevelRenderer.Animation.prototype.update * @description 更新动画片段。 */ _update() { var time = new Date().getTime(); var delta = time - this._time; var clips = this._clips; var len = clips.length; var deferredEvents = []; var deferredClips = []; for (let i = 0; i < len; i++) { var clip = clips[i]; var e = clip.step(time); // Throw out the events need to be called after // stage.update, like destroy if (e) { deferredEvents.push(e); deferredClips.push(clip); } } if (this.stage.update) { this.stage.update(); } // Remove the finished clip for (let i = 0; i < len;) { if (clips[i]._needsRemove) { clips[i] = clips[len - 1]; clips.pop(); len--; } else { i++; } } len = deferredEvents.length; for (let i = 0; i < len; i++) { deferredClips[i].fire(deferredEvents[i]); } this._time = time; this.onframe(delta); this.dispatch('frame', delta); } /** * @function LevelRenderer.Animation.prototype.start * @description 开始运行动画。 */ start() { var requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function (func) { setTimeout(func, 16); }; var self = this; this._running = true; function step() { if (self._running) { self._update(); requestAnimationFrame(step); } } this._time = new Date().getTime(); requestAnimationFrame(step); } /** * @function LevelRenderer.Animation.prototype.stop * @description 停止运行动画。 */ stop() { this._running = false; } /** * @function LevelRenderer.Animation.prototype.clear * @description 清除所有动画片段。 */ clear() { this._clips = []; } /** * @function LevelRenderer.Animation.prototype.animate * @description 对一个目标创建一个animator对象,可以指定目标中的属性使用动画。 * @param {Object} target - 目标对象。 * @param {Object} options - 动画参数选项。 * @param {boolean} [options.loop=false] - 是否循环播放动画。 * @param {function} [options.getter] - 如果指定getter函数,会通过getter函数取属性值。 * @param {function} [options.setter] - 如果指定setter函数,会通过setter函数设置属性值。 * @returns {LevelRenderer.Animation.Animator} Animator。 */ animate(target, options) { options = options || {}; var deferred = new Animator( target, options.loop, options.getter, options.setter ); deferred.animation = this; return deferred; } static _interpolateNumber(p0, p1, percent) { return (p1 - p0) * percent + p0; } static _interpolateArray(p0, p1, percent, out, arrDim) { var len = p0.length; if (arrDim == 1) { for (let i = 0; i < len; i++) { out[i] = Animation._interpolateNumber(p0[i], p1[i], percent); } } else { var len2 = p0[0].length; for (let i = 0; i < len; i++) { for (let j = 0; j < len2; j++) { out[i][j] = Animation._interpolateNumber( p0[i][j], p1[i][j], percent ); } } } } static _isArrayLike(data) { switch (typeof data) { case 'undefined': case 'string': return false; } return typeof data.length !== 'undefined'; } static _catmullRomInterpolateArray(p0, p1, p2, p3, t, t2, t3, out, arrDim) { var len = p0.length; if (arrDim == 1) { for (let i = 0; i < len; i++) { out[i] = Animation._catmullRomInterpolate( p0[i], p1[i], p2[i], p3[i], t, t2, t3 ); } } else { var len2 = p0[0].length; for (let i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { out[i][j] = Animation._catmullRomInterpolate( p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3 ); } } } } static _catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) { var v0 = (p2 - p0) * 0.5; var v1 = (p3 - p1) * 0.5; return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1; } static _cloneValue(value) { var arraySlice = Array.prototype.slice; if (Animation._isArrayLike(value)) { var len = value.length; if (Animation._isArrayLike(value[0])) { var ret = []; for (var i = 0; i < len; i++) { ret.push(arraySlice.call(value[i])); } return ret; } else { return arraySlice.call(value); } } else { return value; } } static rgba2String(rgba) { rgba[0] = Math.floor(rgba[0]); rgba[1] = Math.floor(rgba[1]); rgba[2] = Math.floor(rgba[2]); return 'rgba(' + rgba.join(',') + ')'; } } /** * @class LevelRenderer.Animation.Animator */ class Animator { /** * @function LevelRenderer.Animation.Animator.prototype.animate * @description 构造函数 * @param {Object} target - 目标对象。 * @param {Object} options - 动画参数选项。 * @param {boolean} [loop=false] - 是否循环播放动画。 * @param {function} [getterl] - 如果指定getter函数,会通过getter函数取属性值。 * @param {function} [setter] - 如果指定setter函数,会通过setter函数设置属性值。 */ constructor(target, loop, getter, setter) { /** * @member {Object} LevelRenderer.Animation.Animator.prototype._tracks * @description _tracks。 */ this._tracks = {}; /** * @member {Object} LevelRenderer.Animation.Animator.prototype._target * @description _target。 */ this._target = target; /** * @member {boolean} LevelRenderer.Animation.Animator.prototype._loop * @description _loop。 */ this._loop = loop || false; /** * @member {function} LevelRenderer.Animation.Animator.prototype._getter * @description _getter。 */ this._getter = getter || _defaultGetter; /** * @member {function} LevelRenderer.Animation.Animator.prototype._setter * @description _setter。 */ this._setter = setter || _defaultSetter; /** * @member {number} LevelRenderer.Animation.Animator.prototype._clipCount * @description _clipCount。 */ this._clipCount = 0; /** * @member {number} LevelRenderer.Animation.Animator.prototype._delay * @description _delay。 */ this._delay = 0; /** * @member {Array} LevelRenderer.Animation.Animator.prototype._doneList * @description _doneList。 */ this._doneList = []; /** * @member {Array} LevelRenderer.Animation.Animator.prototype._onframeList * @description _onframeList。 */ this._onframeList = []; /** * @member {Array} LevelRenderer.Animation.Animator.prototype._clipList * @description _clipList。 */ this._clipList = []; this.CLASS_NAME = "SuperMap.LevelRenderer.Animation.Animator"; //Function function _defaultGetter(target, key) { return target[key]; } function _defaultSetter(target, key, value) { target[key] = value; } } /** * @function LevelRenderer.Animation.Animator.prototype.when * @description 设置动画关键帧 * @param {number} time - 关键帧时间,单位是ms * @param {Object} props - 关键帧的属性值,key-value表示 * @returns {LevelRenderer.Animation.Animator} Animator */ when(time /* ms */, props) { for (var propName in props) { if (!this._tracks[propName]) { this._tracks[propName] = []; // If time is 0 // Then props is given initialize value // Else // Initialize value from current prop value if (time !== 0) { this._tracks[propName].push({ time: 0, value: Animation._cloneValue( this._getter(this._target, propName) ) }); } } this._tracks[propName].push({ time: parseInt(time, 10), value: props[propName] }); } return this; } /** * @function LevelRenderer.Animation.Animator.prototype.during * @description 添加动画每一帧的回调函数 * @param {RequestCallback} callback - 回调函数 * @returns {LevelRenderer.Animation.Animator} Animator */ during(callback) { this._onframeList.push(callback); return this; } /** * @function LevelRenderer.Animation.Animator.prototype.start * @description 开始执行动画 * @param {(string|function)} easing - 动画缓动函数。详见:<{@link LevelRenderer.Animation.easing}>。 * @returns {LevelRenderer.Animation.Animator} Animator */ start(easing) { var self = this; var setter = this._setter; var getter = this._getter; var onFrameListLen = self._onframeList.length; var useSpline = easing === 'spline'; var ondestroy = function () { self._clipCount--; if (self._clipCount === 0) { // Clear all tracks self._tracks = {}; var len = self._doneList.length; for (var i = 0; i < len; i++) { self._doneList[i].call(self); } } }; var createTrackClip = function (keyframes, propName) { var trackLen = keyframes.length; if (!trackLen) { return; } // Guess data type var firstVal = keyframes[0].value; var isValueArray = Animation._isArrayLike(firstVal); var isValueColor = false; // For vertices morphing var arrDim = ( isValueArray && Animation._isArrayLike(firstVal[0]) ) ? 2 : 1; // Sort keyframe as ascending keyframes.sort(function (a, b) { return a.time - b.time; }); var trackMaxTime = keyframes[trackLen - 1].time; // Percents of each keyframe var kfPercents = []; // Value of each keyframe var kfValues = []; for (let i = 0; i < trackLen; i++) { kfPercents.push(keyframes[i].time / trackMaxTime); // Assume value is a color when it is a string var value = keyframes[i].value; if (typeof(value) == 'string') { value = SUtil_SUtil.Util_color.toArray(value); if (value.length === 0) { // Invalid color value[0] = value[1] = value[2] = 0; value[3] = 1; } isValueColor = true; } kfValues.push(value); } // Cache the key of last frame to speed up when // animation playback is sequency var cacheKey = 0; var cachePercent = 0; var start; var i; var w; var p0; var p1; var p2; var p3; if (isValueColor) { var rgba = [0, 0, 0, 0]; } var onframe = function (target, percent) { // Find the range keyframes // kf1-----kf2---------current--------kf3 // find kf2 and kf3 and do interpolation if (percent < cachePercent) { // Start from next key start = Math.min(cacheKey + 1, trackLen - 1); for (i = start; i >= 0; i--) { if (kfPercents[i] <= percent) { break; } } i = Math.min(i, trackLen - 2); } else { for (i = cacheKey; i < trackLen; i++) { if (kfPercents[i] > percent) { break; } } i = Math.min(i - 1, trackLen - 2); } cacheKey = i; cachePercent = percent; var range = (kfPercents[i + 1] - kfPercents[i]); if (range === 0) { return; } else { w = (percent - kfPercents[i]) / range; } if (useSpline) { p1 = kfValues[i]; p0 = kfValues[i === 0 ? i : i - 1]; p2 = kfValues[i > trackLen - 2 ? trackLen - 1 : i + 1]; p3 = kfValues[i > trackLen - 3 ? trackLen - 1 : i + 2]; if (isValueArray) { Animation._catmullRomInterpolateArray( p0, p1, p2, p3, w, w * w, w * w * w, getter(target, propName), arrDim ); } else { let value; if (isValueColor) { // value = LevelRenderer.Animation._catmullRomInterpolateArray( // p0, p1, p2, p3, w, w * w, w * w * w, // rgba, 1 // ); value = Animation.rgba2String(rgba); } else { value = Animation._catmullRomInterpolate( p0, p1, p2, p3, w, w * w, w * w * w ); } setter( target, propName, value ); } } else { if (isValueArray) { Animation._interpolateArray( kfValues[i], kfValues[i + 1], w, getter(target, propName), arrDim ); } else { let value; if (isValueColor) { Animation._interpolateArray( kfValues[i], kfValues[i + 1], w, rgba, 1 ); value = Animation.rgba2String(rgba); } else { value = Animation._interpolateNumber(kfValues[i], kfValues[i + 1], w); } setter( target, propName, value ); } } for (i = 0; i < onFrameListLen; i++) { self._onframeList[i](target, percent); } }; var clip = new Clip({ target: self._target, life: trackMaxTime, loop: self._loop, delay: self._delay, onframe: onframe, ondestroy: ondestroy }); if (easing && easing !== 'spline') { clip.easing = easing; } self._clipList.push(clip); self._clipCount++; self.animation.add(clip); }; for (var propName in this._tracks) { createTrackClip(this._tracks[propName], propName); } return this; } /** * @function LevelRenderer.Animation.Animator.prototype.stop * @description 停止动画 */ stop() { for (var i = 0; i < this._clipList.length; i++) { var clip = this._clipList[i]; this.animation.remove(clip); } this._clipList = []; } /** * @function LevelRenderer.Animation.Animator.prototype.delay * @description 设置动画延迟开始的时间 * @param {number} time - 时间,单位ms * @returns {LevelRenderer.Animation.Animator} Animator */ delay(time) { this._delay = time; return this; } /** * @function LevelRenderer.Animation.Animator.prototype.done * @description 添加动画结束的回调 * @param {function} cb - Function * @returns {LevelRenderer.Animation.Animator} Animator */ done(cb) { if (cb) { this._doneList.push(cb); } return this; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/Render.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Render * @category Visualization Theme * @classdesc Render 接口类,对外可用的所有接口都在这里。内部使用非 get 接口统一返回 this 对象,支持链式调用。 * @param {string} id - 唯一标识。 * @param {HTMLElement} dom - Dom 对象。 */ class Render { constructor(id, dom) { /** * @member {string} LevelRenderer.Render.prototype.id * @description 唯一标识。 */ this.id = id; /** * @member {LevelRenderer.Storage} LevelRenderer.Render.prototype.storage * @description 图形仓库对象。 */ this.storage = new Storage(); /** * @member {LevelRenderer.Painter} LevelRenderer.Render.prototype.painter * @description 绘制器对象。 * */ this.painter = new Painter(dom, this.storage); /** * @member {LevelRenderer.Handler} LevelRenderer.Render.prototype.handler * @description 事件处理对象。 * */ this.handler = new Handler(dom, this.storage, this.painter); /** * @member {Array} LevelRenderer.Render.prototype.animatingElements * @description 动画控制数组。 * */ this.animatingElements = []; /** * @member {LevelRenderer.animation.Animation} LevelRenderer.Render.prototype.animation * @description 动画对象。 * */ this.animation = new Animation({ stage: { update: Render.getFrameCallback(this) } }); /** * @member {boolean} LevelRenderer.Render.prototype._needsRefreshNextFrame * @description 是否需要刷新下一帧。 * */ this._needsRefreshNextFrame = false; this.animation.start(); this.CLASS_NAME = "SuperMap.LevelRenderer.Render"; } /** * @function LevelRenderer.Render.prototype.destory * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.id = null; this.storage = null; this.painter = null; this.handler = null; this.animatingElements = null; this.animation = null; this._needsRefreshNextFrame = null; } /** * @function LevelRenderer.Render.prototype.getId * @description 获取实例唯一标识。 * @return {string} 实例唯一标识。 */ getId() { return this.id; } /** * @function LevelRenderer.Render.prototype.addShape * @description 添加图形形状到根节点。 * * @param {LevelRenderer.Shape} shape - 图形对象,可用属性全集,详见各 shape。 * @return {LevelRenderer.Render} this。 */ addShape(shape) { this.storage.addRoot(shape); return this; } /** * @function LevelRenderer.Render.prototype.addGroup * @description 添加组到根节点。 * * (code) * //添加组到根节点例子 * var render = new LevelRenderer.Render("Render",document.getElementById('lRendertest')); * render.clear(); * var g = new LevelRenderer.Group(); * g.addChild(new LevelRenderer.Shape.Circle({ * style: { * x: 100, * y: 100, * r: 20, * brushType: 'fill' * } * })); * render.addGroup(g); * render.render(); * (end) * * @param {LevelRenderer.Group} group - 组对象。 * @return {LevelRenderer.Render} this。 */ addGroup(group) { this.storage.addRoot(group); return this; } /** * @function LevelRenderer.Render.prototype.delShape * @description 从根节点删除图形形状。 * * @param {string} shapeId - 图形对象唯一标识。 * @return {LevelRenderer.Render} this。 */ delShape(shapeId) { this.storage.delRoot(shapeId); return this; } /** * @function LevelRenderer.Render.prototype.delGroup * @description 从根节点删除组。 * * @param {string} groupId - 组对象唯一标识。 * @return {LevelRenderer.Render} this。 */ delGroup(groupId) { this.storage.delRoot(groupId); return this; } /** * @function LevelRenderer.Render.prototype.modShape * @description 修改图形形状。 * * @param {string} shapeId - 图形对象唯一标识。 * @param {LevelRenderer.Shape} shape - 图形对象。 * @return {LevelRenderer.Render} this。 */ modShape(shapeId, shape) { this.storage.mod(shapeId, shape); return this; } /** * @function LevelRenderer.Render.prototype.modGroup * @description 修改组。 * * @param {string} groupId - 组对象唯一标识。 * @param {LevelRenderer.Group} group - 组对象。 * @return {LevelRenderer.Render} this。 */ modGroup(groupId, group) { this.storage.mod(groupId, group); return this; } /** * @function LevelRenderer.Render.prototype.modLayer * @description 修改指定 zlevel 的绘制配置项。 * * @param {string} zLevel - 组对象唯一标识。 * @param {Object} config - 配置对象。 * @param {string} clearColor - 每次清空画布的颜色。默认值:0。 * @param {noolean} motionBlur - 是否开启动态模糊。默认值:false。 * @param {number} lastFrameAlpha - 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显。默认值:0.7。 * @param {Array.} position - 层的平移。 * @param {Array.} rotation - 层的旋转。 * @param {Array.} scale - 层的缩放。 * @param {boolean} zoomable - 层是否支持鼠标缩放操作。默认值:false。 * @param {boolean} panable - 层是否支持鼠标平移操作。默认值:false。 * @return {LevelRenderer.Render} this。 */ modLayer(zLevel, config) { this.painter.modLayer(zLevel, config); return this; } /** * @function LevelRenderer.Render.prototype.addHoverShape * @description 添加额外高亮层显示,仅提供添加方法,每次刷新后高亮层图形均被清空。 * * @param {LevelRenderer.Shape} shape - 图形对象。 * @return {LevelRenderer.Render} this。 */ addHoverShape(shape) { this.storage.addHover(shape); return this; } /** * @function LevelRenderer.Render.prototype.render * @description 渲染。 * * @callback {function} callback - 渲染结束后回调函数。 * @return {LevelRenderer.Render} this。 */ render(callback) { this.painter.render(callback); this._needsRefreshNextFrame = false; return this; } /** * @function LevelRenderer.Render.prototype.refresh * @description 视图更新。 * * @callback {function} callback - 视图更新后回调函数。 * @return {LevelRenderer.Render} this。 */ refresh(callback) { this.painter.refresh(callback); this._needsRefreshNextFrame = false; return this; } /** * @function LevelRenderer.Render.prototype.refreshNextFrame * @description 标记视图在浏览器下一帧需要绘制。 * @return {LevelRenderer.Render} this。 */ refreshNextFrame() { this._needsRefreshNextFrame = true; return this; } /** * @function LevelRenderer.Render.prototype.refreshHover * @description 绘制(视图更新)高亮层。 * @callback {function} callback - 视图更新后回调函数。 * @return {LevelRenderer.Render} this。 */ refreshHover(callback) { this.painter.refreshHover(callback); return this; } /** * @function LevelRenderer.Render.prototype.refreshShapes * @description 视图更新。 * * @param {Array.} shapeList - 需要更新的图形列表。 * @callback {function} callback - 视图更新后回调函数。 * @return {LevelRenderer.Render} this。 */ refreshShapes(shapeList, callback) { this.painter.refreshShapes(shapeList, callback); return this; } /** * @function LevelRenderer.Render.prototype.resize * @description 调整视图大小。 * @return {LevelRenderer.Render} this。 */ resize() { this.painter.resize(); return this; } /** * @function LevelRenderer.Render.prototype.animate * @description 动画。 * * @example * zr.animate(circle.id, 'style', false) * .when(1000, {x: 10} ) * .done(function(){ // Animation done }) * .start() * * * @param {Array.<(LevelRenderer.Shape/LevelRenderer.Group)>} el - 动画对象。 * @param {string} path - 需要添加动画的属性获取路径,可以通过 a.b.c 来获取深层的属性。若传入对象为,path需为空字符串。 * @param {function} loop - 动画是否循环。 * @return {LevelRenderer.animation.Animator} Animator。 */ animate(el, path, loop) { if (typeof(el) === 'string') { el = this.storage.get(el); } if (el) { var target; if (path) { var pathSplitted = path.split('.'); var prop = el; for (var i = 0, l = pathSplitted.length; i < l; i++) { if (!prop) { continue; } prop = prop[pathSplitted[i]]; } if (prop) { target = prop; } } else { target = el; } if (!target) { SUtil_SUtil.Util_log( 'Property "' + path + '" is not existed in element ' + el.id ); return; } var animatingElements = this.animatingElements; if (typeof el.__aniCount === 'undefined') { // 正在进行的动画记数 el.__aniCount = 0; } if (el.__aniCount === 0) { animatingElements.push(el); } el.__aniCount++; return this.animation.animate(target, {loop: loop}) .done(function () { el.__aniCount--; if (el.__aniCount === 0) { // 从animatingElements里移除 var idx = new Util_Util().indexOf(animatingElements, el); animatingElements.splice(idx, 1); } }); } else { SUtil_SUtil.Util_log('Element not existed'); } } /** * @function LevelRenderer.Render.prototype.clearAnimation * @description 停止所有动画。 * */ clearAnimation() { this.animation.clear(); } /** * @function LevelRenderer.Render.prototype.getWidth * @description 获取视图宽度。 * @return {number} 视图宽度。 */ getWidth() { return this.painter.getWidth(); } /** * @function LevelRenderer.Render.prototype.getHeight * @description 获取视图高度。 * @return {number} 视图高度。 */ getHeight() { return this.painter.getHeight(); } /** * @function LevelRenderer.Render.prototype.toDataURL * @description 图像导出。 * * @param {string} type - 类型。 * @param {string} backgroundColor - 背景色,默认值:"#FFFFFF"。 * @param {string} args - 参数。 * @return {string} 图片的 Base64 url。 */ toDataURL(type, backgroundColor, args) { return this.painter.toDataURL(type, backgroundColor, args); } /** * @function LevelRenderer.Render.prototype.shapeToImage * @description 将常规 shape 转成 image shape。 * * @param {LevelRenderer.Shape} e - 图形。 * @param {number} width - 宽度。 * @param {number} height - 高度。 * @return {Object} image shape。 */ shapeToImage(e, width, height) { var id = Util.createUniqueID("SuperMap.LevelRenderer.ToImage_"); return this.painter.shapeToImage(id, e, width, height); } /** * @function LevelRenderer.Render.prototype.on * @description 事件绑定。 * * @param {string} eventName - 事件名称。 * @param {function} eventHandler - 响应函数。 * @return {LevelRenderer.Render} this。 */ on(eventName, eventHandler) { this.handler.on(eventName, eventHandler); return this; } /** * @function LevelRenderer.Render.prototype.un * @description 事件解绑定,参数为空则解绑所有自定义事件。 * * @param {string} eventName - 事件名称。 * @param {function} eventHandler - 响应函数。 * @return {LevelRenderer.Render} this。 */ un(eventName, eventHandler) { this.handler.un(eventName, eventHandler); return this; } /** * @function LevelRenderer.Render.prototype.trigger * @description 事件触发。 * * @param {string} eventName - 事件名称,resize,hover,drag,etc。 * @param {event} event - event dom事件对象。 * @return {LevelRenderer.Render} this。 */ trigger(eventName, event) { this.handler.trigger(eventName, event); this.handler.dispatch(eventName, event); return this; } /** * @function LevelRenderer.Render.prototype.clear * @description 清除当前 Render 下所有类图的数据和显示,clear 后 MVC 和已绑定事件均还存在在,Render 可用。 * @return {LevelRenderer.Render} this。 */ clear() { this.storage.delRoot(); this.painter.clear(); return this; } /** * @function LevelRenderer.Render.prototype.dispose * @description 释放当前 Render 实例(删除包括 dom,数据、显示和事件绑定),dispose后 Render 不可用。 */ dispose() { this.animation.stop(); this.clear(); this.storage.dispose(); this.painter.dispose(); this.handler.dispose(); this.animation = null; this.animatingElements = null; this.storage = null; this.painter = null; this.handler = null; // 释放后告诉全局删除对自己的索引,没想到啥好方法 // zrender.delInstance(this.id); } // SMIC-方法扩展 - start /** * @function LevelRenderer.Render.prototype.updateHoverShapes * @description 更新设置显示高亮图层。 * * @param {Array.} shapes - 图形数组。 * @return {LevelRenderer.Render} this。 */ updateHoverShapes(shapes) { this.painter.updateHoverLayer(shapes); return this; } /** * @function LevelRenderer.Render.prototype.getAllShapes * @description 获取所有图形。 * @return {Array.} 图形数组。 */ getAllShapes() { return this.storage._shapeList; } /** * @function LevelRenderer.Render.prototype.clearAll * @description 清除高亮和图形图层。 * @return {LevelRenderer.Render} this。 */ clearAll() { this.clear(); this.painter.clearHover(); return this; } /** * @function LevelRenderer.Render.prototype.getHoverOne * @description 获取单个高亮图形,当前鼠标对应。 * @return {LevelRenderer.Shape} 高亮图形。 */ getHoverOne() { return this.handler.getLastHoverOne(); } static getFrameCallback(renderInstance) { return function () { var animatingElements = renderInstance.animatingElements; //animatingElements instanceof Array 临时解决 destory 报错 if (animatingElements instanceof Array) { for (var i = 0, l = animatingElements.length; i < l; i++) { renderInstance.storage.mod(animatingElements[i].id); } if (animatingElements.length || renderInstance._needsRefreshNextFrame) { renderInstance.refresh(); } } }; } // SMIC-方法扩展 - end } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/LevelRenderer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LevelRenderer * @deprecatedclass SuperMap.LevelRenderer * @category Visualization Theme * @classdesc LevelRenderer 渲染器 * @example * //在渲染器上加上图形 * var levelRenderer = new LevelRenderer(); * var zr = levelRenderer.init(document.getElementById('lRendertest')); * zr.clear(); * zr.addShape(new LevelRenderer.Shape.Circle({ * style:{ * x : 100, * y : 100, * r : 50, * brushType: 'fill' * } * })); * zr.render(); * @private */ class LevelRenderer { constructor() { /** * @member {Object} LevelRenderer.prototype._instances * @description LevelRenderer 实例 map 索引 */ LevelRenderer._instances = {}; // 工具 LevelRenderer.Tool = {}; /** * @member {string} LevelRenderer.prototype.version * @description 版本。zRender(Baidu)的版本号 * 记录当前 LevelRenderer 是在 zRender 的那个版本上构建而来。 * 在每次完整评判和实施由 zRender(Baidu)升级带来的 LevelRenderer 升级后修改。 */ this.version = '2.0.4'; this.CLASS_NAME = "SuperMap.LevelRenderer"; } /** * @function LevelRenderer.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为null。 */ destroy() { this.dispose(); this.version = null; } /** * @function LevelRenderer.prototype.init * @description 创建 LevelRenderer 实例。 * @param {HTMLElement} dom - 绘图容器。 * @returns {LevelRenderer} LevelRenderer 实例。 */ init(dom) { var zr = new Render(Util.createUniqueID("LRenderer_"), dom); LevelRenderer._instances[zr.id] = zr; return zr; } /** * @function LevelRenderer.prototype.dispose * @description LevelRenderer 实例销毁。 * 可以通过 zrender.dispose(zr) 销毁指定 LevelRenderer.Render 实例。 * 也可以通过 zr.dispose() 直接销毁 * @param {LevelRenderer.Render} zr - ZRender对象,不传此参数则销毁全部。 * @returns {LevelRenderer} this。 */ dispose(zr) { if (zr) { zr.dispose(); this.delInstance(zr.id); } else { for (var key in LevelRenderer._instances) { LevelRenderer._instances[key].dispose(); } LevelRenderer._instances = {}; } return this; } /** * @function LevelRenderer.prototype.getInstance * @description 获取 LevelRenderer.Render 实例。 * @param {string} id - ZRender对象索引。 * @returns {LevelRenderer.Render} LevelRenderer.Render 实例。 */ getInstance(id) { return LevelRenderer._instances[id]; } /** * @function LevelRenderer.prototype.delInstance * @description 删除 zrender 实例,LevelRenderer.Render 实例 dispose 时会调用,删除后 getInstance 则返回 undefined * @param {string} id - ZRender对象索引。 * @param {string} id - LevelRenderer.Render 对象索引。 * @returns {LevelRenderer} this。 */ delInstance(id) { delete LevelRenderer._instances[id]; return this; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicEllipse.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicEllipse * @category Visualization Theme * @classdesc 椭圆。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicEllipse({ * style: { * x: 100, * y: 100, * a: 40, * b: 20, * brushType: 'both', * color: 'blue', * strokeColor: 'red', * lineWidth: 3, * text: 'SmicEllipse' * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 * */ class SmicEllipse extends (/* unused pure expression or super */ null && (Shape)) { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicEllipse.prototype.type * @description 图形类型。 */ this.type = 'smicellipse'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicEllipse"; } /** * @function LevelRenderer.Shape.SmicEllipse.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicEllipse.prototype.buildPath * @description 构建椭圆的 Path。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var k = 0.5522848; var x = style.x + __OP[0]; var y = style.y + __OP[1]; var a = style.a; var b = style.b; var ox = a * k; // 水平控制点偏移量 var oy = b * k; // 垂直控制点偏移量 // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线 ctx.moveTo(x - a, y); ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b); ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y); ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b); ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y); ctx.closePath(); } /** * @function LevelRenderer.Shape.SmicEllipse.prototype.getRect * @description 计算返回椭圆包围盒矩形 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 * */ getRect(style) { if (style.__rect) { return style.__rect; } if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } style.__rect = { x: Math.round((style.x + __OP[0]) - style.a - lineWidth / 2), y: Math.round((style.x + __OP[1]) - style.b - lineWidth / 2), width: style.a * 2 + lineWidth, height: style.b * 2 + lineWidth }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicIsogon.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicIsogon * @category Visualization Theme * @classdesc 正多边形。 * @extends LevelRenderer.Shape * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 */ class SmicIsogon extends (/* unused pure expression or super */ null && (Shape)) { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicIsogon.prototype.type * @description 图形类型。 */ this.type = 'smicisogon'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicIsogon"; } /** * @function LevelRenderer.Shape.SmicIsogon.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicIsogon.prototype.buildPath * @description 创建n角星(n>=3)路径。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var sin = SUtil.Util_math.sin; var cos = SUtil.Util_math.cos; var PI = Math.PI; var n = style.n; if (!n || n < 2) { return; } var x = style.x + __OP[0]; var y = style.y + __OP[1]; var r = style.r; var dStep = 2 * PI / n; var deg = -PI / 2; var xStart = x + r * cos(deg); var yStart = y + r * sin(deg); deg += dStep; // 记录边界点,用于判断insight var pointList = style.pointList = []; pointList.push([xStart, yStart]); for (let i = 0, end = n - 1; i < end; i++) { pointList.push([x + r * cos(deg), y + r * sin(deg)]); deg += dStep; } pointList.push([xStart, yStart]); // 绘制 ctx.moveTo(pointList[0][0], pointList[0][1]); for (let i = 0; i < pointList.length; i++) { ctx.lineTo(pointList[i][0], pointList[i][1]); } ctx.closePath(); return; } /** * @function LevelRenderer.Shape.SmicIsogon.prototype.getRect * @description 计算返回正多边形的包围盒矩形。 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 */ getRect(style) { if (style.__rect) { return style.__rect; } if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } style.__rect = { x: Math.round((style.x + __OP[0]) - style.r - lineWidth / 2), y: Math.round((style.y + __OP[1]) - style.r - lineWidth / 2), width: style.r * 2 + lineWidth, height: style.r * 2 + lineWidth }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicRing.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicRing * @category Visualization Theme * @classdesc 圆环。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicRing({ * style: { * x: 100, * y: 100, * r0: 30, * r: 50 * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 */ class SmicRing extends (/* unused pure expression or super */ null && (Shape)) { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicRing.prototype.type * @description 图形类型。 */ this.type = 'smicring'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicRing"; } /** * @function LevelRenderer.Shape.SmicRing.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicRing.prototype.buildPath * @description 创建圆环路径。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; // 非零环绕填充优化 ctx.arc(style.x + __OP[0], style.y + __OP[1], style.r, 0, Math.PI * 2, false); ctx.moveTo((style.x + __OP[0]) + style.r0, style.y + __OP[1]); ctx.arc(style.x + __OP[0], style.y + __OP[1], style.r0, 0, Math.PI * 2, true); return; } /** * @function LevelRenderer.Shape.SmicRing.prototype.getRect * @description 计算返回圆环包围盒矩阵 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 */ getRect(style) { if (style.__rect) { return style.__rect; } if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } style.__rect = { x: Math.round((style.x + __OP[0]) - style.r - lineWidth / 2), y: Math.round((style.y + __OP[1]) - style.r - lineWidth / 2), width: style.r * 2 + lineWidth, height: style.r * 2 + lineWidth }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/SmicStar.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @private * @class LevelRenderer.Shape.SmicStar * @category Visualization Theme * @classdesc n 角星(n>3)。 * @extends LevelRenderer.Shape * @example * var shape = new LevelRenderer.Shape.SmicStar({ * style: { * x: 200, * y: 100, * r: 150, * n: 5, * text: '五角星' * } * }); * levelRenderer.addShape(shape); * @param {Array} options - shape 的配置(options)项,可以是 shape 的自有属性,也可以是自定义的属性。 * */ class SmicStar extends (/* unused pure expression or super */ null && (Shape)) { constructor(options) { super(options); /** * @member {string} LevelRenderer.Shape.SmicStar.prototype.type * @description 图形类型。 */ this.type = 'smicstar'; if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } this.CLASS_NAME = "SuperMap.LevelRenderer.Shape.SmicStar"; } /** * @function LevelRenderer.Shape.SmicStar.prototype.destroy * @description 销毁对象,释放资源。调用此函数后所有属性将被置为 null。 */ destroy() { this.type = null; super.destroy(); } /** * @function LevelRenderer.Shape.SmicStar.prototype.buildPath * @description 创建n 角星(n>3)路径。 * * @param {CanvasRenderingContext2D} ctx - Context2D 上下文。 * @param {Object} style - style。 * */ buildPath(ctx, style) { if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var n = style.n; if (!n || n < 2) { return; } var sin = SUtil.Util_math.sin; var cos = SUtil.Util_math.cos; var PI = Math.PI; var x = style.x + __OP[0]; var y = style.y + __OP[1]; var r = style.r; var r0 = style.r0; // 如果未指定内部顶点外接圆半径,则自动计算 if (r0 == null) { r0 = n > 4 // 相隔的外部顶点的连线的交点, // 被取为内部交点,以此计算r0 ? r * cos(2 * PI / n) / cos(PI / n) // 二三四角星的特殊处理 : r / 3; } var dStep = PI / n; var deg = -PI / 2; var xStart = x + r * cos(deg); var yStart = y + r * sin(deg); deg += dStep; // 记录边界点,用于判断inside var pointList = style.pointList = []; pointList.push([xStart, yStart]); for (var i = 0, end = n * 2 - 1, ri; i < end; i++) { ri = i % 2 === 0 ? r0 : r; pointList.push([x + ri * cos(deg), y + ri * sin(deg)]); deg += dStep; } pointList.push([xStart, yStart]); // 绘制 ctx.moveTo(pointList[0][0], pointList[0][1]); for (let i = 0; i < pointList.length; i++) { ctx.lineTo(pointList[i][0], pointList[i][1]); } ctx.closePath(); return; } /** * @function LevelRenderer.Shape.SmicStar.prototype.getRect * @description 返回 n 角星包围盒矩形。 * * @param {Object} style - style * @return {Object} 边框对象。包含属性:x,y,width,height。 */ getRect(style) { if (style.__rect) { return style.__rect; } if (!this.refOriginalPosition || this.refOriginalPosition.length !== 2) { this.refOriginalPosition = [0, 0]; } var __OP = this.refOriginalPosition; var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } style.__rect = { x: Math.round((style.x + __OP[0]) - style.r - lineWidth / 2), y: Math.round((style.y + __OP[1]) - style.r - lineWidth / 2), width: style.r * 2 + lineWidth, height: style.r * 2 + lineWidth }; return style.__rect; } } ;// CONCATENATED MODULE: ./src/common/overlay/levelRenderer/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/overlay/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/components/CommonTypes.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @description 该文件用于存储一些公用常量 * @private */ const CommonTypes_FileTypes = { EXCEL: "EXCEL", CSV: "CSV", ISERVER: "ISERVER", GEOJSON: "GEOJSON", JSON: 'JSON' }; const CommonTypes_FileConfig = { fileMaxSize: 10 * 1024 * 1024 }; ;// CONCATENATED MODULE: ./src/common/components/openfile/FileModel.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FileModel * @deprecatedclass SuperMap.FileModel * @description 文件数据组件数据模型,用于存储一些文件数据或状态,todo 结构待完善 * @category Components OpenFile * @private */ class FileModel { constructor(options) { this.FileTypes = FileTypes; this.FileConfig = FileConfig; this.loadFileObject = options && options.loadFileObject ? options.loadFileObject : []; } /** * @function FileModel.prototype.set * @description 设置属性值 * @param {string} key - 属性名称 * @param {string|Object} value - 属性值 */ set(key, value) { this[key] = value; } /** * @function FileModel.prototype.get * @description 获取数据值 * @param {string} key - 属性名称 * @returns {string|Object} value - 返回属性值 */ get(key) { return this[key]; } } ;// CONCATENATED MODULE: ./src/common/components/messagebox/MessageBox.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MessageBox * @aliasclass Components.MessageBox * @deprecatedclass SuperMap.Components.MessageBox * @version 9.1.1 * @classdesc 组件信息提示框。 * @category Components Common * @usage */ class MessageBox { constructor() { this._initView(); } _initView() { //原生js形式 const messageBoxContainer = document.createElement("div"); messageBoxContainer.hidden = true; messageBoxContainer.setAttribute("class", "component-messageboxcontainer component-border-bottom-orange"); //图标 const iconContainer = document.createElement("div"); iconContainer.setAttribute("class", "icon"); this.icon = document.createElement("span"); this.icon.setAttribute("class", "supermapol-icons-message-warning"); iconContainer.appendChild(this.icon); messageBoxContainer.appendChild(iconContainer); //内容: const messageBox = document.createElement("div"); messageBox.setAttribute("class", "component-messagebox"); messageBox.innerHTML = ""; messageBoxContainer.appendChild(messageBox); this.messageBox = messageBox; //关闭按钮 const cancelContainer = document.createElement("div"); cancelContainer.setAttribute("class", "component-messagebox__cancelbtncontainer"); const cancelBtn = document.createElement("button"); cancelBtn.setAttribute("class", "component-messagebox__cancelBtn"); cancelBtn.innerHTML = "x"; cancelBtn.onclick = this.closeView.bind(this); cancelContainer.appendChild(cancelBtn); messageBoxContainer.appendChild(cancelContainer); this.messageBoxContainer = messageBoxContainer; document.body.appendChild(this.messageBoxContainer); } /** * @function MessageBox.prototype.closeView * @description 关闭提示框。 */ closeView() { this.messageBoxContainer.hidden = true; } /** * @function MessageBox.prototype.showView * @description 显示提示框。 * @param {string} message - 提示框显示内容。 * @param {string}[type="warring"] 提示框类型,如 "warring", "failure", "success"。 */ showView(message, type = 'warring') { //设置提示框的样式: if (type === "success") { this.icon.setAttribute("class", "supermapol-icons-message-success"); this.messageBoxContainer.setAttribute("class", "component-messageboxcontainer component-border-bottom-green"); } else if (type === "failure") { this.icon.setAttribute("class", "supermapol-icons-message-failure"); this.messageBoxContainer.setAttribute("class", "component-messageboxcontainer component-border-bottom-red"); } else if (type === "warring") { this.icon.setAttribute("class", "supermapol-icons-message-warning"); this.messageBoxContainer.setAttribute("class", "component-messageboxcontainer component-border-bottom-orange"); } this.messageBox.innerHTML = message; this.messageBoxContainer.hidden = false; } } ;// CONCATENATED MODULE: external "function(){try{return echarts}catch(e){return {}}}()" const external_function_try_return_echarts_catch_e_return_namespaceObject = function(){try{return echarts}catch(e){return {}}}(); var external_function_try_return_echarts_catch_e_return_default = /*#__PURE__*/__webpack_require__.n(external_function_try_return_echarts_catch_e_return_namespaceObject); ;// CONCATENATED MODULE: ./src/common/lang/locales/en-US.js  /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * Namespace: SuperMap.Lang["en"] * Dictionary for English. Keys for entries are used in calls to * . Entry bodies are normal strings or * strings formatted for use with calls. */ let en = { 'title_dataFlowService': 'Data Flow Service', 'title_distributedAnalysis': 'Distributed Analysis', 'title_clientComputing': 'Client Computing', 'title_dataServiceQuery': 'Data Service Query', 'title_searchCity':'Search city', 'title_searchLayer':' Search layer', 'text_input_value_inputDataFlowUrl': 'Please enter the data stream service address such as: ws://{serviceRoot}/{dataFlowName}/dataflow/subscribe', 'text_displayFeaturesInfo': 'Display feature information', 'text_subscribe': 'subscribe', 'text_cancelSubscribe': 'unsubscribe', 'text_densityAnalysis': 'Density Analysis', 'text_CalculateTheValuePerUnitArea': 'Calculate the value per unit area within the neighborhood shape', 'text_option_selectDataset':'Please select a dataset', 'text_label_dataset': 'Dataset', 'text_option_simplePointDensityAnalysis': 'Simple point density analysis', 'text_option_nuclearDensityAnalysis': 'Nuclear density analysis', 'text_label_analyticalMethod': 'Analytical method', 'text_option_quadrilateral': 'Quadrilateral', 'text_option_hexagon': 'hexagon', 'text_label_meshType': 'Mesh type', 'text_option_notSet': 'Not set', 'text_label_weightField': 'Weight field', 'text_label_gridSizeInMeters': 'Grid size', 'text_label_searchRadius': 'Search radius', 'text_label_queryRange': 'Scope of analysis', 'text_label_areaUnit': 'Area unit', 'text_option_equidistantSegmentation': 'Equidistant segmentation', 'text_option_logarithm': 'Logarithm', 'text_option_equalCountingSegment': 'Equal counting segment', 'text_option_squareRootSegmentation': 'Square root segmentation', 'text_label_thematicMapSegmentationMode': 'Thematic map segmentation mode', 'text_label_thematicMapSegmentationParameters': 'Thematic map segmentation parameters', 'text_option_greenOrangePurpleGradient': 'Green orange purple gradient', 'text_option_greenOrangeRedGradient': 'Green orange red gradient', 'text_option_rainbowGradient': 'Rainbow gradient', 'text_option_spectralGradient': 'Spectral gradient', 'text_option_terrainGradient': 'Terrain gradient', 'text_label_thematicMapColorGradientMode': 'Thematic map color gradient mode', 'text_label_resultLayerName': 'Result layer name', 'text_chooseFile': 'Open File', 'text_isoline': 'Isoline', 'text_extractDiscreteValue': 'Extract discrete value generation curve', 'text_buffer': 'Buffer', 'text_specifyTheDistance': 'Specify the distance to create the surrounding area', 'text_label_analysisLayer': 'Analysis layer', 'text_label_extractField': 'Extract field', 'text_label_extractedValue': 'Extracted value', 'text_label_distanceAttenuation': 'Distance attenuation', 'text_label_gridSize': 'gridSize', 'text_label_bufferRadius': 'Buffer radius', 'text_label_defaultkilometers': 'Default 10 kilometers', 'text_label_kilometer': 'kilometer', 'text_label_unit': 'unit', 'text_retainOriginal': 'Retain original object field', 'text_mergeBuffer': 'Merge buffer', 'text_label_color': 'Color', 'text_label_buffer': '[Buffer]', 'text_label_isolines': '[Isolines]', 'text_label_queryRangeTips': 'The default is the full range of input data. Example: -74.050, 40.650, -73.850, 40.850', 'text_label_queryModel': 'Query mode', 'text_label_IDArrayOfFeatures': 'ID array of features', 'text_label_maxFeatures': 'The maximum number of features that can be returned', 'text_label_bufferDistance': 'Buffer distance', 'text_label_queryRange1': 'Query range', 'text_label_spatialQueryMode': 'Spatial query mode', 'text_label_featureFilter': 'Feature filter', 'text_label_geometricObject': 'Geometric object', 'text_label_queryMode': 'Query mode', 'text_label_searchTips': 'Search for city locations or layer features', 'text_label_chooseSearchLayers': 'Select a query layer', 'text_loadSearchCriteria': 'Load search criteria', 'text_saveSearchCriteria': 'Save search criteria', "btn_analyze": "Analyze", "btn_analyzing": "Analyzing", "btn_emptyTheAnalysisLayer": "Empty the analysis layer", "btn_cancelAnalysis": "Cancel", "btn_query": "Query", "btn_querying": "Querying", "btn_emptyTheRresultLayer": "Clear all result layers", 'msg_dataReturnedIsEmpty.': 'The request is successful and the data returned by the query is empty.', 'msg_dataFlowServiceHasBeenSubscribed': 'The data stream service has been subscribed to.', 'msg_inputDataFlowUrlFirst': 'Please enter the data stream service address first.', 'msg_datasetOrMethodUnsupport': 'This dataset does not support this analysis type. Please reselect the dataset.', 'msg_selectDataset': 'Please select a data set!', 'msg_setTheWeightField': 'Please set the weight field!', 'msg_theFieldNotSupportAnalysis': 'The field you currently select does not support analysis!', 'msg_resultIsEmpty': 'The result of the analysis is empty!', 'msg_openFileFail': 'Failed to open file!', 'msg_fileTypeUnsupported': 'File format is not supported!', 'msg_fileSizeExceeded': 'File size exceeded! The file size should not exceed 10M!', 'msg_dataInWrongGeoJSONFormat': 'Wrong data format! Non standard GEOJSON format data!', 'msg_dataInWrongFormat': 'Wrong data format! Non standard EXCEL, CSV or GEOJSON format data!', 'msg_searchKeywords': "Search keywords cannot be empty. Please enter your search criteria.", 'msg_searchGeocodeField':"Did not match the address matching service data!", 'msg_cityGeocodeField':"The address matching service of the current city is not configured.", 'msg_getFeatureField':"No related vector features found!", 'msg_dataflowservicesubscribed':'The data stream service has been subscribed to.', 'msg_subscribesucceeded':'The data stream service subscription was successful.', 'msg_crsunsupport':'Does not support the coordinate system of the current map', 'msg_tilematrixsetunsupport':'Incoming TileMatrixSet is not supported', 'msg_jsonResolveFiled': 'JSON format parsing failure!', 'msg_requestContentFiled': 'Failed to request data through iportal!', 'msg_getdatafailed': 'Failed to get data!' }; ;// CONCATENATED MODULE: ./src/common/lang/locales/zh-CN.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * Namespace: SuperMap.Lang["zh-CN"] * Dictionary for Simplified Chinese. Keys for entries are used in calls to * . Entry bodies are normal strings or * strings formatted for use with calls. */ let zh = { 'title_dataFlowService': '数据流服务', 'title_distributedAnalysis': '分布式分析', 'title_clientComputing': '客户端计算', 'title_dataServiceQuery': '数据服务查询', 'title_searchCity':'搜索城市', 'title_searchLayer':'搜索图层', 'text_input_value_inputDataFlowUrl': '请输入数据流服务地址如:ws://{serviceRoot}/{dataFlowName}/dataflow/subscribe', 'text_displayFeaturesInfo': '显示要素信息', 'text_subscribe': '订阅', 'text_cancelSubscribe': '取消订阅', 'text_densityAnalysis': '密度分析', 'text_CalculateTheValuePerUnitArea': '计算点指定邻域形状内的每单位面积量值', 'text_option_selectDataset':'请选择数据集', 'text_label_dataset': '数据集', 'text_option_simplePointDensityAnalysis': '简单点密度分析', 'text_option_nuclearDensityAnalysis': '核密度分析', 'text_label_analyticalMethod': '分析方法', 'text_option_quadrilateral': '四边形', 'text_option_hexagon': '六边形', 'text_label_meshType': '网格面类型', 'text_option_notSet': '未设置', 'text_label_weightField': '权重字段', 'text_label_gridSizeInMeters': '网格大小', 'text_label_searchRadius': '搜索半径', 'text_label_queryRange': '分析范围', 'text_label_areaUnit': '面积单位', 'text_option_equidistantSegmentation': '等距离分段', 'text_option_logarithm': '对数', 'text_option_equalCountingSegment': '等计数分段', 'text_option_squareRootSegmentation': '平方根分段', 'text_label_thematicMapSegmentationMode': '专题图分段模式', 'text_label_thematicMapSegmentationParameters': '专题图分段参数', 'text_option_greenOrangePurpleGradient': '绿橙紫渐变', 'text_option_greenOrangeRedGradient': '绿橙红渐变', 'text_option_rainbowGradient': '彩虹渐变', 'text_option_spectralGradient': '光谱渐变', 'text_option_terrainGradient': '地形渐变', 'text_label_thematicMapColorGradientMode': '专题图颜色渐变模式', 'text_label_resultLayerName': '结果图层名称', 'text_chooseFile': '选择文件', 'text_isoline': '等值线', 'text_extractDiscreteValue': '提取离散值生成曲线', 'text_buffer': '缓冲区', 'text_specifyTheDistance': '指定距离创建周边区域', 'text_label_analysisLayer': '分析图层', 'text_label_extractField': '提取字段', 'text_label_extractedValue': '提取值', 'text_label_distanceAttenuation': '距离衰减', 'text_label_gridSize': '栅格大小', 'text_label_bufferRadius': '缓冲半径', 'text_label_defaultkilometers': '默认10千米', 'text_option_kilometer': '千米', 'text_label_unit': '单位', 'text_retainOriginal': '保留原对象字段属性', 'text_mergeBuffer': '合并缓冲区', 'text_label_color': '颜色', 'text_label_buffer': '[缓冲区]', 'text_label_isolines': '[等值线]', 'text_label_queryRangeTips': '默认为输入数据的全幅范围。范例:-74.050,40.650,-73.850,40.850', 'text_label_IDArrayOfFeatures': '要素 ID 数组', 'text_label_maxFeatures': '最多可返回的要素数量', 'text_label_bufferDistance': '缓冲区距离', 'text_label_queryRange1': '查询范围', 'text_label_spatialQueryMode': '空间查询模式', 'text_label_featureFilter': '要素过滤器', 'text_label_geometricObject': '几何对象', 'text_label_queryMode': '查询模式', 'text_label_searchTips': '搜索城市地点或图层要素', 'text_label_chooseSearchLayers': '选择查询图层', 'text_loadSearchCriteria': '加载搜索条件', 'text_saveSearchCriteria': '保存搜索条件', "btn_analyze": "分析", "btn_analyzing": "分析中", "btn_emptyTheAnalysisLayer": "清空分析图层", "btn_cancelAnalysis": "取消", "btn_query": "查询", "btn_querying": "查询中", "btn_emptyTheRresultLayer": "清除所有结果图层", 'msg_dataFlowServiceHasBeenSubscribed': '已订阅该数据流服务。', 'msg_inputDataFlowUrlFirst': '请先输入数据流服务地址。', 'msg_datasetOrMethodUnsupport': '该数据集不支持本分析类型,请重新选择数据集', 'msg_selectDataset': '请选择数据集!', 'msg_setTheWeightField': '请设置权重字段!', 'msg_theFieldNotSupportAnalysis': '您当前选择的字段不支持分析!', 'msg_resultIsEmpty': '分析的结果为空!', 'msg_dataReturnedIsEmpty': '请求成功,查询返回的数据为空。', 'msg_openFileFail': '打开文件失败!', 'msg_fileTypeUnsupported': '不支持该文件格式!', 'msg_fileSizeExceeded': '文件大小超限!文件大小不得超过 10M!', 'msg_dataInWrongGeoJSONFormat': '数据格式错误!非标准的 GEOJSON 格式数据!', 'msg_dataInWrongFormat': '数据格式错误!非标准的 EXCEL, CSV 或 GEOJSON 格式数据!', 'msg_searchKeywords': "搜索关键字不能为空,请输入搜索条件。", 'msg_searchGeocodeField':"未匹配到地址匹配服务数据!", 'msg_cityGeocodeField':"未配置当前城市的地址匹配服务。", 'msg_getFeatureField':"未查找到相关矢量要素!", 'msg_dataflowservicesubscribed':'已订阅该数据流服务。', 'msg_subscribesucceeded':'数据流服务订阅成功。', 'msg_crsunsupport':'不支持当前地图的坐标系', 'msg_tilematrixsetunsupport':'不支持传入的TileMatrixSet', 'msg_jsonResolveFiled': 'json格式解析失败!', 'msg_requestContentFiled': '通过iportal请求数据失败!', 'msg_getdatafailed': '获取数据失败!' }; ;// CONCATENATED MODULE: ./src/common/lang/Lang.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @name Lang * @namespace * @category BaseTypes Internationalization * @description 国际化的命名空间,包含多种语言和方法库来设置和获取当前的语言。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { Lang } from '{npm}'; * * const result = Lang.getCode(); * * ``` */ let Lang = { 'en-US': en, "zh-CN": zh, /** * @member {string} Lang.code * @description 当前所使用的语言类型。 */ code: null, /** * @member {string} [Lang.defaultCode='en-US'] * @description 默认使用的语言类型。 */ defaultCode: "en-US", /** * @function Lang.getCode * @description 获取当前的语言代码。 * @returns {string} 当前的语言代码。 */ getCode: function () { if (!Lang.code) { Lang.setCode(); } return Lang.code; }, /** * @function Lang.setCode * @description 设置语言代码。 * @param {string} code - 此参数遵循IETF规范。 */ setCode: function () { var lang = this.getLanguageFromCookie(); if (lang) { Lang.code = lang; return; } lang = Lang.defaultCode; if (navigator.appName === 'Netscape') { lang = navigator.language; } else { lang = navigator.browserLanguage; } if (lang.indexOf('zh') === 0) { lang = 'zh-CN'; } if (lang.indexOf('en') === 0) { lang = 'en-US'; } Lang.code = lang; }, /** * @function Lang.getLanguageFromCookie * @description 从 cookie 中获取语言类型。 */ getLanguageFromCookie() { var name = 'language='; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1) } if (c.indexOf(name) !== -1) { return c.substring(name.length, c.length) } } return ""; }, /** * @function Lang.i18n * @description 从当前语言字符串的字典查找 key。 * @param {string} key - 字典中 i18n 字符串值的关键字。 * @returns {string} 国际化的字符串。 */ i18n: function (key) { var dictionary = Lang[Lang.getCode()]; var message = dictionary && dictionary[key]; if (!message) { // Message not found, fall back to message key message = key; } return message; } }; ;// CONCATENATED MODULE: external "function(){try{return XLSX}catch(e){return {}}}()" const external_function_try_return_XLSX_catch_e_return_namespaceObject = function(){try{return XLSX}catch(e){return {}}}(); ;// CONCATENATED MODULE: ./src/common/components/util/FileReaderUtil.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @name FileReaderUtil * @namespace * @category Components OpenFile * @description 组件读取文件工具类。 * @version 9.1.1 * @type {{rABS: (boolean|*), rABF: (boolean|*), rAT: (boolean|*), readFile: (function(*, *=, *=, *=, *=)), readTextFile: (function(*, *=, *=, *=)), readXLSXFile: (function(*, *=, *=, *=)), processDataToGeoJson: (function(string, Object): GeoJSONObject), processExcelDataToGeoJson: (function(Object): GeoJSONObject), isXField: (function(*)), isYField: (function(*)), string2Csv: (function(*, *=))}} * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { FileReaderUtil } from '{npm}'; * * const result = FileReaderUtil.isXField(data); * ``` */ let FileReaderUtil = { rABS: typeof FileReader !== 'undefined' && FileReader.prototype && FileReader.prototype.readAsBinaryString, rABF: typeof FileReader !== 'undefined' && FileReader.prototype && FileReader.prototype.readAsArrayBuffer, rAT: typeof FileReader !== 'undefined' && FileReader.prototype && FileReader.prototype.readAsText, /** * @function FileReaderUtil.prototype.readFile * @description 读取文件。 * @param {string} fileType - 当前读取的文件类型。 * * @param {Object} file - 读取回来的文件内容对象。 * @param {function} success - 读取文件成功回调函数。 * @param {function} failed - 读取文件失败回调函数。 * @param {Object} context - 回调重定向对象。 */ readFile(fileType, file, success, failed, context) { if (CommonTypes_FileTypes.JSON === fileType || CommonTypes_FileTypes.GEOJSON === fileType) { this.readTextFile(file, success, failed, context) } else if (CommonTypes_FileTypes.EXCEL === fileType || CommonTypes_FileTypes.CSV === fileType) { this.readXLSXFile(file, success, failed, context) } }, /** * @description 读取文本文件。 * @param {Object} file 文件内容对象。 * @param {function} success 读取文件成功回调函数。 * @param {function} failed 读取文件失败回调函数。 * @param {Object} context - 回调重定向对象。 */ readTextFile(file, success, failed, context) { let reader = new FileReader(); reader.onloadend = function (evt) { success && success.call(context, evt.target.result); }; reader.onerror = function (error) { failed && failed.call(context, error) }; this.rAT ? reader.readAsText(file.file, 'utf-8') : reader.readAsBinaryString(file.file); }, /** * @description 读取excel或csv文件。 * @param {Object} file 文件内容对象。 * @param {function} success 读取文件成功回调函数。 * @param {function} failed 读取文件失败回调函数。 * @param {Object} context - 回调重定向对象。 */ readXLSXFile(file, success, failed, context) { let reader = new FileReader(); reader.onloadend = function (evt) { let xLSXData = new Uint8Array(evt.target.result); let workbook = external_function_try_return_XLSX_catch_e_return_namespaceObject.read(xLSXData, {type: "array"}); try { if (workbook && workbook.SheetNames && workbook.SheetNames.length > 0) { //暂时只读取第一个sheets的内容 let sheetName = workbook.SheetNames[0]; let xLSXCSVString = external_function_try_return_XLSX_catch_e_return_namespaceObject.utils.sheet_to_csv(workbook.Sheets[sheetName]); success && success.call(context, xLSXCSVString); } } catch (error) { failed && failed.call(context, error); } }; reader.onerror = function (error) { failed && failed.call(context, error) }; this.rABF && reader.readAsArrayBuffer(file.file); }, /** * @function FileReaderUtil.prototype.processDataToGeoJson * @description 将读取回来得数据统一处理为 GeoJSON 格式。 * @param {string} type - 文件类型。 * @param {Object} data - 读取返回的数据对象。 * @param {function} success - 数据处理成功的回调。 * @param {function} failed - 数据处理失败的回调。 * @param {Object} context - 回调重定向对象。 * @returns {GeoJSONObject} 返回标准 GeoJSON 规范格式数据。 * @private */ processDataToGeoJson(type, data, success, failed, context) { let geojson = null; if (type === "EXCEL" || type === "CSV") { geojson = this.processExcelDataToGeoJson(data); success && success.call(context, geojson); } else if (type === 'JSON' || type === 'GEOJSON') { let result = data; //geojson、json未知,通过类容来判断 if ((typeof result) === "string") { result = JSON.parse(result); } if (result.type === 'ISERVER') { geojson = result.data.recordsets[0].features; } else if (result.type === 'FeatureCollection') { //geojson geojson = result; } else { //不支持数据 failed && failed.call(context, Lang.i18n('msg_dataInWrongGeoJSONFormat')); } success && success.call(context, geojson); } else { failed && failed.call(context, Lang.i18n('msg_dataInWrongFormat')); } }, /** * @function FileReaderUtil.prototype.processExcelDataToGeoJson * @description 表格文件数据处理。 * @param {Object} data - 读取的表格文件数据。 * @returns {GeoJSONObject} 返回标准 GeoJSON 规范格式数据。 * @private */ processExcelDataToGeoJson(data) { //处理为对象格式转化 let dataContent = this.string2Csv(data); let fieldCaptions = dataContent.colTitles; //位置属性处理 let xfieldIndex = -1, yfieldIndex = -1; for (let i = 0, len = fieldCaptions.length; i < len; i++) { if (this.isXField(fieldCaptions[i])) { xfieldIndex = i; } if (this.isYField(fieldCaptions[i])) { yfieldIndex = i; } } // feature 构建后期支持坐标系 4326/3857 let features = []; for (let i = 0, len = dataContent.rows.length; i < len; i++) { let row = dataContent.rows[i]; //if (featureFrom === "LonLat") { let x = Number(row[xfieldIndex]), y = Number(row[yfieldIndex]); //属性信息 let attributes = {}; for (let index in dataContent.colTitles) { let key = dataContent.colTitles[index]; attributes[key] = dataContent.rows[i][index]; } //目前csv 只支持处理点,所以先生成点类型的 geojson let feature = { "type": "Feature", "geometry": { "type": "Point", "coordinates": [x, y] }, "properties": attributes }; features.push(feature); } return features; }, /** * @description 判断是否地理X坐标。 * @param {string} data 字段名。 */ isXField(data) { var lowerdata = data.toLowerCase(); return (lowerdata === "x" || lowerdata === "smx" || lowerdata === "jd" || lowerdata === "经度" || lowerdata === "东经" || lowerdata === "longitude" || lowerdata === "lot" || lowerdata === "lon" || lowerdata === "lng" || lowerdata === "x坐标"); }, /** * @description 判断是否地理Y坐标。 * @param {string} data 字段名。 */ isYField(data) { var lowerdata = data.toLowerCase(); return (lowerdata === "y" || lowerdata === "smy" || lowerdata === "wd" || lowerdata === "纬度" || lowerdata === "北纬" || lowerdata === "latitude" || lowerdata === "lat" || lowerdata === "y坐标"); }, /** * @description 字符串转为dataEditor 支持的csv格式数据。 * @param {string} string 待转化的字符串。 * @param {boolean} withoutTitle 是否需要列标题。 */ string2Csv(string, withoutTitle) { // let rows = string.split('\r\n'); let rows = string.split('\n'); let result = {}; if (!withoutTitle) { result["colTitles"] = rows[0].split(','); } else { result["colTitles"] = []; } result['rows'] = []; for (let i = (withoutTitle) ? 0 : 1; i < rows.length; i++) { rows[i] && result['rows'].push(rows[i].split(',')); } return result; } }; ;// CONCATENATED MODULE: ./src/common/components/chart/ChartModel.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChartModel * @classdesc 图表组件数据模型 * @private * @param {Object} datasets - 数据来源。 * @category Components Chart * @fires ChartModel#getdatafailed */ class ChartModel { constructor(datasets) { this.datasets = datasets; this.EVENT_TYPES = ['getdatafailed']; this.events = new Events(this, null, this.EVENT_TYPES); } /** * @private * @function ChartModel.prototype.getDatasetInfo * @description 获得数据集数据。 * @param {string} datasetUrl - 数据集资源地址。 */ getDatasetInfo(success) { let datasetUrl = this.datasets.url; let me = this; FetchRequest.get(datasetUrl) .then(function (response) { return response.json(); }) .then(function (results) { if (results.datasetInfo) { let datasetInfo = results.datasetInfo; me.datasetsInfo = { dataSourceName: datasetInfo.dataSourceName, datasetName: datasetInfo.name, mapName: results.name }; success({ result: me.datasetsInfo }); } }) .catch(function (error) { console.log(error); me._fireFailedEvent(error); }); } /** * @private * @function ChartModel.prototype.getDataFeatures * @description 请求数据集的数据信息 * @param {Object} results - 数据集信息。 * @param {function} success - 成功回调函数。 */ getDataFeatures(results, success) { let datasetsInfo = results.result; let getFeatureParam, getFeatureBySQLParams, getFeatureBySQLService; let params = { name: datasetsInfo.datasetName + '@' + datasetsInfo.dataSourceName }; Object.assign(params, this.datasets.queryInfo); getFeatureParam = new FilterParameter(params); getFeatureBySQLParams = new GetFeaturesBySQLParameters({ queryParameter: getFeatureParam, datasetNames: [datasetsInfo.dataSourceName + ':' + datasetsInfo.datasetName], fromIndex: 0, toIndex: 100000 }); getFeatureBySQLService = new GetFeaturesBySQLService(datasetsInfo.dataUrl, { eventListeners: { processCompleted: success, processFailed: function () {} } }); getFeatureBySQLService.processAsync(getFeatureBySQLParams); } /** * @private * @function ChartModel.prototype.getLayerFeatures * @description 请求图层要素的数据信息 * @param {Object} results - 数据集信息。 * @param {Callbacks} success - 成功回调函数。 */ getLayerFeatures(results, success) { let datasetsInfo = results.result; let queryParam, queryBySQLParams, queryBySQLService; let params = { name: datasetsInfo.mapName }; Object.assign(params, this.datasets.queryInfo); queryParam = new FilterParameter(params); queryBySQLParams = new QueryBySQLParameters({ queryParams: [queryParam], expectCount: 100000 }); queryBySQLService = new QueryBySQLService(datasetsInfo.dataUrl, { eventListeners: { processCompleted: success, processFailed: function () {} } }); queryBySQLService.processAsync(queryBySQLParams); } /** * @private * @function ChartModel.prototype.getDataInfoByIptl * @description 用dataId获取iportal的数据。 * @param {Callbacks} success - 成功回调函数。 * */ getDataInfoByIptl(success) { // success是chart的回调 this.getServiceInfo(this.datasets.url, success); } /** * @private * @function ChartModel.prototype.getServiceInfo * @description 用iportal获取dataItemServices。 * @param {string} url * @param {Callbacks} success - 成功回调函数。 * */ getServiceInfo(url, success) { let me = this; FetchRequest.get(url, null, { withCredentials: this.datasets.withCredentials }) .then((response) => { return response.json(); }) .then((data) => { if (data.succeed === false) { //请求失败 me._fireFailedEvent(data); return; } // 是否有rest服务 if (data.dataItemServices && data.dataItemServices.length > 0) { let dataItemServices = data.dataItemServices, resultData; dataItemServices.forEach((item) => { // 如果有restdata并且发布成功,就请求restdata服务 // 如果有restmap并且发布成功,就请求restmap服务 // 其他情况就请求iportal/content.json if (item.serviceType === 'RESTDATA' && item.serviceStatus === 'PUBLISHED') { resultData = item; } else if (item.serviceType === 'RESTMAP' && item.serviceStatus === 'PUBLISHED') { resultData = item; } else { me.getDatafromContent(url, success); return; } }); // 如果有服务,获取数据源和数据集, 然后请求rest服务 resultData && me.getDatafromRest(resultData.serviceType, resultData.address, success); } else { me.getDatafromContent(url, success); return; } }) .catch((error) => { console.log(error); me._fireFailedEvent(error); }); } /** * @private * @function ChartModel.prototype.getDatafromURL * @description 用iportal获取数据。(通过固定的url来请求,但是不能请求工作空间的数据) * @param {string} url * @param {Callbacks} success - 成功回调函数。 */ getDatafromContent(url, success) { // 成功回调传入的results let results = { result: {} }, me = this; url += '/content.json?pageSize=9999999¤tPage=1'; // 获取图层数据 FetchRequest.get(url, null, { withCredentials: this.datasets.withCredentials }) .then((response) => { return response.json(); }) .then((data) => { if (data.succeed === false) { //请求失败 me._fireFailedEvent(data); return; } if (data.type) { if (data.type === 'JSON' || data.type === 'GEOJSON') { // 将字符串转换成json data.content = JSON.parse(data.content.trim()); // 如果是json文件 data.content = {type:'fco', features},格式不固定 if (!data.content.features) { //json格式解析失败 console.log(Lang.i18n('msg_jsonResolveFiled')); return; } let features = this._formatGeoJSON(data.content); results.result.features = { type: data.content.type, features }; } else if (data.type === 'EXCEL' || data.type === 'CSV') { let features = this._excelData2Feature(data.content); results.result.features = { type: 'FeatureCollection', features }; } success(results, 'content'); } }, this) .catch((error) => { console.log(error); me._fireFailedEvent(error); }); } /** * @private * @function ChartModel.prototype._getDataSource * @description 获取数据源名和数据集名。 * @param {string} serviceType 服务类型 * @param {string} address 地址 * @param {Callbacks} success - 成功回调函数。 * @return {Array.} ["数据源名:数据集名"] * @return {string} 图层名 */ getDatafromRest(serviceType, address, success) { let me = this, withCredentials = this.datasets.withCredentials; if (serviceType === 'RESTDATA') { let url = `${address}/data/datasources`, sourceName, datasetName; // 请求获取数据源名 FetchRequest.get(url, null, { withCredentials }) .then((response) => { return response.json(); }) .then((data) => { sourceName = data.datasourceNames[0]; url = `${address}/data/datasources/${sourceName}/datasets`; // 请求获取数据集名 FetchRequest.get(url, null, { withCredentials }) .then((response) => { return response.json(); }) .then((data) => { datasetName = data.datasetNames[0]; // 请求restdata服务 me.getDatafromRestData(`${address}/data`, [sourceName + ':' + datasetName], success); return [sourceName + ':' + datasetName]; }) .catch(function (error) { me._fireFailedEvent(error); }); }) .catch(function (error) { me._fireFailedEvent(error); }); } else { // 如果是地图服务 let url = `${address}/maps`, mapName, layerName, path; // 请求获取地图名 FetchRequest.get(url, null, { withCredentials }) .then((response) => { return response.json(); }) .then((data) => { mapName = data[0].name; path = data[0].path; url = url = `${address}/maps/${mapName}/layers`; // 请求获取图层名 FetchRequest.get(url, null, { withCredentials }) .then((response) => { return response.json(); }) .then((data) => { layerName = data[0].subLayers.layers[0].caption; // 请求restmap服务 me.getDatafromRestMap(layerName, path, success); return layerName; }) .catch(function (error) { me._fireFailedEvent(error); }); }) .catch(function (error) { me._fireFailedEvent(error); }); } } /** * @private * @function ChartModel.prototype.getDatafromRestData * @description 请求restdata服务 * @param {string} url * @param {Array} dataSource [数据源名:数据集名] * @param {Callbacks} success - 成功回调函数。 */ getDatafromRestData(url, dataSource, success) { let me = this; this.datasets.queryInfo.attributeFilter = this.datasets.queryInfo.attributeFilter || 'SmID>0'; this._getFeatureBySQL( url, dataSource, this.datasets.queryInfo, (results) => { // 此时的features已经处理成geojson了 success(results, 'RESTDATA'); }, (error) => { console.log(error); me._fireFailedEvent(error); } ); } /** * @private * @function ChartModel.prototype.getDatafromRestMap * @description 请求restmap服务 * @param {string} dataSource layerName * @param {string} path - map服务地址。 * @param {Callbacks} success - 成功回调函数。 */ getDatafromRestMap(dataSource, path, success) { let me = this; this.datasets.queryInfo.attributeFilter = this.datasets.queryInfo.attributeFilter || 'smid=1'; this._queryFeatureBySQL( path, dataSource, this.datasets.queryInfo, null, null, (results) => { // let features = result.result.recordsets[0].features; success(results, 'RESTMAP'); }, (error) => { console.log(error); me._fireFailedEvent(error); } ); } /** * @private * @function ChartModel.prototype._getFeatureBySQL * @description 通过 sql 方式查询数据。 */ _getFeatureBySQL(url, datasetNames, queryInfo, processCompleted, processFaild) { let getFeatureParam, getFeatureBySQLService, getFeatureBySQLParams; let params = { name: datasetNames.join().replace(':', '@') }; Object.assign(params, queryInfo); getFeatureParam = new FilterParameter(params); getFeatureBySQLParams = new GetFeaturesBySQLParameters({ queryParameter: getFeatureParam, datasetNames: datasetNames, fromIndex: 0, toIndex: 100000, returnContent: true }); let options = { eventListeners: { processCompleted: (getFeaturesEventArgs) => { processCompleted && processCompleted(getFeaturesEventArgs); }, processFailed: (e) => { processFaild && processFaild(e); } } }; getFeatureBySQLService = new GetFeaturesBySQLService(url, options); getFeatureBySQLService.processAsync(getFeatureBySQLParams); } /** * @private * @function ChartModel.prototype._queryFeatureBySQL * @description 通过 sql 方式查询数据。 */ _queryFeatureBySQL( url, layerName, queryInfo, fields, epsgCode, processCompleted, processFaild, startRecord, recordLength, onlyAttribute ) { var queryParam, queryBySQLParams; var filterParams = { name: layerName }; Object.assign(filterParams, queryInfo); queryParam = new FilterParameter(filterParams); if (fields) { queryParam.fields = fields; } var params = { queryParams: [queryParam] }; if (onlyAttribute) { params.queryOption = QueryOption.ATTRIBUTE; } startRecord && (params.startRecord = startRecord); recordLength && (params.expectCount = recordLength); if (epsgCode) { params.prjCoordSys = { epsgCode: epsgCode }; } queryBySQLParams = new QueryBySQLParameters(params); this._queryBySQL(url, queryBySQLParams, (data) => { data.type === 'processCompleted' ? processCompleted(data) : processFaild(data); }); } /** * @function ChartModel.prototype._queryBySQL * @description SQL 查询服务。 * @param {QueryBySQLParameters} params - SQL 查询相关参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 结果类型。 */ _queryBySQL(url, params, callback, resultFormat) { var me = this; var queryBySQLService = new QueryBySQLService(url, { eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); queryBySQLService.processAsync(params); } /** * @function ChartModel.prototype._processFormat * @description 将数据转换成geojson。 * @param {Object} resultFormat - 返回结果集。 * @return {Object} [resultFormat=DataFormat.GEOJSON] - 结果类型。 */ _processFormat(resultFormat) { return resultFormat ? resultFormat : DataFormat.GEOJSON; } /** * @private * @function ChartModel.prototype._formatGeoJSON * @description 格式 GeoJSON。 * @param {GeoJSON} data - GeoJSON 数据。 */ _formatGeoJSON(data) { let features = data.features; features.forEach((row, index) => { row.properties['index'] = index; }); return features; } /** * @private * @description 将 csv 和 xls 文件内容转换成 geojson * @function ChartModel.prototype._excelData2Feature * @param content 文件内容 * @param layerInfo 图层信息 * @returns {Array} feature的数组集合 */ _excelData2Feature(dataContent) { let fieldCaptions = dataContent.colTitles; //位置属性处理 let xfieldIndex = -1, yfieldIndex = -1; for (let i = 0, len = fieldCaptions.length; i < len; i++) { if (FileReaderUtil.isXField(fieldCaptions[i])) { xfieldIndex = i; } if (FileReaderUtil.isYField(fieldCaptions[i])) { yfieldIndex = i; } } // feature 构建后期支持坐标系 4326/3857 let features = []; for (let i = 0, len = dataContent.rows.length; i < len; i++) { let row = dataContent.rows[i]; let x = Number(row[xfieldIndex]), y = Number(row[yfieldIndex]); //属性信息 let attributes = {}; for (let index in dataContent.colTitles) { let key = dataContent.colTitles[index]; attributes[key] = dataContent.rows[i][index]; } attributes['index'] = i + ''; //目前csv 只支持处理点,所以先生成点类型的 geojson let feature = { type: 'Feature', geometry: { type: 'Point', coordinates: [x, y] }, properties: attributes }; features.push(feature); } return features; } /** * @private * @description 请求数据失败的事件 * @function ChartModel.prototype._fireFailedEvent * @param {Object} error 错误信息 */ _fireFailedEvent(error) { let errorData = error ? { error, message: Lang.i18n('msg_getdatafailed') } : { message: Lang.i18n('msg_getdatafailed') }; /** * @event ChartModel#getdatafailed * @description 监听到获取数据失败事件后触发 * @property {Object} error - 事件对象。 */ this.events.triggerEvent('getdatafailed', errorData); } } ;// CONCATENATED MODULE: ./src/common/components/chart/ChartViewModel.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChartViewModel * @aliasclass Components.ChartViewModel * @deprecatedclass SuperMap.Components.ChartViewModel * @classdesc 图表组件功能类。 * @category Components Chart * @version 10.0.0 * @param {Object} options - 可选参数。 * @param {string} options.type - 图表类型。 * @param {ChartView.Datasets} options.datasets - 数据来源。 * @param {Array.} options.chartOptions - 图表可选配置。 * @param {Array.} options.chartOptions.xAxis - X轴可选参数。 * @param {string} options.chartOptions.xAxis.field - X轴字段名。 * @param {string} options.chartOptions.xAxis.name - X轴名称。 * @param {Array.} options.chartOptions.yAxis - Y轴可选参数。 * @param {string} options.chartOptions.yAxis.field - Y轴字段名。 * @param {string} options.chartOptions.yAxis.name - Y轴名称。 * @fires ChartViewModel#getdatafailed * @usage */ class ChartViewModel { constructor(options) { this.datasets = options.datasets; this.xField = []; this.yField = []; this.grid = { top: "50px", bottom: "50px", left: "50px", right: "60px" }; this.chartType = options.type || "bar"; this._initXYField(options.chartOptions); this.EVENT_TYPES = ["getdatafailed"]; this.events = new Events(this, null, this.EVENT_TYPES); } /** * @function ChartViewModel.prototype._initXYField * @description 初始化XY字段。 * @private * @param {Object} chartOptions - options里的图表参数。 */ _initXYField(chartOptions) { let me = this; if (chartOptions && chartOptions.length > 0) { chartOptions.forEach(function (option) { if (option.xAxis) { me.xField.push({ field: option.xAxis.field, name: option.xAxis.name }); } if (option.yAxis) { me.yField.push({ field: option.yAxis.field, name: option.yAxis.name }); } }); } } /** * @function ChartViewModel.prototype.getDatasetInfo * @description 获得数据集数据。 * @param {function} success - 成功回调函数。 */ getDatasetInfo(success) { this.createChart = success; if (this.datasets && this._checkUrl(this.datasets.url)) { this.chartModel = new ChartModel(this.datasets); if(this.datasets.type === 'iServer'){ this.chartModel.getDatasetInfo(this._getDatasetInfoSuccess.bind(this)); }else if(this.datasets.type === 'iPortal'){ this.chartModel.getDataInfoByIptl(this._getDataInfoSuccess.bind(this)); } /** * @event ChartViewModel#getdatafailed * @description 监听到获取数据失败事件后触发。 * @property {Object} error - 事件对象。 */ this.chartModel.events.on({"getdatafailed": (error) => { this.events.triggerEvent("getdatafailed", error) }}); } } /** * @function ChartViewModel.prototype._getDatasetInfoSuccess * @description 成功回调函数。 * @private * @param {Object} results - 数据集信息。 */ _getDatasetInfoSuccess(results) { let datasetUrl = this.datasets.url; //判断服务为地图服务 或者 数据服务 let restIndex = datasetUrl.indexOf("rest"); if (restIndex > 0) { let index = datasetUrl.indexOf("/", restIndex + 5); let type = datasetUrl.substring(restIndex + 5, index); let dataUrl = datasetUrl.substring(0, restIndex + 4) + "/data"; if (type === "maps") { let mapIndex = datasetUrl.indexOf("/", index + 1); let mapName = datasetUrl.substring(index + 1, mapIndex); dataUrl = datasetUrl.substring(0, restIndex + 4) + "/maps/" + mapName; results.result.dataUrl = dataUrl; this._getLayerFeatures(results); } else if (type === "data") { results.result.dataUrl = dataUrl; this._getDataFeatures(results); } } } /** * @function ChartViewModel.prototype._getDataInfoSuccess * @description 请求iportal数据成功之后的回调。 * @private */ _getDataInfoSuccess(results, type) { let me = this; if(type === 'RESTMAP'){ me._getChartDatasFromLayer(results); }else{ me._getChartDatas(results); } } /** * @function ChartViewModel.prototype._getDataFeatures * @description 请求数据集的数据信息 * @private * @param {Object} results - 数据集信息 */ _getDataFeatures(results) { this.chartModel.getDataFeatures(results, this._getChartDatas.bind(this)); } /** * @function ChartViewModel.prototype._getLayerFeatures * @description 请求图层的数据信息。 * @private * @param {Object} results - 数据集信息。 */ _getLayerFeatures(results) { this.chartModel.getLayerFeatures(results, this._getChartDatasFromLayer.bind(this)); } /** * @function ChartViewModel.prototype._getChartDatas * @description 将请求回来的数据转换为图表所需的数据格式。 * @private * @param {Object} results - 数据要素信息。 */ _getChartDatas(results) { if (results) { // 数据来自restdata---results.result.features this.features = results.result.features; let features = this.features.features; let data = {}; if (features.length) { let feature = features[0]; let attrFields = [], itemTypes = []; for (let attr in feature.properties) { attrFields.push(attr); itemTypes.push(this._getDataType(feature.properties[attr])); } data = { features, fieldCaptions: attrFields, fieldTypes: itemTypes, fieldValues: [] } for (let m in itemTypes) { let fieldValue = []; for (let j in features) { let feature = features[j]; let caption = data.fieldCaptions[m]; let value = feature.properties[caption]; fieldValue.push(value); } data.fieldValues.push(fieldValue); } this.createChart(data); } } } /** * @function ChartViewModel.prototype._getChartDatasFromLayer * @description 将请求回来的数据转换为图表所需的数据格式。 * @private * @param {Object} results - 图层数据要素信息。 */ _getChartDatasFromLayer(results) { if (results.result.recordsets) { let recordsets = results.result.recordsets[0]; let features = recordsets.features.features; this.features = recordsets.features; let data = {}; if (features.length) { data = { features: recordsets.features, fieldCaptions: recordsets.fieldCaptions, fieldTypes: recordsets.fieldTypes, fieldValues: [] } for (let m in data.fieldCaptions) { let fieldValue = []; for (let j in features) { let feature = features[j]; let caption = data.fieldCaptions[m]; let value = feature.properties[caption]; fieldValue.push(value); } data.fieldValues.push(fieldValue); } this.createChart(data); } } } /** * @function ChartViewModel.prototype._createChartOptions * @description 创建图表所需参数。 * @private * @param {Object} data - 图表数据。 */ _createChartOptions(data) { this.calculatedData = this._createChartDatas(data); return this.updateChartOptions(this.chartType); } /** * @function ChartViewModel.prototype.changeType * @description 改变图表类型。 * @param {string} type - 图表类型。 */ changeType(type) { if (type !== this.chartType) { this.chartType = type; return this.updateChartOptions(this.chartType); } } /** * @function ChartViewModel.prototype.updateData * @description 改变图表类型。 * @param {ChartView.Datasets} datasets - 数据来源。 * @param {function} success 成功回调函数。 */ updateData(datasets, chartOption, success) { this.updateChart = success; this.xField = []; this.yField = []; this._initXYField(chartOption); // type的设置默认值 datasets.type = datasets.type || 'iServer'; // withCredentials的设置默认值 datasets.withCredentials = datasets.withCredentials || false; this.datasets = datasets; this.getDatasetInfo(this._updateDataSuccess.bind(this)); } /** * @function ChartViewModel.prototype._updateDataSuccess * @description 改变图表类型。 * @private * @param {Object} data - 图表数据。 */ _updateDataSuccess(data) { let options = this._createChartOptions(data); this.updateChart(options); } /** * @function ChartViewModel.prototype.updateChartOptions * @description 更新图表所需参数。 * @param {string} type - 图表类型。 * @param {Object} style - 图表样式。 */ updateChartOptions(type, style) { if (this.calculatedData) { let grid = this.grid; let series = this._createChartSeries(this.calculatedData, type); let datas = []; for (let i in this.calculatedData.XData) { datas.push({ value: this.calculatedData.XData[i].fieldsData }); } let xAxis = { type: "category", name: this.xField[0].name || "X", data: datas, nameTextStyle: { color: '#fff', fontSize: 14 }, splitLine: { show: false }, axisLine: { lineStyle: { color: '#eee' } } } let yAxis = { type: "value", name: this.yFieldName || "Y", data: {}, nameTextStyle: { color: '#fff', fontSize: 14 }, splitLine: { show: false }, axisLine: { lineStyle: { color: '#eee' } } } let tooltip = { formatter: '{b0}: {c0}' }; let backgroundColor = '#404a59'; if (style) { if (style.grid) { grid = style.grid; } if (style.tooltip) { tooltip = style.tooltip; } if (style.backgroundColor) { backgroundColor = style.backgroundColor; } } return { backgroundColor: backgroundColor, grid: grid, series: series, xAxis: xAxis, yAxis: yAxis, tooltip: tooltip } } } /** * @function ChartViewModel.prototype._createChartDatas * @description 构建图表数据。 * @private * @param {Object} data - 源数据。 */ _createChartDatas(data) { let fieldIndex = 0, yfieldIndexs = []; let fieldCaptions = data.fieldCaptions; let me = this; //X fieldCaptions.forEach(function (field, index) { if (me.xField[0] && field === me.xField[0].field) { fieldIndex = index; } }); //Y this.yFieldName = ""; this.yField.forEach(function (value, index) { if (index !== 0) { me.yFieldName = me.yFieldName + ","; } me.yFieldName = me.yFieldName + value.name; fieldCaptions.forEach(function (field, index) { if (field === value.field) { yfieldIndexs.push(index); } }); }) let datas = this._getAttrData(data, fieldIndex); let yDatas = []; if (yfieldIndexs.length > 0) { yfieldIndexs.forEach(function (yfieldIndex) { let yData = []; for (let i in data.fieldValues[yfieldIndex]) { yData.push({ value: data.fieldValues[yfieldIndex][i] }); } yDatas.push(yData); }); } else { //未指定Y字段时,y轴计数 let YData = [], XData = [], len = datas.length; //计算X轴,Y轴数据,并去重 for (let i = 0; i < len; i++) { let isSame = false; for (let j = 0, leng = XData.length; j < leng; j++) { if (datas[i].fieldsData === XData[j].fieldsData) { YData[j].value++; XData[j].recordIndexs.push(i); isSame = true; break; } } if (!isSame) { if (datas[i].fieldsData) { XData.push({ fieldsData: datas[i].fieldsData, recordIndexs: [i] }); YData.push({ value: 1 }); } } } datas = XData; yDatas = [YData]; } return { XData: datas, YData: yDatas } } /** * @function ChartViewModel.prototype._getAttrData * @description 选中字段数据。 * @private * @param {Object} datacontent - 图表数据。 * @param {number} index - 字段索引。 */ _getAttrData(datacontent, index) { if (index === 0) { this.xField = [{ field: datacontent.fieldCaptions[index], name: datacontent.fieldCaptions[index] }]; } let fieldsDatas = []; for (let i = 0, len = datacontent.fieldValues[index].length; i < len; i++) { let value = datacontent.fieldValues[index][i]; fieldsDatas.push({ recordIndexs: i, fieldsData: value }); } return fieldsDatas; } /** * @function ChartViewModel.prototype._createChartSeries * @description 图表数据。 * @private * @param {Object} calculatedData - 图表数据。 * @param {string} chartType - 图表类型。 */ _createChartSeries(calculatedData, chartType) { let series = []; let yDatas = calculatedData.YData; yDatas.forEach(function (yData) { let value = 0; let serieData = []; for (let data of yData) { value = data.value; serieData.push({ value: value }); } let serie = { type: chartType, data: serieData, name: "y" }; series.push(serie); }); return series; } /** * @function ChartViewModel.prototype._isDate * @description 判断是否为日期。 * @private * @param {string} data - 字符串。 */ _isDate(data) { let reg = /((^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(10|12|0?[13578])([-\/\._])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(11|0?[469])([-\/\._])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(0?2)([-\/\._])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\/\._])(0?2)([-\/\._])(29)$)|(^([3579][26]00)([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][0][48])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][0][48])([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][2468][048])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][2468][048])([-\/\._])(0?2)([-\/\._])(29)$)|(^([1][89][13579][26])([-\/\._])(0?2)([-\/\._])(29)$)|(^([2-9][0-9][13579][26])([-\/\._])(0?2)([-\/\._])(29)$))/ig; return reg.test(data); } /** * @function ChartViewModel.prototype._isNumber * @description 判断是否为数值。 * @private * @param {string} data - 字符串。 */ _isNumber(data) { let mdata = Number(data); if (mdata === 0) { return true; } return !isNaN(mdata); } /** * @function ChartViewModel.prototype._getDataType * @description 判断数据的类型。 * @private * @param {string} data - 字符串。 */ _getDataType(data) { if (data !== null && data !== undefined && data !== '') { if (this._isDate(data)) { return "DATE"; } if (this._isNumber(data)) { return "NUMBER"; } } return "STRING"; } /** * @function ChartViewModel.prototype._checkUrl * @description 检查url是否符合要求。 * @private * @param {string} url。 */ _checkUrl(url) { let match; if (url === '' || !this._isMatchUrl(url)) { match = false; } else if (/^http[s]?:\/\/localhost/.test(url) || /^http[s]?:\/\/127.0.0.1/.test(url)) { //不是实际域名 match = false; } else { match = true; } return match; } /** * @function ChartViewModel.prototype._isMatchUrl * @description 判断输入的地址是否符合地址格式。 * @private * @param {string} str - url。 */ _isMatchUrl(str) { var reg = new RegExp('(https?|http|file|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]'); return reg.test(str); } /** * @function ChartViewModel.prototype.getStyle * @description 获取图表样式。 */ getStyle() { let style = { grid: this.grid, tooltip: this.tooltip, backgroundColor: this.backgroundColor } return style; } /** * @function ChartViewModel.prototype.getFeatures * @description 获取地图服务,数据服务请求返回的数据。 */ getFeatures() { return this.features; } /** * @function ChartViewModel.prototype.setStyle * @description 设置图表样式。 * @param {Object} style - 图表样式 */ setStyle(style) { return this.updateChartOptions(this.chartType, style); } } ;// CONCATENATED MODULE: ./src/common/components/chart/ChartView.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChartView * @aliasclass Components.Chart * @deprecatedclass SuperMap.Components.Chart * @classdesc 图表组件。 * @version 9.1.2 * @param {string} domID - 图表dom元素ID。 * @param {Object} options - 可选参数。 * @param {string} options.type - 图表类型。 * @param {ChartView.Datasets} options.datasets - 数据来源。 * @param {Array.} options.chartOptions - 图表可选参数。 * @param {Array.} options.chartOptions.xAxis - 图表X轴。 * @param {string} options.chartOptions.xAxis.field - 图表X轴字段名。 * @param {string} options.chartOptions.xAxis.name - 图表X轴名称。 * @param {Array.} options.chartOptions.yAxis - 图表Y轴。 * @param {string} options.chartOptions.yAxis.field - 图表Y轴字段名。 * @param {string} options.chartOptions.yAxis.name - 图表Y轴名称。 * @category Components Chart * @usage */ /** * @typedef {Object} ChartView.Datasets - 数据来源。 * @property {string} [type = 'iServer'] - 服务类型 iServer, iPortal。 * @property {string} url - 服务地址。 * @property {boolean} [withCredentials = false] - 设置请求是否带cookie。 * @property {FilterParameter} queryInfo - 查询条件。 */ class ChartView { constructor(domID, options) { this.domID = domID; this.chartType = options.type || "bar"; // 设置options.datasets.type的默认值是iServer options.datasets.type = options.datasets.type || 'iServer'; // 设置withCredentials的默认值为false options.datasets.withCredentials = options.datasets.withCredentials || false; this.viewModel = new ChartViewModel(options); //添加控件。 this._fillDataToView(); } /** * @function ChartView.prototype.onAdd * @description 创建图表之后成功回调。 * @param {function} addChart - 回调函数。 */ onAdd(addChart) { this.addChart = addChart; } /** * @function ChartView.prototype._fillDataToView * @description 填充数据到 view。 * @private */ _fillDataToView() { let messageboxs = new MessageBox(); //iclient 绑定createChart事件成功回调 this.viewModel.getDatasetInfo(this._createChart.bind(this)); this.viewModel.events.on({ "getdatafailed": (error) => { messageboxs.showView(error.message); } }); } /** * @function ChartView.prototype.getStyle * @description 获取图表样式。 */ getStyle() { return this.viewModel.getStyle() } /** * @function ChartView.prototype.getFeatures * @description 获取地图服务,数据服务请求返回的数据。 */ getFeatures() { return this.viewModel.getFeatures(); } /** * @function ChartView.prototype.setStyle * @description 设置图表样式。 * @param {Object} style - 图表样式,参考Echarts-options样式设置。 */ setStyle(style) { let newOptions = this.viewModel.setStyle(style); this._updateChart(newOptions); } /** * @function ChartView.prototype.changeType * @description 改变图表类型。 * @param {string} type - 图表类型。 */ changeType(type) { if (this.chartType !== type) { this.chartType = type; let newOptions = this.viewModel.changeType(type); this._updateChart(newOptions); } } /** * @function ChartView.prototype.updateData * @description 更新图表数据。 * @param {ChartView.Datasets} datasets - 数据来源。 * @param {Object} chartOption - X,Y轴信息。 */ updateData(datasets, chartOption) { let me = this; this.viewModel.updateData(datasets, chartOption, function (options) { me._updateChart(options); if (me.addChart) { me.addChart(); } }); } /** * @function ChartView.prototype._createChart * @description 创建图表。 * @private * @param {Object} data - 图表数据。 */ _createChart(data) { this.echart = external_function_try_return_echarts_catch_e_return_default().init( document.getElementById(this.domID), null, { renderer: "canvas" } ) let options = this.viewModel._createChartOptions(data); this.echart.setOption(options); if (this.addChart) { this.addChart(); } } /** * @function ChartView.prototype._updateChart * @description 更新图表。 * @private * @param {Object} options - 图表参数。 */ _updateChart(options) { if (this.echart) { this.echart.clear(); this.echart.setOption(options); } } } ;// CONCATENATED MODULE: ./src/common/components/templates/TemplateBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TemplateBase * @aliasclass Components.TemplateBase * @deprecatedclass SuperMap.Components.TemplateBase * @classdesc 组件公用组件父类,用于约束统一封装的公用组件结构。 * @version 9.1.1 * @param {Object} options - 组件配置参数。 * @param {string} options.id - 组件 dom 元素 id。 * @category Components Common * @usage */ class TemplateBase { constructor(options) { options = options ? options : {}; /** * @member {string} [TemplateBase.prototype.id=null] * @description 组件 dom 元素 id。 */ this.id = options.id ? options.id : null; /** * @member {HTMLElement} [TemplateBase.prototype.rootContainer=null] * @description 组件 dom 元素对象。 */ this.rootContainer = null; } /** * @function TemplateBase.prototype.getElement * @description 获取当前组件元素对象。 * @return {HTMLElement} 组件 dom 元素对象 */ getElement() { //todo 其实感觉再这里给组件设置不太合理 if (this.id) { this.rootContainer.id = this.id; } return this.rootContainer; } /** * @function TemplateBase.prototype._initView * @private * @description 初始化模板。 */ _initView() { //子类实现此方法 } /** * @function TemplateBase.prototype.showView * @description 显示组件。 */ showView() { this.rootContainer.hidden = false; } /** * @function TemplateBase.prototype.closeView * @description 隐藏组件。 */ closeView() { this.rootContainer.hidden = true; } } ;// CONCATENATED MODULE: ./src/common/components/templates/CommonContainer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class CommonContainer * @aliasclass Components.CommonContainer * @deprecatedclass SuperMap.Components.CommonContainer * @classdesc 组件统一外框。 * @version 9.1.1 * @param {Object} options - 组件配置参数。 * @param {string} options.id - 组件 dom 元素 id。 * @param {string} options.title - 标题。 * @category Components Common * @extends {TemplateBase} * @usage */ class CommonContainer extends TemplateBase { constructor(options) { super(options); let title = options.title ? options.title : ""; this._initView(title); } /** * @private * @override */ _initView(title) { const container = document.createElement("div"); container.setAttribute("class", "component-container"); //title const titleContainer = document.createElement("div"); titleContainer.setAttribute("class", "component-title"); const titleContent = document.createElement("div"); titleContent.innerHTML = title; titleContainer.appendChild(titleContent); container.appendChild(titleContainer); //container const componentContent = document.createElement("div"); componentContent.setAttribute("class", "component-content"); container.appendChild(componentContent); this.content = componentContent; this.rootContainer = container; return container; } /** * @function CommonContainer.prototype.getContentElement * @description 获取内容元素容器。 */ getContentElement() { return this.content; } /** * @function CommonContainer.prototype.appendContent * @description 填充内容元素。 */ appendContent(element) { this.content.appendChild(element); } } ;// CONCATENATED MODULE: ./src/common/components/templates/Select.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Select * @aliasclass Components.Select * @deprecatedclass SuperMap.Components.Select * @classdesc 组件统一的文字下拉框。 * @version 9.1.1 * @param {Array.} options - 组件配置参数数组。 * @param {string} options.id - 组件 dom 元素 id。 * @param {string} [options.labelName] - label 名称。 * @param {Array.} options.optionsArr - 需要创建的 option 数据数组。 * @param {function} [options.optionsClickCb] - option 点击事件回调函数。 * @extends {TemplateBase} * @category Components Common * @usage */ class Select extends TemplateBase { constructor(options) { super(options); this._initView(options); } _initView(options) { let selectTool = this._createElement('div', "component-selecttool"); if (options.labelName) { let label = this._createElement('label', 'component-selecttool__lable--describe', selectTool); label.innerHTML = options.labelName; } let chartSelect = this._createElement('div', 'component-selecttool--chart', selectTool); chartSelect.setAttribute('tabindex', '1'); let selectName = this._createElement('div', "component-selecttool__name", chartSelect); selectName.title = options.optionsArr[0]; selectName.innerHTML = options.optionsArr[0]; let chartTriangleBtn = this._createElement('div', 'component-selecttool__trianglebtn--chart', chartSelect); let triangleBtn = this._createElement('div', 'component-triangle-down-img', chartTriangleBtn); let selectContent = this._createElement('div', 'component-selecttool__content', chartSelect); let scrollarea = this._createElement('div', 'component-selecttool__content--chart', selectContent); let scrollareaContent = this._createElement('div', 'component-selecttool__scrollarea__content', scrollarea); scrollareaContent.setAttribute('tabindex', '1'); this.createOptions(scrollareaContent, options.optionsArr); this.optionClickEvent(scrollareaContent, selectName, options.optionsClickCb); // 下拉框显示 & 隐藏事件 this._selectClickEvent(chartSelect, selectContent, triangleBtn); this.rootContainer = selectTool; } /** * @function Select.prototype.createOptions * @description 创建所属下拉框选项。 */ createOptions(container, optionsArr) { for (let i in optionsArr) { let option = this._createElement('div', 'component-selecttool__option', container); option.title = optionsArr[i]; option.innerHTML = optionsArr[i]; } } /** * @function Select.prototype._selectClickEvent * @description select 点击显示&隐藏事件。 * @private */ _selectClickEvent(eventElement, contentElement, triangleBtn) { eventElement.onclick = function (e) { if (contentElement.style.display === "block") { contentElement.style.display = "none"; triangleBtn.className = "component-triangle-down-img"; } else { contentElement.style.display = "block"; triangleBtn.className = "triangle-up-img"; } e.preventDefault(); e.stopPropagation(); }; eventElement.onmousedown = function (evt) { //console.log('dropdownbox onmousedown '+evt.target.className); if (evt.target !== this) { this.focus(); evt.preventDefault(); evt.stopPropagation() } }; eventElement.onblur = function () { contentElement.style.display = "none"; triangleBtn.className = "component-triangle-down-img"; } } /** * @function Select.prototype._createElement * @description 通用创建元素。 * @private */ _createElement(tagName, className, parentEle) { let ele = document.createElement(tagName || 'div'); className && (ele.className = className); parentEle && parentEle.appendChild(ele); return ele; } /** * @function Select.prototype.optionClickEvent * @description 下拉框的 option 的点击事件。 */ optionClickEvent(optionEleArr, selectNameEle, optionsClickCb) { for (let i = 0; i < optionEleArr.children.length; i++) { let childEle = optionEleArr.children[i]; childEle.onclick = function () { selectNameEle.innerHTML = childEle.innerHTML; selectNameEle.title = childEle.title; if (childEle.getAttribute('data-value')) { selectNameEle.setAttribute('data-value', childEle.getAttribute('data-value')) } optionsClickCb && optionsClickCb(childEle); } } } } ;// CONCATENATED MODULE: ./src/common/components/templates/DropDownBox.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DropDownBox * @aliasclass Components.DropDownBox * @deprecatedclass SuperMap.Components.DropDownBox * @classdesc 组件统一的图片下拉框。 * @version 9.1.1 * @param {Array.} options - 组件配置参数数组。 * @param {string} options.id - 组件 dom 元素 id。 * @param {string} options.title - 下拉框 title。 * @param {string} options.remark - 下拉框解释标记文本。 * @param {string} [options.dataValue] - 下拉框 attribute 名为 data-value 的值 。 * @param {string} [options.icon] - 下拉框图标。 * @param {string} [options.icon.className] - 下拉框图标类名。 * @param {string} [options.icon.background] - 下拉框图标背景 url。 * @category Components Common * @extends {TemplateBase} * @usage */ class DropDownBox extends TemplateBase { constructor(optionsArr) { super(optionsArr); this._initView(optionsArr); } /** * @function DropDownBox.prototype._initView * @description 初始化下拉框。 * @private * @override */ _initView(optionsArr) { let dropDownContainer = document.createElement('div'); dropDownContainer.className = 'component-dropdownbox--container'; let dropDownBox = document.createElement('div'); dropDownBox.setAttribute('tabindex', '1'); dropDownBox.className = "component-dropdownbox"; dropDownContainer.appendChild(dropDownBox); let dropDownTopContainer = document.createElement('div'); dropDownBox.appendChild(dropDownTopContainer); this._createDropDownOption(optionsArr[0], dropDownTopContainer); let triangleBtnContainer = document.createElement('div'); triangleBtnContainer.className = 'component-dropdownbox__triangle-btn'; dropDownBox.appendChild(triangleBtnContainer); let triangleBtn = document.createElement('div'); triangleBtn.className = 'component-triangle-down-img'; triangleBtnContainer.appendChild(triangleBtn); let createDropDownBoxParam = { "parentEle": dropDownBox, "dropDownContent": ['component-dropdownbox__content component-dropdownbox__content--chart', 'dropDownContent'], "scrollareaContent": 'component-selecttool__scrollarea__content', "optionsArr": optionsArr, "triangleBtn": triangleBtn, "dropDownTopContainer": dropDownTopContainer }; this._createDropDownBox(createDropDownBoxParam); this.rootContainer = dropDownContainer; } /** * @function DropDownBox.prototype._createDropDownBox * @description 创建下拉框。 * @private */ _createDropDownBox(createDropDownBoxParam) { let dropDownBox = createDropDownBoxParam.parentEle; let dropDownTopContainer = createDropDownBoxParam.dropDownTopContainer; let dropDownContent = document.createElement('div'); dropDownContent.className = createDropDownBoxParam.dropDownContent[0]; dropDownBox.appendChild(dropDownContent); let scrollareaContent = document.createElement('div'); scrollareaContent.className = createDropDownBoxParam.scrollareaContent; dropDownContent.appendChild(scrollareaContent); let optionsArr = createDropDownBoxParam.optionsArr; for (let i = 0; i < optionsArr.length; i++) { this._createDropDownOption(optionsArr[i], scrollareaContent) } // 下拉框显示 & 隐藏事件 let triangleBtn = createDropDownBoxParam.triangleBtn; this._dropDownClickEvent(dropDownBox, dropDownContent, triangleBtn); this._eleOnblur(dropDownBox, dropDownContent, triangleBtn); // 下拉框 options 点击事件 let scrollareaOptions = scrollareaContent.children; for (let i = 0; i < scrollareaOptions.length; i++) { scrollareaOptions[i].onclick = function () { dropDownTopContainer.innerHTML = scrollareaOptions[i].outerHTML; //evt.stopPropagation(); } } } /** * @function DropDownBox.prototype._createDropDownOption * @description 创建下拉框子元素。 * @private */ _createDropDownOption(data, parentElement) { let ele = document.createElement('div'); ele.className = 'component-dropdownbox__item'; let dataItem = data; if (dataItem['dataValue']) { ele.setAttribute('data-value', dataItem['dataValue']); } parentElement.appendChild(ele); let imgContainer = document.createElement('div'); imgContainer.className = 'component-dropdownbox__item__img'; ele.appendChild(imgContainer); let img = document.createElement('div'); if (dataItem.icon.className) { img.className = dataItem.icon.className; } if (dataItem.icon.background) { img.style.background = dataItem.icon.background; } imgContainer.appendChild(img); let title = document.createElement('div'); title.className = 'component-dropdownbox__item__title'; title.title = dataItem.title; title.innerHTML = dataItem.title; ele.appendChild(title); let remark = document.createElement('div'); remark.className = 'component-dropdownbox__item__remark'; remark.title = dataItem.remark; remark.innerHTML = dataItem.remark; ele.appendChild(remark); } /** * @function DropDownBox.prototype._dropDownClickEvent * @description 下拉框点击事件。 * @private */ _dropDownClickEvent(eventElement, contentElement, triangleBtn) { eventElement.onclick = function (e) { if (contentElement.style.display === "block") { contentElement.style.display = "none"; triangleBtn.className = "component-triangle-down-img"; } else { contentElement.style.display = "block"; triangleBtn.className = "triangle-up-img"; } e.preventDefault(); e.stopPropagation() }; eventElement.onmousedown = function (evt) { //console.log('dropdownbox onmousedown '+evt.target.className); if (evt.target !== this) { this.focus(); evt.preventDefault(); evt.stopPropagation() } } } /** * @function DropDownBox.prototype._eleOnblur * @description 下拉框失焦事件。 * @private */ _eleOnblur(eventElement, contentElement, triangleBtn) { eventElement.onblur = function () { contentElement.style.display = "none"; triangleBtn.className = "component-triangle-down-img"; } } /** * @function DropDownBox.prototype._createElement * @description 通用创建元素。 * @private */ _createElement(tagName, className, parentEle) { let ele = document.createElement(tagName || 'div'); className && (ele.className = className); parentEle && parentEle.appendChild(ele); return ele; } } ;// CONCATENATED MODULE: ./src/common/components/templates/PopContainer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class PopContainer * @aliasclass Components.PopContainer * @deprecatedclass SuperMap.Components.PopContainer * @classdesc 弹框组件。 * @version 9.1.1 * @param {Object} options - 组件配置参数。 * @param {string} options.id - 组件 dom 元素 id。 * @param {string} options.title - 弹框组件名称。 * @extends {TemplateBase} * @category Components Common * @usage */ class PopContainer extends TemplateBase { constructor(options) { options = options ? options : {}; super(options); options.title = options.title ? options.title : ""; this._initView(options.title); } /** * @private * @override */ _initView(titile) { const container = document.createElement("div"); container.setAttribute("class", "component-popcontainer"); //header const header = document.createElement("div"); header.setAttribute("class", "component-popcontainer__header"); const title = document.createElement("label"); title.setAttribute("class", "component-popcontainer__header__title"); title.innerHTML = titile; header.appendChild(title); const closeBtn = document.createElement("span"); closeBtn.setAttribute("class", "supermapol-icons-clear component-popcontainer__header__close"); closeBtn.onclick = this.closeView.bind(this); container.appendChild(closeBtn); container.appendChild(header); //content const content = document.createElement("div"); content.setAttribute("class", "component-popcontainer__content"); this.content = content; container.appendChild(content); this.rootContainer = container; } /** * @function PopContainer.prototype.appendContent * @description 追加内容。 * @param {HTMLElement} dom - 内容元素。 */ appendContent(dom) { this.content.appendChild(dom); } } ;// CONCATENATED MODULE: ./src/common/components/templates/AttributesPopContainer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class AttributesPopContainer * @aliasclass Components.AttributesPopContainer * @deprecatedclass SuperMap.Components.AttributesPopContainer * @classdesc 属性弹框组件 * @version 9.1.1 * @param {Object} options - 组件配置参数。 * @param {string} options.id - 组件 dom 元素 id。 * @param {Object} options.title - 属性弹框组件名称。 * @param {Object} options.attributes - 组件需要显示的属性内容。 * @extends {PopContainer} * @category Components Common * @usage */ class AttributesPopContainer extends PopContainer { constructor(options) { //默认为属性: options.title = options.title ? options.title : "属性"; super(options); this.rootContainer.firstChild.hidden = true; options.attributes = options.attributes ? options.attributes : []; this._createAttributesTable(options.attributes); } _createAttributesTable(attributes) { const table = document.createElement("table"); table.setAttribute("class", "component-popcontainer__content__table"); const tbody = document.createElement("tbody"); let single = true; for (let name in attributes) { const tr = document.createElement("tr"); if (single) { tr.setAttribute("class", "component-popcontainer__content__td--color"); } const title = document.createElement("td"); const titleSpan = document.createElement("Span"); titleSpan.innerHTML = name; title.appendChild(titleSpan); const value = document.createElement("td"); value.innerHTML = attributes[name]; tr.appendChild(title); tr.appendChild(value); tbody.appendChild(tr); single = !single; } table.appendChild(tbody); this.appendContent(table); } } ;// CONCATENATED MODULE: ./src/common/components/templates/IndexTabsPageContainer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class IndexTabsPageContainer * @aliasclass Components.IndexTabsPageContainer * @deprecatedclass SuperMap.Components.IndexTabsPageContainer * @classdesc 标签索引组件。 * @version 9.1.1 * @param {Object} options - 组件配置参数。 * @param {string} options.id - 组件 dom 元素 id。 * @category Components Common * @extends {TemplateBase} * @usage */ class IndexTabsPageContainer extends TemplateBase { constructor(options) { super(options); this._initView(); } /** * @private * @override */ _initView() { const container = document.createElement("div"); container.setAttribute("class", "component-tabpage"); const header = document.createElement("ul"); this.header = header; const content = document.createElement("div"); content.setAttribute("class", "component-tabpage__content"); this.content = content; container.appendChild(header); container.appendChild(content); this.rootContainer = container; } /** * @function IndexTabsPageContainer.prototype.setTabs * @description 设置标签元素。 * @param {Array.} tabs */ setTabs(tabs) { this.removeAllTabs(); this.appendTabs(tabs); } /** * @function IndexTabsPageContainer.prototype.appendTabs * @description 追加标签元素。 * @param {Array.} tabs */ appendTabs(tabs) { for (let i = 0; i < tabs.length; i++) { let title = document.createElement("span"); title.index = i; title.appendChild(document.createTextNode(tabs[i].title)); //绑定标签切换对应页面: title.onclick = this._changeTabsPage.bind(this); let content = tabs[i].content; content.index = i; content.hidden = true; this.header.appendChild(title); this.content.appendChild(content); } //todo 确认是否两个子元素的 index 相互对应 //默认显示第一个标签对象 this.header.firstChild.setAttribute("class", "on"); this.content.firstChild.hidden = false; } /** * @function IndexTabsPageContainer.prototype.removeTab * @description 删除某个标签页面。 * @param {number} index - 标签索引号。 */ removeTab(index) { this.header.removeChild(this.header.children[index]); this.content.removeChild(this.content.children[index]); } /** * @function IndexTabsPageContainer.prototype.removeAllTabs * @description 删除所有标签。 */ removeAllTabs() { for (let i = this.header.children.length; i > 0; i--) { this.header.removeChild(this.header.children[i]); this.content.removeChild(this.content.children[i]); } } _changeTabsPage(e) { const index = e.target.index; for (let i = 0; i < this.header.children.length; i++) { this.header.children[i].setAttribute("class", ""); this.content.children[i].hidden = true; if (i === index) { this.header.children[i].setAttribute("class", "on"); this.content.children[i].hidden = false; } } } } ;// CONCATENATED MODULE: ./src/common/components/templates/CityTabsPage.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class CityTabsPage * @aliasclass Components.CityTabsPage * @deprecatedclass SuperMap.Components.CityTabsPage * @classdesc 城市地址匹配组件模板 * @version 9.1.1 * @param {Object} options - 组件配置参数。 * @param {string} options.id - 组件 dom 元素 id。 * @param {Object|Array.} options.config - 城市名称配置列表,支持两种格式:{key1:{A:[],B:[]}, key2:{C:[],D:[]}} 或 * ["成都市","北京市"],用户可根据自己的项目需求进行配置 * @extends {IndexTabsPageContainer} * @category Components Common * @usage */ class CityTabsPage extends IndexTabsPageContainer { constructor(options) { super(options); //去掉默认的边框阴影样式: this.rootContainer.classList.add("component-citytabpage--noneBoxShadow"); this.config = options.config; //header,若 config为城市名称数组,则直接加载内容 if (Util.isArray(this.config)) { this.header.hidden = true; this._createCityItem("城市", this.config); this.content.style.border = "none"; } else { this._createTabs(); this.header.onclick = (e) => { //关闭所有元素 是否有更简化的写法? for (let i = 0; i < this.header.children.length; i++) { this.header.children[i].setAttribute("class", ""); } //打开点击内容元素 e.target.setAttribute("class", "on"); this._createCityContent(e.target.innerHTML); }; } } /** * @function CityTabsPage.prototype._createTabs * @description 创建 Tabs * @private */ _createTabs() { //header if (Util.isArray(this.config)) { for (let i = 0; i < this.config.length; i++) { let innerHTML = ""; for (const key in this.config[i]) { innerHTML += key; } let li = document.createElement("li"); li.innerHTML = innerHTML; this.header.appendChild(li); } } else { for (const key in this.config) { let li = document.createElement("li"); li.innerHTML = key; this.header.appendChild(li); } } this.header.firstChild.setAttribute("class", "on"); this._createCityContent(this.header.firstChild.innerHTML); } /** * @function CityTabsPage.prototype._createCityContent * @description 创建列表容器 * @private */ _createCityContent(keyName) { //清除元素: for (let i = this.content.children.length; i > 0; i--) { this.content.removeChild(this.content.children[i - 1]); } //创建对应元素 const cities = this.config[keyName]; for (let key in cities) { this._createCityItem(key, cities[key]); } } /** * @function CityTabsPage.prototype._createCityContent * @description 创建列表容器 * @private */ _createCityItem(key, cities) { const city = document.createElement("div"); const cityClass = document.createElement("div"); cityClass.setAttribute("class", "component-citytabpag__py-key"); cityClass.innerHTML = key; city.appendChild(cityClass); const cityContent = document.createElement("div"); cityContent.setAttribute("class", "component-citytabpag__content"); for (let i = 0; i < cities.length; i++) { let span = document.createElement("span"); span.innerHTML = cities[i]; cityContent.appendChild(span); } //HOT 元素长度单独微调: if (key === "HOT") { cityContent.style.width = "428px"; } city.appendChild(cityContent); this.content.appendChild(city); } } ;// CONCATENATED MODULE: ./src/common/components/templates/NavTabsPage.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class NavTabsPage * @aliasclass Components.NavTabsPage * @deprecatedclass SuperMap.Components.NavTabsPage * @classdesc 标签页面组件。 * @version 9.1.1 * @param {Object} options - 组件配置参数。 * @param {string} options.id - 组件 dom 元素 id。 * @param {Array.} [options.tabs=[]] - 标签对象数组,形如:[{title: "",content: HTMLElement}],初始时,传入则创建页面。 * @extends {TemplateBase} * @category Components Common * @usage */ // todo 思考拆分的控件应该以哪种方式使用 class NavTabsPage extends TemplateBase { constructor(options) { super(options); this.navTabsTitle = null; this.navTabsContent = null; options.tabs = options.tabs ? options.tabs : []; this._initView(options.tabs); } /** * @override * @private */ _initView(tabs) { const navTabsPage = document.createElement("div"); navTabsPage.setAttribute("class", "component-navtabspage"); //关闭按钮 const closeBtn = document.createElement("span"); closeBtn.setAttribute("class", "supermapol-icons-close"); closeBtn.onclick = this.closeView.bind(this); navTabsPage.appendChild(closeBtn); //标签 const navTabsTitle = document.createElement("div"); this.navTabsTitle = navTabsTitle; navTabsTitle.setAttribute("class", "component-navtabspage__title"); navTabsPage.appendChild(navTabsTitle); //内容 const navTabsContent = document.createElement("div"); this.navTabsContent = navTabsContent; navTabsContent.setAttribute("class", "component-navtabspage__content"); navTabsPage.appendChild(navTabsContent); //若 tabs 初始传入值,则 if (tabs.length > 0) { this.appendTabs(tabs); } this.rootContainer = navTabsPage; } /** * @function NavTabsPage.prototype.setTabs * @description 设置标签。 * @param {Array.} tabs - 标签对象数组,形如:[{title: "",content: {}}]。 */ setTabs(tabs) { this.removeAllTabs(); this.appendTabs(tabs); } /** * @function NavTabsPage.prototype.appendTabs * @description 添加标签页面。 * @param {Array.} tabs - 标签对象数组,形如:[{title: "",content: {}}]。 */ appendTabs(tabs) { for (let i = 0; i < tabs.length; i++) { let title = document.createElement("span"); title.index = i; title.appendChild(document.createTextNode(tabs[i].title)); //绑定标签切换对应页面: title.onclick = this._changeTabsPage.bind(this); let content = tabs[i].content; content.index = i; content.hidden = true; this.navTabsTitle.appendChild(title); this.navTabsContent.appendChild(content); } //todo 确认是否两个子元素的 index 相互对应 //默认显示第一个标签对象 this.navTabsTitle.firstChild.setAttribute("class", "component-navtabspage__tabs--select"); this.navTabsContent.firstChild.hidden = false; } /** * @function NavTabsPage.prototype.removeTab * @description 删除某个标签页面。 * @param {number} index - 标签索引号。 */ removeTab(index) { this.navTabsTitle.removeChild(this.navTabsTitle.children[index]); this.navTabsContent.removeChild(this.navTabsContent.children[index]); } /** * @function NavTabsPage.prototype.removeAllTabs * @description 删除所有标签。 */ removeAllTabs() { for (let i = this.navTabsTitle.children.length; i > 0; i--) { this.navTabsTitle.removeChild(this.navTabsTitle.children[i]); this.navTabsContent.removeChild(this.navTabsContent.children[i]); } } _changeTabsPage(e) { const index = e.target.index; for (let i = 0; i < this.navTabsTitle.children.length; i++) { this.navTabsTitle.children[i].setAttribute("class", ""); this.navTabsContent.children[i].hidden = true; if (i === index) { this.navTabsTitle.children[i].setAttribute("class", "component-navtabspage__tabs--select"); this.navTabsContent.children[i].hidden = false; } } } } ;// CONCATENATED MODULE: ./src/common/components/templates/PaginationContainer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class PaginationContainer * @aliasclass Components.PaginationContainer * @deprecatedclass SuperMap.Components.PaginationContainer * @classdesc 分页组件模板。 * @version 9.1.1 * @param {Object} options - 组件配置参数。 * @param {string} options.id - 组件 dom 元素 id。 * @param {HTMLElement} options.contents - 页面填充的 DOM 元素对象。 * @param {number} options.pageCounts - 页数。 * @extends {TemplateBase} * @category Components Common * @usage */ class PaginationContainer extends TemplateBase { constructor(options) { options = options ? options : {}; super(options); this.currentPage = 0; this.pageNumberLis = []; this.currentPageNumberLis = []; this.linkageEvent = null; options.contents = options.contents ? options.contents : null; options.pageCounts = options.pageCounts ? options.pageCounts : 0; this._initView(options.contents, options.pageCounts); } /** * @function PaginationContainer.prototype.setLinkageEvent * @description 设置页面联动方法。 * @param {function} linkageEvent - 联动方法,实现指定功能。 */ setLinkageEvent(linkageEvent) { this.linkageEvent = linkageEvent; } /** * @private * @override */ _initView(contents, pageCounts) { const container = document.createElement("div"); container.setAttribute("class", "component-pagination"); //content const content = document.createElement("div"); content.setAttribute("class", "component-pagination__content"); container.appendChild(content); this.content = content; //link const link = document.createElement("ul"); link.setAttribute("class", "component-pagination__link"); link.onclick = this._changePageEvent.bind(this); container.appendChild(link); this._createLink(link); this.link = link; //填充内容: if (contents) { this.setContent(contents); } if (pageCounts !== 0) { this.setPageLink(pageCounts); } this.rootContainer = container; } /**---------以下是页面相关操作 **/ /** * @function PaginationContainer.prototype.setContent * @description 设置页面内容。 * @param {HTMLElement} element - 页面内容元素。 */ setContent(element) { this.clearContent(); this.appendContent(element); } /** * @function PaginationContainer.prototype.appendContent * @description 追加内容。 * @param {HTMLElement} element - 页面内容元素。 */ appendContent(element) { this.content.appendChild(element); } /** * @function PaginationContainer.prototype.clearContent * @description 清空内容元素。 */ clearContent() { for (let i = this.content.children.length - 1; i >= 0; i--) { this.content.removeChild(this.content.children[i]); } } /** -----以下是页码相关的操作:**/ /** * @function PaginationContainer.prototype.setPageLink * @description 设置页码数。 * @param {number} pageNumber - 页码数。 */ setPageLink(pageNumber) { //清空当前页码 this.pageNumberLis = []; this.currentPageNumberLis = []; this.clearPageLink(); //创建页码 this._createPageLi(pageNumber); //添加页码到页码列表 this._appendPageLink(); } /** * @description 创建页码。 * @param pageNumber * @private */ _createPageLi(pageNumber) { for (let i = 0; i < pageNumber; i++) { const pageLi = document.createElement("li"); pageLi.innerHTML = i + 1; /*const liContent = document.createElement("span"); liContent.innerHTML = i + 1;*/ // pageLi.appendChild(liContent); this.pageNumberLis.push(pageLi); } this.pageNumberLis[0].setAttribute("class", "active"); this.currentPage = 1; if (pageNumber < 5) { this.currentPageNumberLis = this.pageNumberLis; } else { for (let i = 0; i < 5; i++) { this.currentPageNumberLis.push(this.pageNumberLis[i]); } } } /** * @description 添加页码到页码列表。 * @private */ _appendPageLink() { //todo 如何插入中间 for (let i = 0; i < this.currentPageNumberLis.length; i++) { this.link.insertBefore(this.currentPageNumberLis[i], this.link.childNodes[this.link.children.length - 2]); } for (let i = 0; i < this.currentPageNumberLis.length; i++) { //清空 active 状态 this.currentPageNumberLis[i].setAttribute("class", ""); //给当前选中的 li 赋值 active 状态 if (Number(this.currentPageNumberLis[i].innerHTML) === this.currentPage) { this.currentPageNumberLis[i].setAttribute("class", "active"); } } //根据 currentPage 改变按钮状态 this._changeDisableState(); if (this.linkageEvent) { this.linkageEvent(this.currentPage); } } /** * @function PaginationContainer.prototype.clearPageLink * @description 清除页码列表。 */ clearPageLink() { for (let i = this.link.children.length - 3; i > 1; i--) { this.link.removeChild(this.link.children[i]); } } /** * @description 创建页码按钮。 * @param ul * @private */ _createLink(ul) { for (let i = 0; i < 4; i++) { const li = document.createElement("li"); li.setAttribute("class", "disable"); const liContent = document.createElement("span"); li.appendChild(liContent); if (i === 0) { liContent.id = "first"; liContent.setAttribute("class", "supermapol-icons-first"); } else if (i === 1) { liContent.id = "prev"; liContent.setAttribute("class", "supermapol-icons-prev"); } else if (i === 2) { liContent.id = "next"; liContent.setAttribute("class", "supermapol-icons-next"); } else if (i === 3) { liContent.id = "last"; liContent.setAttribute("class", "supermapol-icons-last"); } ul.appendChild(li); } } /** * @description 点击页码事件。 * @param e * @private */ _changePageEvent(e) { //todo const trigger = e.target; //若列表禁用,点击无效 if (trigger.parentElement.classList[0] === "disable") { return; } let targetLi; if (trigger.id) { targetLi = trigger.id; } else if (Number(trigger.innerHTML)) { targetLi = Number(trigger.innerHTML); } else { return; } //页码预处理: this._prePageNum(targetLi); //根据 currentPageNumberLis 创建页码列表 this.clearPageLink(); this._appendPageLink(); } /** * @description 根据 currentPage 改变按钮状态。 * @private */ _changeDisableState() { this.link.children[0].setAttribute("class", ""); this.link.children[1].setAttribute("class", ""); this.link.children[this.link.children.length - 1].setAttribute("class", ""); this.link.children[this.link.children.length - 2].setAttribute("class", ""); if (this.currentPage === 1) { this.link.children[0].setAttribute("class", "disable"); this.link.children[1].setAttribute("class", "disable"); } if (this.currentPage === this.pageNumberLis.length) { this.link.children[this.link.children.length - 1].setAttribute("class", "disable"); this.link.children[this.link.children.length - 2].setAttribute("class", "disable"); } } /** * @description 根据点击页码列表事件准备需展现的页码列表。 * @param {string|number} targetLi - 被点击的列表对象 id 或 被点击的页码值。 * @private */ _prePageNum(targetLi) { const currentPageNumberLis = []; if (targetLi === "first") { this.currentPage = 1; } else if (targetLi === "last") { this.currentPage = this.pageNumberLis.length; } else if (targetLi === "prev") { this.currentPage = this.currentPage - 1; } else if (targetLi === "next") { this.currentPage = this.currentPage + 1; } else { this.currentPage = targetLi; } if (this.pageNumberLis.length <= 5) { for (let i = 0; i < this.pageNumberLis.length; i++) { currentPageNumberLis.push(this.pageNumberLis[i]); } } else { //当前点击前三,都取前五 if (this.currentPage <= 3) { for (let i = 0; i < 5; i++) { currentPageNumberLis.push(this.pageNumberLis[i]); } } else if (this.currentPage >= this.pageNumberLis.length - 3) { //点击后三,都取后5 for (let i = this.pageNumberLis.length - 5; i < this.pageNumberLis.length; i++) { currentPageNumberLis.push(this.pageNumberLis[i]); } } else { //其他,取中间: for (let i = this.currentPage - 3; i <= this.currentPage + 1; i++) { currentPageNumberLis.push(this.pageNumberLis[i]); } } } if (currentPageNumberLis.length > 0) { this.currentPageNumberLis = currentPageNumberLis; } } } ;// CONCATENATED MODULE: ./src/common/components/util/Util.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @name ComponentsUtil * @namespace * @category BaseTypes Util * @description 获取文件类型工具类。 * @usage * ``` * // 浏览器 * * * // ES6 Import * import { ComponentsUtil } from '{npm}'; * * const result = ComponentsUtil.getFileType(fileName); * ``` */ let ComponentsUtil = { /** * @function ComponentsUtil.getFileType * @description 获取上传文件类型。 * @param {string} fileName - 文件名称。 */ getFileType(fileName) { let regCSV = /^.*\.(?:csv)$/i; let regExcel = /^.*\.(?:xls|xlsx)$/i; //文件名可以带空格 let regGeojson = /^.*\.(?:geojson|json)$/i; if (regExcel.test(fileName)) { //校验不通过 return CommonTypes_FileTypes.EXCEL; } else if (regCSV.test(fileName)) { return CommonTypes_FileTypes.CSV; } else if (regGeojson.test(fileName)) { return CommonTypes_FileTypes.GEOJSON; } return null; } }; ;// CONCATENATED MODULE: ./src/common/components/util/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/components/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ //数据 //组件 //提示框组件 //图表组件 //公用模板: //工具类 ;// CONCATENATED MODULE: ./src/common/lang/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/index.common.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/common/index.all.js ;// CONCATENATED MODULE: ./src/common/namespace.js /* Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /* Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ // Lang SuperMap.Lang = Lang; SuperMap.i18n = SuperMap.Lang.i18n; // CommonUtil SuperMap.Util = { ...SuperMap.Util, ...Util }; SuperMap.Browser = Browser; SuperMap.INCHES_PER_UNIT = INCHES_PER_UNIT; SuperMap.METERS_PER_INCH = METERS_PER_INCH; SuperMap.DOTS_PER_INCH = DOTS_PER_INCH; SuperMap.IS_GECKO = IS_GECKO; // FetchRequest SuperMap.setCORS = setCORS; SuperMap.isCORS = isCORS; SuperMap.setRequestTimeout = setRequestTimeout; SuperMap.getRequestTimeout = getRequestTimeout; SuperMap.FetchRequest = FetchRequest; // commontypes SuperMap.inherit = inheritExt; SuperMap.mixin = mixinExt; SuperMap.String = StringExt; SuperMap.Number = NumberExt; SuperMap.Function = FunctionExt; SuperMap.Array = ArrayExt; SuperMap.Date = DateExt; SuperMap.Event = Event; SuperMap.Bounds = Bounds; SuperMap.Credential = Credential; SuperMap.Events = Events; SuperMap.Feature = Feature_Feature; SuperMap.Geometry = Geometry_Geometry; SuperMap.Pixel = Pixel; SuperMap.Size = Size; SuperMap.Feature.Vector = Vector; SuperMap.Geometry.Collection = Collection; SuperMap.Geometry.Curve = Curve; SuperMap.Geometry.GeoText = GeoText; SuperMap.Geometry.LinearRing = LinearRing; SuperMap.Geometry.LineString = LineString; SuperMap.Geometry.MultiLineString = MultiLineString; SuperMap.Geometry.MultiPoint = MultiPoint; SuperMap.Geometry.MultiPolygon = MultiPolygon; SuperMap.Geometry.Point = Point; SuperMap.Geometry.Polygon = Polygon; SuperMap.Geometry.Rectangle = Rectangle; // Components SuperMap.Components.Chart = ChartView; SuperMap.Components.ChartViewModel = ChartViewModel; SuperMap.Components.MessageBox = MessageBox; SuperMap.Components.AttributesPopContainer = AttributesPopContainer; SuperMap.Components.CityTabsPage = CityTabsPage; SuperMap.Components.CommonContainer = CommonContainer; SuperMap.Components.DropDownBox = DropDownBox; SuperMap.Components.IndexTabsPageContainer = IndexTabsPageContainer; SuperMap.Components.NavTabsPage = NavTabsPage; SuperMap.Components.PaginationContainer = PaginationContainer; SuperMap.Components.PopContainer = PopContainer; SuperMap.Components.Select = Select; SuperMap.Components.TemplateBase = TemplateBase; SuperMap.Components.FileReaderUtil = FileReaderUtil; // control SuperMap.TimeControlBase = TimeControlBase; SuperMap.TimeFlowControl = TimeFlowControl; // Format SuperMap.Format = SuperMap.Format || Format; SuperMap.Format.GeoJSON = GeoJSON; SuperMap.Format.JSON = JSONFormat; SuperMap.Format.WKT = WKT; // iManager SuperMap.iManager = IManager; SuperMap.iManagerCreateNodeParam = IManagerCreateNodeParam; SuperMap.iManagerServiceBase = IManagerServiceBase; // iPortal SuperMap.iPortal = IPortal; SuperMap.iPortalAddDataParam = IPortalAddDataParam; SuperMap.iPortalAddResourceParam = IPortalAddResourceParam; SuperMap.iPortalDataConnectionInfoParam = IPortalDataConnectionInfoParam; SuperMap.iPortalDataMetaInfoParam = IPortalDataMetaInfoParam; SuperMap.iPortalDataStoreInfoParam = IPortalDataStoreInfoParam; SuperMap.iPortalQueryParam = IPortalQueryParam; SuperMap.iPortalQueryResult = IPortalQueryResult; SuperMap.iPortalRegisterServiceParam = IPortalRegisterServiceParam; SuperMap.iPortalResource = IPortalResource; SuperMap.iPortalServiceBase = IPortalServiceBase; SuperMap.iPortalShareEntity = IPortalShareEntity; SuperMap.iPortalShareParam = IPortalShareParam; SuperMap.iPortalUser = IPortalUser; // iServer SuperMap.AddressMatchService = AddressMatchService_AddressMatchService; SuperMap.AggregationParameter = AggregationParameter; SuperMap.AreaSolarRadiationParameters = AreaSolarRadiationParameters; SuperMap.AreaSolarRadiationService = AreaSolarRadiationService; SuperMap.BucketAggParameter = BucketAggParameter; SuperMap.BufferAnalystParameters = BufferAnalystParameters; SuperMap.BufferAnalystService = BufferAnalystService; SuperMap.BufferDistance = BufferDistance; SuperMap.BuffersAnalystJobsParameter = BuffersAnalystJobsParameter; SuperMap.BuffersAnalystJobsService = BuffersAnalystJobsService; SuperMap.BufferSetting = BufferSetting; SuperMap.BurstPipelineAnalystParameters = BurstPipelineAnalystParameters; SuperMap.BurstPipelineAnalystService = BurstPipelineAnalystService; SuperMap.ChartFeatureInfoSpecsService = ChartFeatureInfoSpecsService; SuperMap.ChartQueryFilterParameter = ChartQueryFilterParameter; SuperMap.ChartQueryParameters = ChartQueryParameters; SuperMap.ChartQueryService = ChartQueryService; SuperMap.ClipParameter = ClipParameter; SuperMap.ColorDictionary = ColorDictionary; SuperMap.CommonServiceBase = CommonServiceBase; SuperMap.ComputeWeightMatrixParameters = ComputeWeightMatrixParameters; SuperMap.ComputeWeightMatrixService = ComputeWeightMatrixService; SuperMap.CreateDatasetParameters = CreateDatasetParameters; SuperMap.DataFlowService = DataFlowService_DataFlowService; SuperMap.DataReturnOption = DataReturnOption; SuperMap.DatasetBufferAnalystParameters = DatasetBufferAnalystParameters; SuperMap.DatasetInfo = DatasetInfo; SuperMap.DatasetOverlayAnalystParameters = DatasetOverlayAnalystParameters; SuperMap.DatasetService = DatasetService_DatasetService; SuperMap.DatasetSurfaceAnalystParameters = DatasetSurfaceAnalystParameters; SuperMap.DatasetThiessenAnalystParameters = DatasetThiessenAnalystParameters; SuperMap.DatasourceConnectionInfo = DatasourceConnectionInfo; SuperMap.DatasourceService = DatasourceService_DatasourceService; SuperMap.DensityAnalystService = DensityAnalystService; SuperMap.DensityKernelAnalystParameters = DensityKernelAnalystParameters; SuperMap.EditFeaturesParameters = EditFeaturesParameters; SuperMap.EditFeaturesService = EditFeaturesService; SuperMap.FacilityAnalyst3DParameters = FacilityAnalyst3DParameters; SuperMap.FacilityAnalystSinks3DParameters = FacilityAnalystSinks3DParameters; SuperMap.FacilityAnalystSinks3DService = FacilityAnalystSinks3DService; SuperMap.FacilityAnalystSources3DParameters = FacilityAnalystSources3DParameters; SuperMap.FacilityAnalystSources3DService = FacilityAnalystSources3DService; SuperMap.FacilityAnalystStreamParameters = FacilityAnalystStreamParameters; SuperMap.FacilityAnalystStreamService = FacilityAnalystStreamService; SuperMap.FacilityAnalystTracedown3DParameters = FacilityAnalystTracedown3DParameters; SuperMap.FacilityAnalystTracedown3DService = FacilityAnalystTracedown3DService; SuperMap.FacilityAnalystTraceup3DParameters = FacilityAnalystTraceup3DParameters; SuperMap.FacilityAnalystTraceup3DService = FacilityAnalystTraceup3DService; SuperMap.FacilityAnalystUpstream3DParameters = FacilityAnalystUpstream3DParameters; SuperMap.FacilityAnalystUpstream3DService = FacilityAnalystUpstream3DService; SuperMap.FieldParameters = FieldParameters; SuperMap.FieldsFilter = FieldsFilter; SuperMap.FieldStatisticService = FieldStatisticService; SuperMap.FieldStatisticsParameters = FieldStatisticsParameters; SuperMap.FilterParameter = FilterParameter; SuperMap.FindClosestFacilitiesParameters = FindClosestFacilitiesParameters; SuperMap.FindClosestFacilitiesService = FindClosestFacilitiesService; SuperMap.FindLocationParameters = FindLocationParameters; SuperMap.FindLocationService = FindLocationService; SuperMap.FindMTSPPathsParameters = FindMTSPPathsParameters; SuperMap.FindMTSPPathsService = FindMTSPPathsService; SuperMap.FindPathParameters = FindPathParameters; SuperMap.FindPathService = FindPathService; SuperMap.FindServiceAreasParameters = FindServiceAreasParameters; SuperMap.FindServiceAreasService = FindServiceAreasService; SuperMap.FindTSPPathsParameters = FindTSPPathsParameters; SuperMap.FindTSPPathsService = FindTSPPathsService; SuperMap.GenerateSpatialDataParameters = GenerateSpatialDataParameters; SuperMap.GenerateSpatialDataService = GenerateSpatialDataService; SuperMap.GeoCodingParameter = GeoCodingParameter; SuperMap.GeoDecodingParameter = GeoDecodingParameter; SuperMap.GeoHashGridAggParameter = GeoHashGridAggParameter; SuperMap.GeometryBatchAnalystService = GeometryBatchAnalystService; SuperMap.GeometryBufferAnalystParameters = GeometryBufferAnalystParameters; SuperMap.GeometryOverlayAnalystParameters = GeometryOverlayAnalystParameters; SuperMap.GeometrySurfaceAnalystParameters = GeometrySurfaceAnalystParameters; SuperMap.GeometryThiessenAnalystParameters = GeometryThiessenAnalystParameters; SuperMap.GeoprocessingService = GeoprocessingService_GeoprocessingService; SuperMap.GeoRelationAnalystParameters = GeoRelationAnalystParameters; SuperMap.GeoRelationAnalystService = GeoRelationAnalystService; SuperMap.GetFeaturesByBoundsParameters = GetFeaturesByBoundsParameters; SuperMap.GetFeaturesByBoundsService = GetFeaturesByBoundsService; SuperMap.GetFeaturesByBufferParameters = GetFeaturesByBufferParameters; SuperMap.GetFeaturesByBufferService = GetFeaturesByBufferService; SuperMap.GetFeaturesByGeometryParameters = GetFeaturesByGeometryParameters; SuperMap.GetFeaturesByGeometryService = GetFeaturesByGeometryService; SuperMap.GetFeaturesByIDsParameters = GetFeaturesByIDsParameters; SuperMap.GetFeaturesByIDsService = GetFeaturesByIDsService; SuperMap.GetFeaturesBySQLParameters = GetFeaturesBySQLParameters; SuperMap.GetFeaturesBySQLService = GetFeaturesBySQLService; SuperMap.GetFeaturesParametersBase = GetFeaturesParametersBase; SuperMap.GetFeaturesServiceBase = GetFeaturesServiceBase; SuperMap.GetFieldsService = GetFieldsService; SuperMap.GetGridCellInfosParameters = GetGridCellInfosParameters; SuperMap.GetGridCellInfosService = GetGridCellInfosService; SuperMap.GetLayersInfoService = GetLayersInfoService; SuperMap.Grid = Grid; SuperMap.HillshadeParameter = HillshadeParameter; SuperMap.Image = UGCImage; SuperMap.ImageCollectionService = ImageCollectionService_ImageCollectionService; SuperMap.ImageGFAspect = ImageGFAspect; SuperMap.ImageGFHillShade = ImageGFHillShade; SuperMap.ImageGFOrtho = ImageGFOrtho; SuperMap.ImageGFSlope = ImageGFSlope; SuperMap.ImageRenderingRule = ImageRenderingRule; SuperMap.ImageSearchParameter = ImageSearchParameter; SuperMap.ImageService = ImageService_ImageService; SuperMap.ImageStretchOption = ImageStretchOption; SuperMap.InterpolationAnalystParameters = InterpolationAnalystParameters; SuperMap.InterpolationAnalystService = InterpolationAnalystService; SuperMap.InterpolationDensityAnalystParameters = InterpolationDensityAnalystParameters; SuperMap.InterpolationIDWAnalystParameters = InterpolationIDWAnalystParameters; SuperMap.InterpolationKrigingAnalystParameters = InterpolationKrigingAnalystParameters; SuperMap.InterpolationRBFAnalystParameters = InterpolationRBFAnalystParameters; SuperMap.JoinItem = JoinItem; SuperMap.KernelDensityJobParameter = KernelDensityJobParameter; SuperMap.KernelDensityJobsService = KernelDensityJobsService; SuperMap.LabelImageCell = LabelImageCell; SuperMap.LabelMatrixCell = LabelMatrixCell; SuperMap.LabelMixedTextStyle = LabelMixedTextStyle; SuperMap.LabelSymbolCell = LabelSymbolCell; SuperMap.LabelThemeCell = LabelThemeCell; SuperMap.LayerStatus = LayerStatus; SuperMap.LinkItem = LinkItem; SuperMap.MappingParameters = MappingParameters; SuperMap.MapService = MapService_MapService; SuperMap.MathExpressionAnalysisParameters = MathExpressionAnalysisParameters; SuperMap.MathExpressionAnalysisService = MathExpressionAnalysisService; SuperMap.MeasureParameters = MeasureParameters; SuperMap.MeasureService = MeasureService_MeasureService; SuperMap.MetricsAggParameter = MetricsAggParameter; SuperMap.NDVIParameter = NDVIParameter; SuperMap.NetworkAnalystServiceBase = NetworkAnalystServiceBase; SuperMap.OutputSetting = OutputSetting; SuperMap.OverlapDisplayedOptions = OverlapDisplayedOptions; SuperMap.OverlayAnalystParameters = OverlayAnalystParameters; SuperMap.OverlayAnalystService = OverlayAnalystService; SuperMap.OverlayGeoJobParameter = OverlayGeoJobParameter; SuperMap.OverlayGeoJobsService = OverlayGeoJobsService; SuperMap.PointWithMeasure = PointWithMeasure; SuperMap.ProcessingServiceBase = ProcessingServiceBase; SuperMap.QueryByBoundsParameters = QueryByBoundsParameters; SuperMap.QueryByBoundsService = QueryByBoundsService; SuperMap.QueryByDistanceParameters = QueryByDistanceParameters; SuperMap.QueryByDistanceService = QueryByDistanceService; SuperMap.QueryByGeometryParameters = QueryByGeometryParameters; SuperMap.QueryByGeometryService = QueryByGeometryService; SuperMap.QueryBySQLParameters = QueryBySQLParameters; SuperMap.QueryBySQLService = QueryBySQLService; SuperMap.QueryParameters = QueryParameters; SuperMap.QueryService = QueryService; SuperMap.RasterFunctionParameter = RasterFunctionParameter; SuperMap.Route = Route; SuperMap.RouteCalculateMeasureParameters = RouteCalculateMeasureParameters; SuperMap.RouteCalculateMeasureService = RouteCalculateMeasureService; SuperMap.RouteLocatorParameters = RouteLocatorParameters; SuperMap.RouteLocatorService = RouteLocatorService; SuperMap.ServerColor = ServerColor; SuperMap.ServerFeature = ServerFeature; SuperMap.ServerGeometry = ServerGeometry; SuperMap.ServerStyle = ServerStyle; SuperMap.ServerTextStyle = ServerTextStyle; SuperMap.ServerTheme = ServerTheme; SuperMap.SetDatasourceParameters = SetDatasourceParameters; SuperMap.SetLayerInfoParameters = SetLayerInfoParameters; SuperMap.SetLayerInfoService = SetLayerInfoService; SuperMap.SetLayersInfoParameters = SetLayersInfoParameters; SuperMap.SetLayersInfoService = SetLayersInfoService; SuperMap.SetLayerStatusParameters = SetLayerStatusParameters; SuperMap.SetLayerStatusService = SetLayerStatusService; SuperMap.SingleObjectQueryJobsParameter = SingleObjectQueryJobsParameter; SuperMap.SingleObjectQueryJobsService = SingleObjectQueryJobsService; SuperMap.Sortby = Sortby; SuperMap.SpatialAnalystBase = SpatialAnalystBase; SuperMap.StopQueryParameters = StopQueryParameters; SuperMap.StopQueryService = StopQueryService; SuperMap.SummaryAttributesJobsParameter = SummaryAttributesJobsParameter; SuperMap.SummaryAttributesJobsService = SummaryAttributesJobsService; SuperMap.SummaryMeshJobParameter = SummaryMeshJobParameter; SuperMap.SummaryMeshJobsService = SummaryMeshJobsService; SuperMap.SummaryRegionJobParameter = SummaryRegionJobParameter; SuperMap.SummaryRegionJobsService = SummaryRegionJobsService; SuperMap.SupplyCenter = SupplyCenter; SuperMap.SurfaceAnalystParameters = SurfaceAnalystParameters; SuperMap.SurfaceAnalystParametersSetting = SurfaceAnalystParametersSetting; SuperMap.SurfaceAnalystService = SurfaceAnalystService; SuperMap.TerrainCurvatureCalculationParameters = TerrainCurvatureCalculationParameters; SuperMap.TerrainCurvatureCalculationService = TerrainCurvatureCalculationService; SuperMap.Theme = Theme; SuperMap.ThemeDotDensity = ThemeDotDensity; SuperMap.ThemeFlow = ThemeFlow; SuperMap.ThemeGraduatedSymbol = ThemeGraduatedSymbol; SuperMap.ThemeGraduatedSymbolStyle = ThemeGraduatedSymbolStyle; SuperMap.ThemeGraph = ThemeGraph; SuperMap.ThemeGraphAxes = ThemeGraphAxes; SuperMap.ThemeGraphItem = ThemeGraphItem; SuperMap.ThemeGraphSize = ThemeGraphSize; SuperMap.ThemeGraphText = ThemeGraphText; SuperMap.ThemeGridRange = ThemeGridRange; SuperMap.ThemeGridRangeItem = ThemeGridRangeItem; SuperMap.ThemeGridUnique = ThemeGridUnique; SuperMap.ThemeGridUniqueItem = ThemeGridUniqueItem; SuperMap.ThemeLabel = ThemeLabel; SuperMap.ThemeLabelAlongLine = ThemeLabelAlongLine; SuperMap.ThemeLabelBackground = ThemeLabelBackground; SuperMap.ThemeLabelItem = ThemeLabelItem; SuperMap.ThemeLabelText = ThemeLabelText; SuperMap.ThemeLabelUniqueItem = ThemeLabelUniqueItem; SuperMap.ThemeMemoryData = ThemeMemoryData; SuperMap.ThemeOffset = ThemeOffset; SuperMap.ThemeParameters = ThemeParameters; SuperMap.ThemeRange = ThemeRange; SuperMap.ThemeRangeItem = ThemeRangeItem; SuperMap.ThemeService = ThemeService_ThemeService; SuperMap.ThemeUnique = ThemeUnique; SuperMap.ThemeUniqueItem = ThemeUniqueItem; SuperMap.ThiessenAnalystParameters = ThiessenAnalystParameters; SuperMap.ThiessenAnalystService = ThiessenAnalystService; SuperMap.TilesetsService = TilesetsService; SuperMap.TopologyValidatorJobsParameter = TopologyValidatorJobsParameter; SuperMap.TopologyValidatorJobsService = TopologyValidatorJobsService; SuperMap.TransferLine = TransferLine; SuperMap.TransferPathParameters = TransferPathParameters; SuperMap.TransferPathService = TransferPathService; SuperMap.TransferSolutionParameters = TransferSolutionParameters; SuperMap.TransferSolutionService = TransferSolutionService; SuperMap.TransportationAnalystParameter = TransportationAnalystParameter; SuperMap.TransportationAnalystResultSetting = TransportationAnalystResultSetting; SuperMap.UGCLayer = UGCLayer; SuperMap.UGCMapLayer = UGCMapLayer; SuperMap.UGCSubLayer = UGCSubLayer; SuperMap.UpdateDatasetParameters = UpdateDatasetParameters; SuperMap.UpdateEdgeWeightParameters = UpdateEdgeWeightParameters; SuperMap.UpdateEdgeWeightService = UpdateEdgeWeightService; SuperMap.UpdateTurnNodeWeightParameters = UpdateTurnNodeWeightParameters; SuperMap.UpdateTurnNodeWeightService = UpdateTurnNodeWeightService; SuperMap.Vector = Vector_Vector; SuperMap.VectorClipJobsParameter = VectorClipJobsParameter; SuperMap.VectorClipJobsService = VectorClipJobsService; SuperMap.WebPrintingJobContent = WebPrintingJobContent; SuperMap.WebPrintingJobCustomItems = WebPrintingJobCustomItems; SuperMap.WebPrintingJobExportOptions = WebPrintingJobExportOptions; SuperMap.WebPrintingJobImage = WebPrintingJobImage; SuperMap.WebPrintingJobLayers = WebPrintingJobLayers; SuperMap.WebPrintingJobLayoutOptions = WebPrintingJobLayoutOptions; SuperMap.WebPrintingJobLegendOptions = WebPrintingJobLegendOptions; SuperMap.WebPrintingJobLittleMapOptions = WebPrintingJobLittleMapOptions; SuperMap.WebPrintingJobNorthArrowOptions = WebPrintingJobNorthArrowOptions; SuperMap.WebPrintingJobParameters = WebPrintingJobParameters; SuperMap.WebPrintingJobScaleBarOptions = WebPrintingJobScaleBarOptions; SuperMap.WebPrintingService = WebPrintingService; //Online SuperMap.Online = Online; SuperMap.OnlineData = OnlineData; SuperMap.OnlineQueryDatasParameter = OnlineQueryDatasParameter; SuperMap.ServiceStatus = ServiceStatus; // 包含online中的DataItemType数据类型 SuperMap.DataItemType = DataItemType; SuperMap.DataItemOrderBy = DataItemOrderBy; SuperMap.FilterField = FilterField; SuperMap.OnlineServiceBase = OnlineServiceBase; // overlay SuperMap.Feature = SuperMap.Feature || {}; SuperMap.Feature.Theme = Theme_Theme; SuperMap.Feature.Theme.Bar = Bar; SuperMap.Feature.Theme.Bar3D = Bar3D; SuperMap.Feature.Theme.Circle = Circle; SuperMap.Feature.Theme.Graph = Graph; SuperMap.Feature.Theme.Line = Line; SuperMap.Feature.Theme.Pie = Pie; SuperMap.Feature.Theme.Point = overlay_Point_Point; SuperMap.Feature.Theme.RankSymbol = RankSymbol; SuperMap.Feature.Theme.Ring = Ring; SuperMap.Feature.Theme.ThemeVector = ThemeVector; SuperMap.Feature.ShapeParameters = ShapeParameters; SuperMap.Feature.ShapeParameters.Circle = Circle_Circle; SuperMap.Feature.ShapeParameters.Image = Image_Image; SuperMap.Feature.ShapeParameters.Label = Label; SuperMap.Feature.ShapeParameters.Line = Line_Line; SuperMap.Feature.ShapeParameters.Point = Point_Point; SuperMap.Feature.ShapeParameters.Polygon = Polygon_Polygon; SuperMap.Feature.ShapeParameters.Rectangle = Rectangle_Rectangle; SuperMap.Feature.ShapeParameters.Sector = Sector; SuperMap.Feature.ShapeFactory = ShapeFactory; // LevelRenderer SuperMap.LevelRenderer = LevelRenderer; // security SuperMap.KeyServiceParameter = KeyServiceParameter; SuperMap.SecurityManager = SecurityManager; SuperMap.ServerInfo = ServerInfo; SuperMap.TokenServiceParameter = TokenServiceParameter; // style SuperMap.ThemeStyle = ThemeStyle; SuperMap.CartoCSS = CartoCSS; // thirdparty // SuperMap.BinaryClassification = BinaryClassification; // SuperMap.LandcoverClassification = LandcoverClassification; // SuperMap.ObjectDetection = ObjectDetection; // SuperMap.WebMachineLearning = WebMachineLearning; SuperMap.ElasticSearch = ElasticSearch; // util SuperMap.ArrayStatistic = ArrayStatistic; SuperMap.ColorsPickerUtil = ColorsPickerUtil; // REST SuperMap.DataFormat = DataFormat; SuperMap.ServerType = ServerType; SuperMap.GeometryType = REST_GeometryType; SuperMap.QueryOption = QueryOption; SuperMap.JoinType = JoinType; SuperMap.SpatialQueryMode = SpatialQueryMode; SuperMap.SpatialRelationType = SpatialRelationType; SuperMap.MeasureMode = MeasureMode; SuperMap.Unit = Unit; SuperMap.BufferRadiusUnit = BufferRadiusUnit; SuperMap.EngineType = EngineType; SuperMap.ThemeGraphTextFormat = ThemeGraphTextFormat; SuperMap.ThemeGraphType = ThemeGraphType; SuperMap.GraphAxesTextDisplayMode = GraphAxesTextDisplayMode; SuperMap.GraduatedMode = GraduatedMode; SuperMap.RangeMode = RangeMode; SuperMap.ThemeType = ThemeType; SuperMap.ColorGradientType = ColorGradientType; SuperMap.TextAlignment = TextAlignment; SuperMap.FillGradientMode = FillGradientMode; SuperMap.AlongLineDirection = AlongLineDirection; SuperMap.LabelBackShape = LabelBackShape; SuperMap.LabelOverLengthMode = LabelOverLengthMode; SuperMap.DirectionType = DirectionType; SuperMap.OverlayOperationType = OverlayOperationType; SuperMap.OutputType = OutputType; SuperMap.SideType = SideType; SuperMap.SupplyCenterType = SupplyCenterType; SuperMap.TurnType = TurnType; SuperMap.BufferEndType = BufferEndType; SuperMap.SmoothMethod = SmoothMethod; SuperMap.SurfaceAnalystMethod = SurfaceAnalystMethod; SuperMap.DataReturnMode = DataReturnMode; SuperMap.EditType = EditType; SuperMap.TransferTactic = TransferTactic; SuperMap.TransferPreference = TransferPreference; SuperMap.GridType = GridType; SuperMap.ColorSpaceType = ColorSpaceType; SuperMap.LayerType = LayerType; SuperMap.UGCLayerType = UGCLayerType; SuperMap.StatisticMode = StatisticMode; SuperMap.PixelFormat = PixelFormat; SuperMap.SearchMode = SearchMode; SuperMap.InterpolationAlgorithmType = InterpolationAlgorithmType; SuperMap.VariogramMode = VariogramMode; SuperMap.Exponent = Exponent; SuperMap.ClientType = ClientType; SuperMap.ChartType = ChartType; SuperMap.ClipAnalystMode = ClipAnalystMode; SuperMap.AnalystAreaUnit = AnalystAreaUnit; SuperMap.AnalystSizeUnit = AnalystSizeUnit; SuperMap.StatisticAnalystMode = StatisticAnalystMode; SuperMap.SummaryType = SummaryType; SuperMap.TopologyValidatorRule = TopologyValidatorRule; SuperMap.BucketAggType = BucketAggType; SuperMap.MetricsAggType = MetricsAggType; SuperMap.GetFeatureMode = GetFeatureMode; SuperMap.RasterFunctionType = RasterFunctionType; SuperMap.ResourceType = ResourceType; SuperMap.OrderBy = OrderBy; SuperMap.OrderType = OrderType; SuperMap.SearchType = SearchType; SuperMap.AggregationTypes = AggregationTypes; SuperMap.PermissionType = PermissionType; SuperMap.EntityType = EntityType; SuperMap.WebExportFormatType = WebExportFormatType; SuperMap.WebScaleOrientationType = WebScaleOrientationType; SuperMap.WebScaleType = WebScaleType; SuperMap.WebScaleUnit = WebScaleUnit; ;// CONCATENATED MODULE: external "ol.Observable" const external_ol_Observable_namespaceObject = ol.Observable; var external_ol_Observable_default = /*#__PURE__*/__webpack_require__.n(external_ol_Observable_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/services/ServiceBase.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ServiceBase * @category iServer Core * @classdesc ol.supermap 的服务基类。 * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {ol.Observable} * @usage */ class ServiceBase extends (external_ol_Observable_default()) { constructor(url, options) { super(url, options); this.options = options || {}; this.url = url; this.dispatchEvent({type: 'initialized', value: this}); } } ;// CONCATENATED MODULE: ./src/openlayers/services/MapService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MapService * @category iServer Map * @classdesc 地图信息服务类。 * @extends {ServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * new MapService(url).getMapInfo(function(result){ * //doSomething * }) * @usage */ class MapService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function MapService.prototype.getMapInfo * @description 地图信息查询服务。 * @param {RequestCallback} callback - 回调函数。 * @returns {MapService} 获取服务信息。 */ getMapInfo(callback) { var me = this; var getMapStatusService = new MapService_MapService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, projection: me.options.projection }); getMapStatusService.processAsync(); } /** * @function MapService.prototype.getWkt * @description 获取WKT。 * @param {RequestCallback} callback - 回调函数。 */ getWkt(callback) { var me = this; var getMapStatusService = new MapService_MapService(`${me.url}/prjCoordSys.wkt`, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, withoutFormatSuffix: true, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, projection: me.options.projection }); getMapStatusService.processAsync(); } /** * @function MapService.prototype.getTilesets * @description 切片列表信息查询服务。 * @param {RequestCallback} callback - 回调函数。 * @returns {MapService} 获取服务信息。 */ getTilesets(callback) { var me = this; var tilesetsService = new TilesetsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); tilesetsService.processAsync(); } } ;// CONCATENATED MODULE: external "ol.control.Control" const external_ol_control_Control_namespaceObject = ol.control.Control; var external_ol_control_Control_default = /*#__PURE__*/__webpack_require__.n(external_ol_control_Control_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/control/ChangeTileVersion.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChangeTileVersion * @aliasclass control.ChangeTileVersion * @category Control * @classdesc 版本切换控件(目前仅支持 IE10 及以上)暂时不支持自定义位置。 * @extends {ol.control.Control} * @param {Object} options -参数。 * @param {string} [options.title='switch tile version'] - 提示信息。 * @param {string} [options.tooltip='top'] - 提示显示位置 top | right | bottom | left。 * @param {boolean} [options.collapsed=true] - 是否折叠。 * @param {string} [options.lastText='-'] - 上一个版本的按钮布局。 * @param {string} [options.nextText='+'] - 下一个版本的按钮布局。 * @param {string} [options.ico='V'] - 控件显示的logo。 * @param {string} [options.orientation='horizontal'] - 方向 horizontal|vertical。 * @param {boolean} [options.switch=true] - 是否显示上/下一个版本切换控件。 * @example * var control = new ChangeTileVersion({ * layer: baseLayer, * orientation: "horizontal" * }); * map.addControl(control) * @usage */ class ChangeTileVersion extends (external_ol_control_Control_default()) { constructor(options) { options = options || {}; //鼠标滑过时提示 if (!options.title) { options.title = 'switch tile version'; } //tooltip提示显示位置 top | right | bottom | left if (!options.tooltip) { options.tooltip = 'top'; } //是否折叠 if (!options.collapsed) { options.collapsed = true; } //上一个版本的按钮布局 if (!options.lastText) { options.lastText = '-'; } //下一个版本的按钮布局 if (!options.nextText) { options.nextText = '+'; } //控件显示的logo if (!options.ico) { options.ico = 'V'; } //方向horizontal|vertical if (options.orientation !== 'vertical') { options.orientation = 'horizontal'; } //是否显示上/下一个版本切换控件 if (!options.switch) { options.switch = true; } super(options); this.options = options; this.element = options.element = initLayout.call(this); if (options.layer) { this.setLayer(options.layer); } /** * @function ChangeTileVersion.prototype.initLayout * @description 初始化。 */ function initLayout() { var className = 'ol-control-ctv'; this._container = createElement( 'div', className + ' ' + className + '-' + options.orientation + ' ol-unselectable ol-control' ); //正常情况下显示btn this._sliderBtn = createElement('button', className + '-toggle', this._container); this._sliderBtn.setAttribute('title', options.title); this._sliderBtn.innerHTML = options.ico; //滑块拖动时值显示区域 this._sliderValue = createElement('p', className + '-value', this._container); this._sliderValue.innerHTML = options.ico; this._sliderValue.setAttribute('title', options.title); var sliderClassName = 'ol-ctv-slider'; this._sliderContent = createElement('div', sliderClassName + '-main' + ' tooltip', this._container); //tooltip提示框 if (options.orientation === 'vertical' && options.tooltip === 'top') { options.tooltip = 'right'; } this.tooltip = createElement( 'span', 'tooltip-text' + ' ' + 'tooltip-' + options.tooltip, this._sliderContent ); this.tooltip.innerHTML = options.ico; //加控件 if (options.switch) { this._next = createElement( 'a', sliderClassName + '-incdec' + ' ' + sliderClassName + '-next', this._sliderContent ); this._next.innerHTML = options.nextText; addDomEvent(this._next, 'click', this.nextTilesVersion, this); this._container.classList.add(className + '-incdec'); } //滑块 this._sliderContainer = createElement('div', sliderClassName + '-container', this._sliderContent); this.slider = createElement('input', sliderClassName, this._sliderContainer); this.min = this.min == null || isNaN(this.min) ? 0 : parseInt(this.min); this.slider.setAttribute('title', options.title); this.slider.setAttribute('id', 'slider'); this.slider.setAttribute('type', 'range'); this.slider.setAttribute('min', this.min); this.slider.setAttribute('max', 0); this.slider.setAttribute('step', 1); this.slider.setAttribute('value', 0); // //判断浏览器是否支持Range滑动条 // if (this.slider.type == "text") { // console.error("抱歉,您的浏览器不支持HTML5 range滑动条,请使用高版本浏览器"); // } this.firstLoad = true; if ('oninput' in this.slider || 'onchange' in this.slider) { addDomEvent(this.slider, 'change', tilesVersion, this); } else { this.slider.onpropertychange = tilesVersion; } //减控件 if (options.switch) { this._last = createElement( 'a', sliderClassName + '-incdec' + ' ' + sliderClassName + '-last', this._sliderContent ); this._last.innerHTML = options.lastText; addDomEvent(this._last, 'click', this.lastTilesVersion, this); } // if (window.matchMedia("screen and (-webkit-min-device-pixel-ratio:0)").matches && options.orientation == 'vertical') { if (options.orientation == 'vertical') { this.slider.style.width = 170 + 'px'; this._sliderContainer.style.height = 170 + 'px'; } else { this._sliderContainer.style.width = 150 + 'px'; } addDomEvent( this._container, 'click', function(e) { e.preventDefault(); e.stopPropagation(); }, this ); if (options.collapsed) { addDomEvent(this._container, 'mouseenter', expand, this); addDomEvent(this._container, 'mouseleave', collapse, this); addDomEvent(this._sliderBtn, 'click', function(e) { e.preventDefault(); e.stopPropagation(); }); addDomEvent(this._sliderBtn, 'click', expand, this); addDomEvent(this._sliderBtn, 'focus', expand, this); } else { expand(); } return this._container; } /** * @function ChangeTileVersion.prototype.createElement * @description 新建元素。 * @param {string} tagName - 标签名。 * @param {string} className - 类名。 * @param {Object} container - 容器。 * @returns {object|HTMLElement} 元素。 */ function createElement(tagName, className, container) { var el = document.createElement(tagName); el.className = className || ''; if (container) { container.appendChild(el); } return el; } /** * @function ChangeTileVersion.prototype.addDomEvent * @description 为元素添加事件。 * @param {Object} obj - 事件对象集。 * @param {string} type - 事件类型。 * @param {Object} fn -容器。 * @param {Object} context -当前环境。 * @returns {function} 添加的事件。 */ function addDomEvent(obj, type, fn, context) { var handler = function(e) { if (fn) { return fn.call(context || obj, e || window.event); } }; var originalHandler = handler; if ('addEventListener' in obj) { if (type === 'mousewheel') { obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false); } else if (type === 'mouseenter' || type === 'mouseleave') { handler = function(e) { e = e || window.event; if (isExternalTarget(obj, e)) { originalHandler(e); } }; obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false); } else { obj.addEventListener(type, handler, false); } } else if ('attachEvent' in obj) { obj.attachEvent('on' + type, handler); } return this; } function isExternalTarget(el, e) { var related = e.relatedTarget; if (!related) { return true; } try { while (related && related !== el) { related = related.parentNode; } } catch (err) { return false; } return related !== el; } function expand() { this._container.classList.add('ol-control-ctv-expanded'); } function collapse() { this._container.classList.remove('ol-control-ctv-expanded'); } function tilesVersion() { var version = this.getVersion(); this.tilesVersion(version); } } /** * @function ChangeTileVersion.prototype.setContent * @description 设置版本相关信息。 * @param {Object} version - 版本信息。 */ setContent(version) { var content = version || {}; this.setVersionName(content.desc).setToolTip(content.desc); } /** * @function ChangeTileVersion.prototype.setVersionName * @description 设置版本号 * @param {string} content -版本内容。 */ setVersionName(content) { var value = content; if (!content) { value = this.getValue(); } this._sliderValue.innerHTML = value; return this; } /** * @function ChangeTileVersion.prototype.setToolTip * @description 设置提示信息。 * @param {string} tooltip - 提示信息。 * @returns {ChangeTileVersion} ChangeTileVersion的实例对象。 */ setToolTip(tooltip) { this.tooltip.innerHTML = tooltip; return this; } /** * @function ChangeTileVersion.prototype.updateLength * @description 更新进度条长度。 * @param {number} length - 进度条长度。 */ updateLength(length) { if (length > 0) { this.length = length; this.max = this.length - 1; this.slider.setAttribute('max', this.max); } } /** * @function ChangeTileVersion.prototype.setLayer * @description 绑定图层。 * @param {Object} layer - 图层。 */ setLayer(layer) { if (layer) { this.options.layer = layer; } var me = this; var tileLayer = me.options.layer; tileLayer.on('tilesetsinfoloaded', function(evt) { var tileVersions = evt.value && evt.value.tileVersions; me.update(tileVersions); }); tileLayer.on('tileversionschanged', function(evt) { var tileVersions = evt.value && evt.value.tileVersion; me.setContent(tileVersions); }); me.getTileSetsInfo(); } /** * @function ChangeTileVersion.prototype.update * @description 更新缓存切片集及进度条长度。 * @param {Object} tileVersions - 待更新的切片版本。 */ update(tileVersions) { this.tileVersions = tileVersions ||[]; this.updateLength(this.tileVersions.length); } /** * @function ChangeTileVersion.prototype.getTileSetsInfo * @description 请求获取切片集信息。 */ getTileSetsInfo() { var me = this; if (me.options.layer) { new MapService(me.options.layer._url).getTilesets(function getTilesInfoSucceed(info) { me.options.layer.setTileSetsInfo(info.result); }); } } /** * @function ChangeTileVersion.prototype.removeLayer * @description 移除绑定的地图图层。 */ removeLayer() { this.options.layer = null; } /** * @function ChangeTileVersion.prototype.nextTilesVersion * @description 下一个版本,第一次不进行加减,是无版本的状态。 * @returns {ChangeTileVersion} ChangeTileVersion的实例对象。 */ nextTilesVersion() { if (this.firstLoad) { this.options.layer.nextTilesVersion(); this.firstLoad = !!0; return this; } if (parseInt(this.slider.value) > this.max - 1) { return this; } this.slider.value = parseInt(this.slider.value) + 1; this.options.layer.nextTilesVersion(); return this; } /** * @function ChangeTileVersion.prototype.lastTilesVersion * @description 获取上一个版本信息。 * @returns {ChangeTileVersion} ChangeTileVersion的实例对象。 */ lastTilesVersion() { if (parseInt(this.slider.value) < this.min + 1) { return this; } this.slider.value = parseInt(this.slider.value) - 1; this.options.layer.lastTilesVersion(); return this; } /** * @function ChangeTileVersion.prototype.tilesVersion * @description 根据指定版本号请求版本。 * @param {Object} version - 版本信息。 */ tilesVersion(version) { var layer = this.options.layer, tileVersions = this.tileVersions; var len = tileVersions.length; for (var i = 0; i < len; i++) { if (tileVersions[i].name == version) { layer.updateCurrentTileSetsIndex(i); layer.changeTilesVersion(); break; } } } /** * @function ChangeTileVersion.prototype.getValue * @description 获取进度条的值。注:(进度条的值并不是版本号)。 */ getValue() { return this.slider.value; } /** * @function ChangeTileVersion.prototype.getVersion * @description 获取当前进度条值对应的版本号。 */ getVersion() { var version = this.tileVersions[this.getValue()]; return version && version.name; } } ;// CONCATENATED MODULE: external "ol.control.ScaleLine" const external_ol_control_ScaleLine_namespaceObject = ol.control.ScaleLine; var external_ol_control_ScaleLine_default = /*#__PURE__*/__webpack_require__.n(external_ol_control_ScaleLine_namespaceObject); ;// CONCATENATED MODULE: external "ol.proj" const external_ol_proj_namespaceObject = ol.proj; ;// CONCATENATED MODULE: external "ol.AssertionError" const external_ol_AssertionError_namespaceObject = ol.AssertionError; var external_ol_AssertionError_default = /*#__PURE__*/__webpack_require__.n(external_ol_AssertionError_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/control/ScaleLine.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ScaleLine * @aliasclass control.ScaleLine * @category Control * @version 9.1.2 * @classdesc 比例尺控件。 *
*

Notice

*

该功能继承 {@link ol.control.ScaleLine },与 {@link ol.control.ScaleLine } 功能完全相同。仅为修复 `openlayers` v4.6.5 版本中 WGS84 等地理坐标系比例尺数值错误的问题。 *

* @extends {ol.control.ScaleLine} * @param {Object} options -参数。 * @param {string} [options.className='ol-scale-line'] - CSS Class name.。 * @param {number} [options.minWidth=64] - 最小像素宽度。 * @param {(HTMLElement|string) } [options.target] - 指定比例尺控件目标容器。 * @param {(ol.control.ScaleLine.Units|string)} [options.units='metric'] - 上一个版本的按钮布局。 * @example * var control = new ScaleLine(); * map.addControl(control) * @usage */ class ScaleLine extends (external_ol_control_ScaleLine_default()) { constructor(options) { options = options || {}; //需在super之前定义render,真正的调用是在初始化完成后 options.render = function (mapEvent) { var frameState = mapEvent.frameState; if (!frameState) { this.viewState_ = null; //NOSONAR } else { this.viewState_ = frameState.viewState; //NOSONAR } this.updateElementRepair(); //NOSONAR }; super(options); //NOSONAR } updateElementRepair() { const viewState = this.viewState_ || this.o || this.Om; if (!viewState) { this.renderedVisible_ = this.renderedVisible_ || this.j || this.yn; if (this.renderedVisible_) { this.element_ = this.element_ || this.c; this.element.style.display = 'none'; this.renderedVisible_ = false; } return; } const center = viewState.center; const projection = viewState.projection; const units = this.getUnits(); const pointResolutionUnits = units == "degrees" ? "degrees" : "m"; let pointResolution = external_ol_proj_namespaceObject.getPointResolution(projection, viewState.resolution, center, pointResolutionUnits); this.minWidth_ = this.minWidth_ || this.v || this.Em; let nominalCount = this.minWidth_ * pointResolution; let suffix = ''; if (units == "degrees") { const metersPerDegree = external_ol_proj_namespaceObject.METERS_PER_UNIT.degrees; nominalCount *= metersPerDegree; if (nominalCount < metersPerDegree / 60) { suffix = '\u2033'; // seconds pointResolution *= 3600; } else if (nominalCount < metersPerDegree) { suffix = '\u2032'; // minutes pointResolution *= 60; } else { suffix = '\u00b0'; // degrees } } else if (units == "imperial") { if (nominalCount < 0.9144) { suffix = 'in'; pointResolution /= 0.0254; } else if (nominalCount < 1609.344) { suffix = 'ft'; pointResolution /= 0.3048; } else { suffix = 'mi'; pointResolution /= 1609.344; } } else if (units == "nautical") { pointResolution /= 1852; suffix = 'nm'; } else if (units == "metric") { if (nominalCount < 0.001) { suffix = 'μm'; pointResolution *= 1000000; } else if (nominalCount < 1) { suffix = 'mm'; pointResolution *= 1000; } else if (nominalCount < 1000) { suffix = 'm'; } else { suffix = 'km'; pointResolution /= 1000; } } else if (units == "us") { if (nominalCount < 0.9144) { suffix = 'in'; pointResolution *= 39.37; } else if (nominalCount < 1609.344) { suffix = 'ft'; pointResolution /= 0.30480061; } else { suffix = 'mi'; pointResolution /= 1609.3472; } } else { throw new (external_ol_AssertionError_default())(33); // Invalid units } var DIGITS = [1, 2, 5]; let i = 3 * Math.floor( Math.log(this.minWidth_ * pointResolution) / Math.log(10)); let count, width, decimalCount; while (true) { //eslint-disable-line no-constant-condition decimalCount = Math.floor(i / 3); const decimal = Math.pow(10, decimalCount); count = DIGITS[((i % 3) + 3) % 3] * decimal; width = Math.round(count / pointResolution); if (isNaN(width)) { this.element.style.display = 'none'; this.renderedVisible_ = false; return; } else if (width >= this.minWidth_) { break; } ++i; } this.renderedHTML_ = this.renderedHTML_ || this.D || this.am; this.innerElement_ = this.innerElement_ || this.l || this.Tm; this.renderedWidth_ = this.renderedWidth_ || this.B || this.Am; this.renderedVisible_ = this.renderedVisible_ || this.j || this.yn; this.element_ = this.element_ || this.c; let html= count.toFixed(decimalCount < 0 ? -decimalCount : 0) + ' ' + suffix; if (this.renderedHTML_ != html) { this.innerElement_.innerHTML = html; this.renderedHTML_ = html; } if (this.renderedWidth_ != width) { this.innerElement_.style.width = width + 'px'; this.renderedWidth_ = width; } if (!this.renderedVisible_) { this.element.style.display = ''; this.renderedVisible_ = true; } } } ;// CONCATENATED MODULE: ./src/common/control/img/Logo.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ var LogoBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF4AAAAdCAYAAAAjHtusAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA4ZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDozYWZlOGIwMi01MWE3LTRiZjYtYWVkYS05MGQ2ZTQ4YjZiMmUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6ODg0NkFBQUE3RjEzMTFFNzhFRjJFQkY4RjcxQjc1NjIiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6ODg0NkFBQTk3RjEzMTFFNzhFRjJFQkY4RjcxQjc1NjIiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTUgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo4MWI3NzdhNC1lZmEyLTQ1MzUtOGQzNi03MmRjNDkyODMzN2UiIHN0UmVmOmRvY3VtZW50SUQ9ImFkb2JlOmRvY2lkOnBob3Rvc2hvcDpjYTYzODVjMi1jNDQ1LTExN2EtYTc0ZC1lM2I5MzJlMGE4Y2QiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5q1HM0AAAF/ElEQVR42tSabYhUVRjHZ7W01C1uaCRW4F3oi9SXCUnwQ9gsGUFvOEtQH1bLu5VS9sbYh5KicjYt29qiGQwVg2xWWKgocob91AvC+CWsoJqB3qHMSdTMpZyeU/+Df07n3pk7997Z6cBv99z7nHvOvf/z/pxJNZvNVI/jCKXmv6EquAmVkxPSlvtp2GItr0/96fFQForChJAWDiVYTkMYMu4XBFcYjLOwWS3sNwmn8NGzZ0h4Flv/zwIdchAnh/slCGmmKUNIBzYPaXOUr0vPuEjD71JAPh7l61embzinhV3V8nnCGmGT8LwlzSL8/yUh4Tfjo9T/CgnCIYNKycA2Qq21AcHU/VHE80Idoo3Qs0W6p0UtUnkZvEMDeVcCyqxEafF7hL8Qf0oYsIj+lfC9cH1CwhchWAGCtZO+AooQOkdC1Km1VtCb63StW73uFSzgKFUkNwBbmZGGmqowhvg8ZNpH9oXChcIcYRdeNomgxLkaH+S1SGubAxyIpFv+Zp+0DYjrAS00j/dem2VGEl6FJ4Qa4quEu8j2hTCJ+GJhe4JjfQMf6JCYPPbysMPxBlp0BUKOogEF9Rg9/heNvNKYfM0KsZUZaYxX4STGrzJa+zbhPeFH2DcK10KItcI+pI0rVElwXl1ULaKnIJhDw0oRQpTQc1zcbwRU8ATy4DR6yMlTzwkqMziEWHvubJ4Nk4ZtHdnqwvwY17xq3Z4FjrG+z2Kdrdf2ZSGD+xlLPh6t1R0jP9fI22ZzKI92yvQl7EbmBxI4S7Y+vIAOL87QZqsc5uNnssxZIcfYjXT9snCR7jjobidp+FkxA2v+Cq1QervMDmp4P7Xs3YZtE9kOC3P/By6JGaETl8ElwueYTNTDq4UDsKnd7YfCNbT239LF1udS72xYJt1UWxNfN4IIP4bWuTpEja01JtMFZFsm/AHbtHBlDE6yasA4moYTrUbvdBTXHqUrAH4uSadbyzF+vbBM2IsNkS3MNa5305JxqfA02T4TnkX8XOH1mPw8ruVejpxbI9hZD2Cz1U7LdrrUvjP/WfZinNZhr6V27hP+FPZh9aLvLxVO4DllX0G2OcKnlO/DCblxaz6uXBtmi+8mBaP3/SP8IuEIiTRoPPQm2TaEmEyXo0JU+F0YiPFD0hhOsiE/vqeEVwyTgF8L51OilcIZ2I4Ll5NttvAJPfukUeB2sk0ZPSbKIUUJpCII7+DasWy08uhNNazT0wGHI7mAtB7KqMKm38HhDdAUibTVKGicbB8YAqrJ9DRsp43JdB4qUof1HQrPE6XTQWu3Ce/inVzjXhXpMiTwUYugNVQ+p80jrUsV5EH0POKeuXO9QjhFq5GryNYvfEMCDhsftYVsB9ETtG0V9ZjfhCURhbcJFpfwVZ9jvhxsLHwTYtp2svlWQw3vXL8UnqHVSIG8l8ex+tHhBXgjddgqHEZ8ufAA2aaEnYgrF/KrPXrEmMUqZ9THLW06xhoBaVueQpkug+ewOUphE3Qv2Q5gGamXYa+QbVq4O+DQ5FHyZqrjxNt7UHh9uuRa0F7HjCF8o9PCTOGnscM7g2u1Hl9C9oeEnxC/1ajZg8JLiM9Hj9GHJseMShwL2DO0G5yEWn3Zh1QUods5CPkIoqlwAZxhXMsb6HrcEPBxchhdJ6wj29vCW4hfLOzo8J3rltYX50nXQAATSf/K4DEaGlTLvplsk/QCpoD60EQ7gLYZc8H9wq+I3yncEOEcNhuz6HWf3XEiwU/4Y8YEqVp2P10rt+8REvBGw026i4aDcbL9jF8r8Blmf4fCOzhViiscskygXRdehf3CO4hfigmTBXyQrl8TFtD1IzQX3CbcQrY3hPcRv4z8OmHPXwchVNln2MmE7BX6VwIFi/he6uxvb6JM3m0fdqvx/ATidxg2JeC7VDErAw5NzGfvwRJVheEIQ8Mg/pdwIM+UOmi9Q8ivCsrIy0tF+wVbEcLrd3Pb2XisEb4Tdlhsi4WP4RBbaLGrHfC3PrvMIezy9rTpGm5lz9LOMG15xvFxD/j5gjzjjDbMOzk+9zzt3v5bgAEAibzFeFHVgYkAAAAASUVORK5CYII="; ;// CONCATENATED MODULE: ./src/openlayers/control/Logo.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Logo * @aliasclass control.Logo * @category Control * @classdesc Logo控件。默认不显示,需手动添加控件。 * @extends {ol.control.Control} * @example * var control = new Logo(); * map.addControl(control); * @param {Object} options - 参数。 * @param {string} [options.imageUrl] - logo 图片地址。 * @param {number} [options.width] - logo 图片宽。 * @param {number} [options.height] - logo 图片高。 * @param {string} [options.link='https://iclient.supermap.io'] - 跳转链接。 * @param {string} [options.alt='SuperMap iClient'] - logo 图片失效时显示文本。 * @usage */ class Logo extends (external_ol_control_Control_default()) { constructor(options) { options = options || {}; options.imageUrl = options.imageUrl || null; options.width = options.width || null; options.height = options.height || null; options.alt = options.alt || "SuperMap iClient"; super(options); this.options = options; this.element = options.element = initLayerout.call(this); /** * @function Logo.prototype.initLayerout * @description 初始化图层信息。 */ function initLayerout() { var className = 'ol-control-logo ol-unselectable ol-control'; var div = document.createElement("div"); div.className = className; setDivStyle.call(this, div); var imgSrc = LogoBase64; if (this.options.imageUrl) { imgSrc = this.options.imageUrl; } var alt = this.options.alt; var link = this.options.link; var imageWidth = "94px"; var imageHeight = "29px"; var styleSize = "width:" + imageWidth + ";height:" + imageHeight + ";"; if (this.options.imageUrl) { imageWidth = this.options.width; imageHeight = this.options.height; styleSize = "width:" + imageWidth + ";height:" + imageHeight + ";"; if (!imageWidth || !imageHeight) { styleSize = ""; } } div.innerHTML = "" + "" + alt + ""; return div; } /** * @function Logo.prototype.setDivStyle * @description 设置对象 style。 * @param {HTMLElement} div - 待设置的 div。 */ function setDivStyle(div) { var attributionsElem = document.getElementsByClassName('ol-attribution'); attributionsElem = attributionsElem && attributionsElem[0]; var attrHeight = attributionsElem && attributionsElem.clientHeight || 29; div.style.bottom = (parseInt(attrHeight) + 6) + "px"; div.style.right = "4px"; div.style.marginTop = 0; div.style.marginLeft = 0; div.style.marginBottom = 0; div.style.marginRight = 0; var logoStyle = document.createElement('style'); logoStyle.type = 'text/css'; logoStyle.innerHTML = '.ol-control-logo,.ol-control-logo:hover {' + 'background-color: rgba(255,255,255,0);' + '}'; document.getElementsByTagName('head')[0].appendChild(logoStyle); } } } ;// CONCATENATED MODULE: ./src/openlayers/control/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/openlayers/overlay/vectortile/StyleMap.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @constant pointMap * @description 点图。 * @private */ var pointMap = { "point-file": "pointFile", "point-fill": "fillStyle", "point-radius": "pointRadius", "point-halo-radius": "pointHaloRadius", "point-halo-color": "pointHaloColor", "point-dx": "offsetX", "point-dy": "offsetY", "point-opacity": "globalAlpha", "point-comp-op": "globalCompositeOperation" }; /** * @constant lineMap * @description 线图。 * @private */ var lineMap = { "line-color": "strokeStyle", "line-width": "lineWidth", "line-cap": "lineCap", "line-join": "lineJoin", "line-miterlimit": "miterLimit", "line-dash-offset": "lineDashOffset", /*expand*/ "line-opacity": "strokeOpacity", "line-dasharray": "lineDasharray", "line-offset": "offset", "line-comp-op": "globalCompositeOperation" }; /** * @constant polygonMap * @description 面图。 * @private */ var polygonMap = { /*包括LINE的部分,用以设置面的外围边界*/ "line-color": "strokeStyle", "line-width": "lineWidth", "line-cap": "lineCap", "line-join": "lineJoin", "line-miterlimit": "miterLimit", "line-dash-offset": "lineDashOffset", /*expand*/ "line-opacity": "strokeOpacity", "line-dasharray": "lineDasharray", /*以下为面的特性*/ "polygon-fill": "fillStyle", "polygon-dx": "offsetX", "polygon-dy": "offsetY", "polygon-opacity": "fillOpacity", "polygon-comp-op": "globalCompositeOperation" }; /** * @enum StyleMap {Object} * @description 地图样式。 * @category BaseTypes Constant * @usage * ``` * // 浏览器 * * * // ES6 Import * import { StyleMap } from '{npm}'; * * const result = StyleMap.CartoStyleMap; * ``` */ var StyleMap = { /** CartoCSS 中的 style 属性名与 Canvas 的 style 属性名的对应表 */ CartoStyleMap: { "TEXT": { //前两个属性值组成font "text-size": "fontSize", "text-face-name": "fontFamily", "text-align": "textAlign", "text-vertical-alignment": "textBaseline", "text-horizontal-alignment": "textAlign", /*expand*/ 'text-bold': 'bold', 'text-weight': 'fontWeight', "text-name": "textName", "text-halo-radius": "haloRadius", "text-halo-color": "backColor", "text-fill": "foreColor", "text-opacity": "globalAlpha", "text-dx": "offsetX", "text-dy": "offsetY", "text-comp-op": "globalCompositeOperation" }, /*expand*/ "POINT": pointMap, "MULTIPOINT": pointMap, "LINE": lineMap, "LINESTRING": lineMap, "MULTILINESTRING": lineMap, "REGION": polygonMap, "POLYGON": polygonMap, "MULTIPOLYGON": polygonMap }, /** 服务端传过来的 style 属性名与 Canvas 的 style 属性名的对应表。 */ ServerStyleMap: { fillBackOpaque: { canvasStyle: "", type: "bool", defaultValue: true }, lineWidth: { canvasStyle: "lineWidth", type: "number", unit: "mm", defaultValue: 0.1 }, fillBackColor: { canvasStyle: "", type: "color", defaultValue: "rgba(0,0,0,0)" }, markerWidth: { canvasStyle: "", type: "number", unit: "mm", defaultValue: "" }, markerAngle: { canvasStyle: "", type: "number", unit: "degree", defaultValue: "" }, fillForeColor: { canvasStyle: "fillStyle", type: "color", defaultValue: "rgba(0,0,0,0)" }, foreColor: { canvasStyle: "fillStyle", type: "color", defaultValue: "rgba(0,0,0,0)" }, markerSize: { canvasStyle: "markerSize", type: "number", unit: "mm", defaultValue: 2.4 }, fillGradientOffsetRatioX: { canvasStyle: "", type: "number", defaultValue: 0 }, fillGradientOffsetRatioY: { canvasStyle: "", type: "number", defaultValue: 0 }, lineColor: { canvasStyle: "strokeStyle", type: "color", defaultValue: "rgba(0,0,0,0)" }, fillOpaqueRate: { canvasStyle: "", type: "number", defaultValue: 100 }, markerHeight: { canvasStyle: "", type: "number", unit: "mm", defaultValue: 0 }, fillGradientMode: { canvasStyle: "", type: "string", defaultValue: "NONE" }, fillSymbolID: { canvasStyle: "", type: "number", defaultValue: 0 }, fillGradientAngle: { canvasStyle: "", type: "number", unit: "degree", defaultValue: 0 }, markerSymbolID: { canvasStyle: "", type: "number", defaultValue: 0 }, lineSymbolID: { canvasStyle: "", type: "number", defaultValue: 0 } }, /** Canvas 中的 globalCompositeOperation 属性值与 CartoCSS 中的 CompOp 属性值对照表。 */ CartoCompOpMap: { "clear": "", "src": "", "dst": "", "src-over": "source-over", "dst-over": "destination-over", "src-in": "source-in", "dst-in": "destination-in", "src-out": "source-out", "dst-out": "destination-out", "src-atop": "source-atop", "dst-atop": "destination-atop", "xor": "xor", "plus": "lighter", "minus": "", "multiply": "", "screen": "", "overlay": "", "darken": "", "lighten": "lighter", "color-dodge": "", "color-burn": "", "hard-light": "", "soft-light": "", "difference": "", "exclusion": "", "contrast": "", "invert": "", "invert-rgb": "", "grain-merge": "", "grain-extract": "", "hue": "", "saturation": "", "color": "", "value": "" } }; ;// CONCATENATED MODULE: ./src/openlayers/overlay/vectortile/DeafultCanvasStyle.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @constant pointStyle * @description 点属性名的对应表。 * @private */ var pointStyle = { pointFile: "", /*expand*/ pointRadius: 3, pointHaloRadius: 1, pointHaloColor: "#c33", offsetX: 0, offsetY: 0, fillStyle: "#fc0", globalAlpha: 1, globalCompositeOperation: "source-over", imageSmoothingEnabled: true }; /** * @constant lineStyle * @description 线属性名的对应表。 * @private */ var lineStyle = { strokeStyle: "rgba(0,0,0,0)", lineWidth: 1, lineCap: "butt", lineJoin: "round", miterLimit: 10, lineDashOffset: 0, /*expand*/ lineDasharray: [], strokeOpacity: 1, offset: 0, globalAlpha: 1, globalCompositeOperation: "source-over", imageSmoothingEnabled: true }; /** * @constant polygonStyle * @description 面属性名的对应表。 * @private */ var polygonStyle = { /*包含LINE的部分*/ strokeStyle: "rgba(0,0,0,0)", lineWidth: 1, lineCap: "butt", lineJoin: "round", miterLimit: 10, lineDashOffset: 0, /*expand*/ lineOpacity: 1, fillOpacity: 1, lineDasharray: [], fillStyle: "rgba(0,0,0,0)", polygonOpacity: 1, /*expand*/ offsetX: 0, offsetY: 0, globalAlpha: 1, globalCompositeOperation: "source-over", imageSmoothingEnabled: true }; /** * @constant DeafultCanvasStyle * @description 默认画布属性名的对应表。 * @private */ var DeafultCanvasStyle = { /** * @constant DeafultCanvasStyle.prototype.TEXT * @description 默认文本样式。 */ "TEXT": { font: "10px sans-serif", textAlign: "middle", textBaseline: "center", direction: "ltr", /*expand*/ bold: false, haloRadius: 0, backColor: "rgba(255,255,255,1)", foreColor: "rgba(0,0,0,1)", // foreColor: "rgba(0,0,0,0)", offsetX: 0, offsetY: 0, textHeight: 0, globalAlpha: 1, globalCompositeOperation: "source-over", imageSmoothingEnabled: true }, "POINT": pointStyle, "MULTIPOINT": pointStyle, "LINE": lineStyle, "LINESTRING": lineStyle, "MULTILINESTRING": lineStyle, "REGION": polygonStyle, "POLYGON": polygonStyle, "MULTIPOLYGON": polygonStyle, "SHADOW": { shadowBlur: 0, shadowColor: "rgba(0,0,0,0)", shadowOffsetX: 0, shadowOffsetY: 0 }, "GLOBAL": { globalAlpha: 1, globalCompositeOperation: "source-over", imageSmoothingEnabled: true } }; ;// CONCATENATED MODULE: external "ol.util" const external_ol_util_namespaceObject = ol.util; ;// CONCATENATED MODULE: external "ol.geom.Geometry" const external_ol_geom_Geometry_namespaceObject = ol.geom.Geometry; var external_ol_geom_Geometry_default = /*#__PURE__*/__webpack_require__.n(external_ol_geom_Geometry_namespaceObject); ;// CONCATENATED MODULE: external "ol.render" const external_ol_render_namespaceObject = ol.render; ;// CONCATENATED MODULE: external "ol.source.Vector" const external_ol_source_Vector_namespaceObject = ol.source.Vector; var external_ol_source_Vector_default = /*#__PURE__*/__webpack_require__.n(external_ol_source_Vector_namespaceObject); ;// CONCATENATED MODULE: external "ol.layer.Vector" const external_ol_layer_Vector_namespaceObject = ol.layer.Vector; var external_ol_layer_Vector_default = /*#__PURE__*/__webpack_require__.n(external_ol_layer_Vector_namespaceObject); ;// CONCATENATED MODULE: external "ol.style" const external_ol_style_namespaceObject = ol.style; ;// CONCATENATED MODULE: external "ol.Feature" const external_ol_Feature_namespaceObject = ol.Feature; var external_ol_Feature_default = /*#__PURE__*/__webpack_require__.n(external_ol_Feature_namespaceObject); ;// CONCATENATED MODULE: external "ol.proj.Projection" const external_ol_proj_Projection_namespaceObject = ol.proj.Projection; var external_ol_proj_Projection_default = /*#__PURE__*/__webpack_require__.n(external_ol_proj_Projection_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/core/Util.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @name Util * @namespace * @category BaseTypes Util * @classdesc 工具类。 * @usage * ``` * // 浏览器 * * * * // ES6 Import * import { Util } from '{npm}'; * * const result = Util.getOlVersion(); * ``` */ const core_Util_Util = { getOlVersion() { if (external_ol_util_namespaceObject && external_ol_util_namespaceObject.VERSION) { return external_ol_util_namespaceObject.VERSION.split('.')[0]; } if (window && window.ol) { if (window.ol.util) { return '6'; } if (window.ol.WebGLMap) { return '5'; } } return '4'; }, /** * @function Util.toGeoJSON * @description 将传入对象转为 GeoJSON 格式。 * @param {Object} smObj - 待转参数。 */ toGeoJSON(smObj) { if (!smObj) { return null; } return new GeoJSON().toGeoJSON(smObj); }, /** * @function Util.toSuperMapGeometry * @description 将 GeoJSON 对象转为 SuperMap 几何图形。 * @param {GeoJSONObject} geoJSON - GeoJSON 对象。 */ toSuperMapGeometry(geoJSON) { if (!geoJSON || !geoJSON.type) { return null; } const result = new GeoJSON().read(geoJSON, 'FeatureCollection'); return result[0].geometry; }, /** * @function Util.resolutionToScale * @description 通过分辨率计算比例尺。 * @param {number} resolution - 分辨率。 * @param {number} dpi - 屏幕分辨率。 * @param {string} mapUnit - 地图单位。 * @returns {number} 比例尺。 */ resolutionToScale(resolution, dpi, mapUnit) { const inchPerMeter = 1 / 0.0254; // 地球半径。 const meterPerMapUnit = getMeterPerMapUnit(mapUnit); const scale = 1 / (resolution * dpi * inchPerMeter * meterPerMapUnit); return scale; }, /** * @function Util.toSuperMapBounds * @description 转为 SuperMapBounds 格式。 * @param {Array.} bounds - bounds 数组。 * @returns {Bounds} 返回 SuperMap 的 Bounds 对象。 */ toSuperMapBounds(bounds) { return new Bounds(bounds[0], bounds[1], bounds[2], bounds[3]); }, /** * @function Util.toProcessingParam * @description 将 Region 节点数组转为 Processing 服务需要的分析参数。 * @param {Array} points - Region 各个节点数组。 * @returns processing 服务裁剪、查询分析的分析参数。 */ toProcessingParam(points) { if (points.length < 1) { return ''; } const geometryParam = {}; const results = []; for (let i = 0; i < points.length; i++) { const point = { x: points[i][0], y: points[i][1] }; results.push(point); } results.push(results[0]); geometryParam.type = 'REGION'; geometryParam.points = results; return geometryParam; }, /** * @function Util.scaleToResolution * @description 通过比例尺计算分辨率。 * @param {number} scale - 比例尺。 * @param {number} dpi - 屏幕分辨率。 * @param {string} mapUnit - 地图单位。 * @returns {number} 分辨率。 */ scaleToResolution(scale, dpi, mapUnit) { const inchPerMeter = 1 / 0.0254; const meterPerMapUnitValue = getMeterPerMapUnit(mapUnit); const resolution = 1 / (scale * dpi * inchPerMeter * meterPerMapUnitValue); return resolution; }, /** * @private * @function Util.getMeterPerMapUnit * @description 获取每地图单位多少米。 * @param {string} mapUnit - 地图单位。 * @returns {number} 返回每地图单位多少米。 */ getMeterPerMapUnit: getMeterPerMapUnit, /** * @function Util.isArray * @description 判断是否为数组格式。 * @param {Object} obj - 待判断对象。 * @returns {boolean} 是否是数组。 */ isArray, /** * @function Util.Csv2GeoJSON * @description 将 csv 格式转为 GeoJSON。 * @param {Object} csv - csv 对象。 * @param {Object} options - 转换参数。 */ Csv2GeoJSON(csv, options) { const defaultOptions = { titles: ['lon', 'lat'], latitudeTitle: 'lat', longitudeTitle: 'lon', fieldSeparator: ',', lineSeparator: '\n', deleteDoubleQuotes: true, firstLineTitles: false }; options = options || defaultOptions; const _propertiesNames = []; if (typeof csv === 'string') { let titulos = options.titles; if (options.firstLineTitles) { csv = csv.split(options.lineSeparator); if (csv.length < 2) { return; } titulos = csv[0]; csv.splice(0, 1); csv = csv.join(options.lineSeparator); titulos = titulos.trim().split(options.fieldSeparator); for (let i = 0; i < titulos.length; i++) { titulos[i] = _deleteDoubleQuotes(titulos[i]); } options.titles = titulos; } for (let i = 0; i < titulos.length; i++) { let prop = titulos[i] .toLowerCase() .replace(/[^\w ]+/g, '') .replace(/ +/g, '_'); if (prop === '' || prop === '_') { prop = `prop-${i}`; } _propertiesNames[i] = prop; } csv = _csv2json(csv); } return csv; function _deleteDoubleQuotes(cadena) { if (options.deleteDoubleQuotes) { cadena = cadena.trim().replace(/^"/, '').replace(/"$/, ''); } return cadena; } function _csv2json(csv) { const json = {}; json['type'] = 'FeatureCollection'; json['features'] = []; const titulos = options.titles; csv = csv.split(options.lineSeparator); for (let num_linea = 0; num_linea < csv.length; num_linea++) { const campos = csv[num_linea].trim().split(options.fieldSeparator), lng = parseFloat(campos[titulos.indexOf(options.longitudeTitle)]), lat = parseFloat(campos[titulos.indexOf(options.latitudeTitle)]); const isInRange = lng < 180 && lng > -180 && lat < 90 && lat > -90; if (!(campos.length === titulos.length && isInRange)) { continue; } const feature = {}; feature['type'] = 'Feature'; feature['geometry'] = {}; feature['properties'] = {}; feature['geometry']['type'] = 'Point'; feature['geometry']['coordinates'] = [lng, lat]; for (let i = 0; i < titulos.length; i++) { if (titulos[i] !== options.latitudeTitle && titulos[i] !== options.longitudeTitle) { feature['properties'][_propertiesNames[i]] = _deleteDoubleQuotes(campos[i]); } } json['features'].push(feature); } return json; } }, /** * @function Util.createCanvasContext2D * @description 创建 2D 画布。 * @param {number} opt_width - 画布宽度。 * @param {number} opt_height - 画布高度。 */ createCanvasContext2D(opt_width, opt_height) { const canvas = document.createElement('CANVAS'); if (opt_width) { canvas.width = opt_width; } if (opt_height) { canvas.height = opt_height; } return canvas.getContext('2d'); }, /** * @function Util.supportWebGL2 * @description 是否支持 webgl2。 */ supportWebGL2() { const canvas = document.createElement('canvas'); return Boolean(canvas && canvas.getContext('webgl2')); }, /** * @function Util.isString * @description 是否为字符串 * @param {string} str - 需要判断的内容 * @returns {boolean} */ isString, /** * @function Util.isObject * @description 是否为对象 * @param {any} obj - 需要判断的内容 * @returns {boolean} */ isObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; }, /** * @function Util.trim * @description 字符串裁剪两边的空格 * @param {string} str - 需要裁剪的字符串 * @returns {boolean} */ trim(str = '') { return str.replace(/(^\s*)|(\s*$)/g, ''); }, /** * @function Util.newGuid * @description 随机生成id * @param {string} attr - 几位数字的id * @returns {string} */ newGuid(attr) { let len = attr || 32; let guid = ''; for (let i = 1; i < len; i++) { let n = Math.floor(Math.random() * 16.0).toString(16); guid += n; } return guid; }, /** * @function Util.isNumber * @description 检测数据是否为number * @param {string} value - 值,未知数据类型 * @returns {boolean} */ isNumber(value) { if (value === '') { return false; } let mdata = Number(value); if (mdata === 0) { return true; } return !isNaN(mdata); }, /** * @function Util.isMatchAdministrativeName * @param {string} featureName 原始数据中的地名 * @param {string} fieldName 需要匹配的地名 * @returns {boolean} 是否匹配 */ isMatchAdministrativeName, /** * @function Util.getHighestMatchAdministration * @param {string} featureName 初始匹配的要素数组 * @param {string} fieldName 要匹配的地名 * @returns {boolean} 是否匹配 */ getHighestMatchAdministration(features, fieldName) { let filterFeatures = features.filter((item) => { return isMatchAdministrativeName(item.properties.Name, fieldName); }); let maxMatchPercent = 0, maxMatchFeature = null; filterFeatures.forEach((feature) => { let count = 0; Array.from(new Set(feature.properties.Name.split(''))).forEach((char) => { if (fieldName.includes(char)) { count++; } }); if (count > maxMatchPercent) { maxMatchPercent = count; maxMatchFeature = feature; } }); return maxMatchFeature; }, /** * @function Util.setMask * @description 为图层设置掩膜。 * @version 10.1.0 * @param {ol.layer.Layer|Array.} layers 图层 * @param {ol.geom.Geometry|ol.Feature} polygon 掩膜矢量要素,支持面类型的要素。 */ setMask(layers, polygon) { if (!polygon) { return; } const geo = polygon instanceof (external_ol_Feature_default()) ? polygon.getGeometry() : polygon; if (!(geo instanceof (external_ol_geom_Geometry_default())) && ['MultiPolygon', 'Polygon'].indexOf(polygon.getType()) < 0) { return; } const feature = polygon instanceof (external_ol_Feature_default()) ? polygon : new (external_ol_Feature_default())(polygon); const style = new external_ol_style_namespaceObject.Style({ fill: new external_ol_style_namespaceObject.Fill({ color: 'black' }) }); const clipLayer = new (external_ol_layer_Vector_default())({ source: new (external_ol_source_Vector_default())({ features: [feature], wrapX: false }) }); const clipRender = function (e) { const vectorContext = (0,external_ol_render_namespaceObject.getVectorContext)(e); e.context.globalCompositeOperation = 'destination-in'; clipLayer.getSource().forEachFeature(function (feature) { vectorContext.drawFeature(feature, style); e.context.globalCompositeOperation = 'source-over'; }); }; const todoLayers = Array.isArray(layers) ? layers : [layers]; unsetMask(todoLayers); todoLayers.forEach((layer) => { layer.classNameBak_ = layer.className_; layer.className_ = `ol_mask_layer_${layer.ol_uid}`; layer.clipRender = clipRender; layer.extentBak_ = layer.getExtent(); layer.setExtent(clipLayer.getSource().getExtent()); layer.on('postrender', clipRender); layer.changed(); }); }, /** * @function Util.unsetMask * @description 取消图层掩膜。 * @version 10.1.0 * @param {ol.layer.Layer|Array.} layers 图层 */ unsetMask, getZoomByResolution(scale, scales) { return getZoomByResolution(scale, scales); }, scalesToResolutions(scales, bounds, dpi, unit, mapobj, level) { return scalesToResolutions(scales, bounds, dpi, unit, mapobj, level); }, getProjection(prjCoordSys, extent) { let projection = (0,external_ol_proj_namespaceObject.get)(`EPSG:${prjCoordSys.epsgCode}`); if (prjCoordSys.type == 'PCS_NON_EARTH') { projection = new (external_ol_proj_Projection_default())({ extent, units: 'm', code: '0' }); } if (!projection) { console.error(`The projection of EPSG:${prjCoordSys.epsgCode} is missing, please register the projection of EPSG:${prjCoordSys.epsgCode} first, refer to the documentation: https://iclient.supermap.io/web/introduction/leafletDevelop.html#multiProjection`); } return projection; } } function isString(str) { return typeof str === 'string' && str.constructor === String; } function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } function unsetMask(layers) { const todoLayers = Array.isArray(layers) ? layers : [layers]; for (let index = 0; index < todoLayers.length; index++) { const layer = todoLayers[index]; if (!layer.clipRender) { continue; } layer.un('postrender', layer.clipRender); layer.className_ = layer.classNameBak_; layer.setExtent(layer.extentBak); delete layer.classNameBak_; delete layer.clipRender; delete layer.extentBak_; layer.changed(); } } function isMatchAdministrativeName(featureName, fieldName) { if (isString(fieldName)) { let shortName = featureName.substr(0, 2); // 张家口市和张家界市 特殊处理 if (shortName === '张家') { shortName = featureName.substr(0, 3); } return !!fieldName.match(new RegExp(shortName)); } return false; } ;// CONCATENATED MODULE: external "function(){try{return canvg}catch(e){return {}}}()" const external_function_try_return_canvg_catch_e_return_namespaceObject = function(){try{return canvg}catch(e){return {}}}(); var external_function_try_return_canvg_catch_e_return_default = /*#__PURE__*/__webpack_require__.n(external_function_try_return_canvg_catch_e_return_namespaceObject); ;// CONCATENATED MODULE: external "ol.style.Style" const external_ol_style_Style_namespaceObject = ol.style.Style; var external_ol_style_Style_default = /*#__PURE__*/__webpack_require__.n(external_ol_style_Style_namespaceObject); ;// CONCATENATED MODULE: external "ol.style.Icon" const external_ol_style_Icon_namespaceObject = ol.style.Icon; var external_ol_style_Icon_default = /*#__PURE__*/__webpack_require__.n(external_ol_style_Icon_namespaceObject); ;// CONCATENATED MODULE: external "ol.style.Circle" const external_ol_style_Circle_namespaceObject = ol.style.Circle; var external_ol_style_Circle_default = /*#__PURE__*/__webpack_require__.n(external_ol_style_Circle_namespaceObject); ;// CONCATENATED MODULE: external "ol.style.Fill" const external_ol_style_Fill_namespaceObject = ol.style.Fill; var external_ol_style_Fill_default = /*#__PURE__*/__webpack_require__.n(external_ol_style_Fill_namespaceObject); ;// CONCATENATED MODULE: external "ol.style.Stroke" const external_ol_style_Stroke_namespaceObject = ol.style.Stroke; var external_ol_style_Stroke_default = /*#__PURE__*/__webpack_require__.n(external_ol_style_Stroke_namespaceObject); ;// CONCATENATED MODULE: external "ol.style.Text" const external_ol_style_Text_namespaceObject = ol.style.Text; var external_ol_style_Text_default = /*#__PURE__*/__webpack_require__.n(external_ol_style_Text_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/core/StyleUtils.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ var padding = 8, doublePadding = padding * 2; const ZERO = 0.0000001; /** * @class StyleUtils * @classdesc 样式工具类。 * @private */ class StyleUtils { /** * @function StyleUtils.getValidStyleFromLayerInfo * @description 通过图层信息获取有效的样式。 * @param {Object} layerInfo - 图层信息。 * @param {ol.Feature} feature - 要素。 * @param {string} url - 图层数据地址。 * @returns {ol.style.Style} 返回图层样式。 */ static getValidStyleFromLayerInfo(layerInfo, feature, url) { var type = feature.getGeometry().getType().toUpperCase(), shader = layerInfo.layerStyle, style = this.getDefaultStyle(type); if ((type === "POINT" || type === 'MULTIPOINT') && !feature.getProperties().textStyle && layerInfo.type !== 'LABEL' && !feature.getProperties().TEXT_FEATURE_CONTENT) { if (shader) { var symbolParameters = { "transparent": true, "resourceType": "SYMBOLMARKER", "picWidth": Math.ceil(shader.markerSize * DOTS_PER_INCH * INCHES_PER_UNIT.mm) || 13, "picHeight": Math.ceil(shader.markerSize * DOTS_PER_INCH * INCHES_PER_UNIT.mm) || 13, "style": JSON.stringify(shader) }; var imageUrl = Util.urlAppend(url + "/symbol.png", Util.getParameterString(symbolParameters)); style.pointFile = imageUrl; return new (external_ol_style_Style_default())({ image: new (external_ol_style_Icon_default())({ src: style.pointFile }) }); } return this.toOLPointStyle(style); } else if ((type === "POINT" || type === 'MULTIPOINT') && (feature.getProperties().textStyle || layerInfo.type === 'LABEL' || feature.getProperties().TEXT_STYLE_INFO)) { style = this.getDefaultStyle('TEXT'); if (feature.getProperties().textStyle) { shader = feature.getProperties().textStyle; } if (feature.getProperties().TEXT_STYLE_INFO) { shader = JSON.parse(feature.getProperties().TEXT_STYLE_INFO).textStyle; } if (shader && shader !== "{}") { var fontStr = ""; //设置文本是否倾斜 style.fontStyle = shader.italic ? "italic" : "normal"; //设置文本是否使用粗体 style.fontWeight = shader.bold ? shader.fontWeight : "normal"; //设置文本的尺寸(对应fontHeight属性)和行高,行高iserver不支持,默认5像素 //固定大小的时候单位是毫米 var text_h = shader.fontHeight * DOTS_PER_INCH * INCHES_PER_UNIT.mm * 0.85; //毫米转像素,服务端的字体貌似要稍微小一点 style.fontSize = text_h + "px"; //设置文本字体类型 //在桌面字体钱加@时为了解决对联那种形式,但是在canvas不支持,并且添加了@会导致 //字体大小被固定,这里需要去掉 if (shader.fontName.indexOf("@")) { fontStr = shader.fontName.replace(/@/g, ""); } else { fontStr = shader.fontName } style.fontFamily = fontStr; style.textHeight = text_h; //设置对齐方式 var alignStr = shader.align.replace(/TOP|MIDDLE|BASELINE|BOTTOM/, ""); style.textAlign = alignStr.toLowerCase(); var baselineStr = shader.align.replace(/LEFT|RIGHT|CENTER/, ""); if (baselineStr === "BASELINE") { baselineStr = "alphabetic"; } style.textBaseline = baselineStr.toLowerCase(); /*//首先判定是否需要绘制阴影,如果需要绘制,阴影应该在最下面 if(shader.shadow) { //桌面里面的阴影没有做模糊处理,这里统一设置为0, style.shadowBlur=0; //和桌面统一,往右下角偏移阴影,默认3像素 style.shadowOffsetX=3; style.shadowOffsetY=3; //颜色取一个灰色,调成半透明 style.shadowColor="rgba(50,50,50,0.5)"; }else{ style.shadowOffsetX=0; style.shadowOffsetY=0; }*/ style.haloRadius = shader.outline ? shader.outlineWidth : 0; style.backColor = "rgba(" + shader.backColor.red + "," + shader.backColor.green + "," + shader.backColor.blue + ",1)"; style.foreColor = "rgba(" + shader.foreColor.red + "," + shader.foreColor.green + "," + shader.foreColor.blue + ",1)"; style.rotation = shader.rotation; } var text; if (feature.getProperties().textStyle && feature.getProperties().texts) { text = feature.getProperties().texts[0]; } if (layerInfo.type === 'LABEL') { var textField = layerInfo.textField; if (textField && textField.indexOf('.')) { var arr = textField.split('.'); textField = arr && arr.length > 0 && arr[arr.length - 1]; } text = feature.getProperties().attributes ? feature.getProperties().attributes[textField] : feature.getProperties()[textField]; } if (feature.getProperties().TEXT_FEATURE_CONTENT) { text = feature.getProperties().TEXT_FEATURE_CONTENT; } if (!text) { return this.toOLPointStyle(this.getDefaultStyle('POINT')); } return this.toOLTextStyle(style, text); } else if (shader) { //目前只实现桌面系统默认的几种symbolID,非系统默认的面用颜色填充替代,线则用实线来替代 var fillSymbolID = shader["fillSymbolID"] > 7 ? 0 : shader["fillSymbolID"]; var lineSymbolID = shader["lineSymbolID"] > 5 ? 0 : shader["lineSymbolID"]; for (var attr in shader) { var obj = StyleMap.ServerStyleMap[attr]; var canvasStyle = obj.canvasStyle; if (canvasStyle && canvasStyle != "") { var value; switch (obj.type) { case "number": value = shader[attr]; if (obj.unit) { //将单位转换为像素单位 value = value * DOTS_PER_INCH * INCHES_PER_UNIT[obj.unit] * 2.5; } style[canvasStyle] = value; break; case "color": var color = shader[attr]; var backColor = shader["fillBackColor"]; var alpha = 1; if (canvasStyle === "fillStyle") { if (fillSymbolID === 0 || fillSymbolID === 1) { //当fillSymbolID为0时,用颜色填充,为1是无填充,即为透明填充,alpha通道为0 alpha = 1 - fillSymbolID; value = "rgba(" + color.red + "," + color.green + "," + color.blue + "," + alpha + ")"; } else { //当fillSymbolID为2~7时,用的纹理填充,但要按照前景色修改其颜色 try { var tempCvs = document.createElement("canvas"); tempCvs.height = 8; tempCvs.width = 8; var tempCtx = tempCvs.getContext("2d"); var image = new Image(); if (this.layer && this.layer.fillImages) { tempCtx.drawImage(this.layer.fillImages["System " + fillSymbolID], 0, 0); } var imageData = tempCtx.getImageData(0, 0, tempCvs.width, tempCvs.height); var pix = imageData.data; for (var i = 0, len = pix.length; i < len; i += 4) { var r = pix[i], g = pix[i + 1], b = pix[i + 2]; //将符号图片中的灰色或者黑色的部分替换为前景色,其余为后景色 if (r < 225 && g < 225 && b < 225) { pix[i] = color.red; pix[i + 1] = color.green; pix[i + 2] = color.blue; } else if (backColor) { pix[i] = backColor.red; pix[i + 1] = backColor.green; pix[i + 2] = backColor.blue; } } tempCtx.putImageData(imageData, 0, 0); image.src = tempCvs.toDataURL(); if (this.context) { value = this.context.createPattern(image, "repeat"); } } catch (e) { throw Error(e.message); } } } else if (canvasStyle === "strokeStyle") { if (lineSymbolID === 0 || lineSymbolID === 5) { //对于lineSymbolID为0时,线为实线,为lineSymbolID为5时,为无线模式,即线为透明,即alpha通道为0 alpha = lineSymbolID === 0 ? 1 : 0; } else { //以下几种linePattern分别模拟了桌面的SymbolID为1~4几种符号的linePattern var linePattern = [1, 0]; switch (lineSymbolID) { case 1: linePattern = [9.7, 3.7]; break; case 2: linePattern = [3.7, 3.7]; break; case 3: linePattern = [9.7, 3.7, 2.3, 3.7]; break; case 4: linePattern = [9.7, 3.7, 2.3, 3.7, 2.3, 3.7]; break; default: break } style.lineDasharray = linePattern; } value = "rgba(" + color.red + "," + color.green + "," + color.blue + "," + alpha + ")"; } style[canvasStyle] = value; break; default: break; } } } } if (type === 'LINESTRING' || type === 'MULTILINESTRING') { return this.toOLLineStyle(style); } if (type === 'POLYGON' || type === 'MULTIPOLYGON') { return this.toOLPolygonStyle(style); } } /** * @function StyleUtils.getStyleFromCarto * @description 从 Carto 中获取有效的样式。 * @param {number} zoom -缩放级别。 * @param {number} scale - 比例尺。 * @param {Array.} shader - 渲染器对象数组。 * @param {Object} feature - 要素。 * @param {string} fromServer - 服务源。 * @param {string} url - 地址。 */ static getStyleFromCarto(zoom, scale, shader, feature, fromServer, url) { var type = feature.getGeometry().getType().toUpperCase(), attributes = {}, style = this.getDefaultStyle(type); attributes.FEATUREID = feature.getProperties().id; attributes.SCALE = scale; var cartoStyleType = feature.getProperties().type === "TEXT" ? "TEXT" : type; var cartoStyleMap = StyleMap.CartoStyleMap[cartoStyleType]; var fontSize, fontName; if (shader) { for (var i = 0, len = shader.length; i < len; i++) { var _shader = shader[i]; var prop = cartoStyleMap[_shader.property]; var value = _shader.getValue(attributes, zoom, true); if ((value !== null) && prop) { if (prop === "fontSize") { if (fromServer) { value *= 0.8; } //斜杠后面为行间距,默认为0.5倍行间距 fontSize = value + "px"; style.fontSize = fontSize; } else if (prop === "fontName") { fontName = value; style.fontName = fontName; } else { if (prop === "globalCompositeOperation") { value = StyleMap.CartoCompOpMap[value]; if (!value) { continue; } } else if (fromServer && prop === 'pointFile') { value = url + '/tileFeature/symbols/' + value.replace(/(___)/gi, '@'); value = value.replace(/(__0__0__)/gi, '__8__8__'); } if (prop === 'lineWidth' && value < 1) { value = Math.ceil(value); } style[prop] = value; } } } } if (feature.getProperties().type === 'TEXT') { var text; if (feature.getProperties().texts) { text = feature.getProperties().texts[0]; } if (text == null && style.textName) { var textName = style.textName.substring(1, style.textName.length - 1); text = feature.getProperties().attributes ? feature.getProperties().attributes[textName] : feature.getProperties()[textName]; if (text != null) { var texts = feature.getProperties().texts || []; texts.push(text); feature.setProperties({ texts: texts }); } } return this.toOLTextStyle(style, text) } if (type === 'POINT' || type === 'MULTIPOINT') { return this.toOLPointStyle(style); } if (type === 'LINESTRING' || type === 'MULTILINESTRING') { return this.toOLLineStyle(style); } if (type === 'POLYGON' || type === 'MULTIPOLYGON') { return this.toOLPolygonStyle(style); } } /** * @function StyleUtils.toOLPointStyle * @description 点样式。 * @param {Object} style - 样式参数。 * @returns {ol.style.Style} 获取点样式。 */ static toOLPointStyle(style) { if (style.pointFile !== '') { return new (external_ol_style_Style_default())({ image: new (external_ol_style_Icon_default())({ src: style.pointFile }) }); } return new (external_ol_style_Style_default())({ image: new (external_ol_style_Circle_default())({ radius: style.pointRadius, fill: new (external_ol_style_Fill_default())({ color: style.fillStyle }), stroke: new (external_ol_style_Stroke_default())({ color: style.pointHaloColor, width: style.pointHaloRadius }) }) }); } /** * @function StyleUtils.toOLLineStyle * @description 线样式。 * @param {Object} style - 样式参数。 * @returns {ol.style.Style} 获取线的样式。 */ static toOLLineStyle(style) { return new (external_ol_style_Style_default())({ stroke: new (external_ol_style_Stroke_default())({ color: style.strokeStyle, width: style.lineWidth, lineCap: style.lineCap, lineDash: style.lineDasharray, lineDashOffset: style.lineDashOffset, lineJoin: style.lineJoin, miterLimit: style.miterLimit }) }); } /** * @function StyleUtils.toOLPolygonStyle * @description 面样式。 * @param {Object} style - 样式参数。 * @returns {ol.style.Style} 获取面的样式。 */ static toOLPolygonStyle(style) { var fill = new (external_ol_style_Fill_default())({ color: style.fillStyle }); var stroke = new (external_ol_style_Stroke_default())({ color: style.strokeStyle, width: style.lineWidth, lineCap: style.lineCap, lineDash: style.lineDasharray, lineDashOffset: style.lineDashOffset, lineJoin: style.lineJoin, miterLimit: style.miterLimit }); return new (external_ol_style_Style_default())({ fill: fill, stroke: stroke }); } /** * @function StyleUtils.toOLTextStyle * @description 文本样式。 * @param {Object} style - 样式对象。 * @param {string} text - 文本参数。 * @returns {ol.style.Style} 获取的文本样式。 */ static toOLTextStyle(style, text) { return new (external_ol_style_Style_default())({ text: new (external_ol_style_Text_default())({ font: (style.fontStyle || '') + ' ' + (style.fontWeight || '') + ' ' + (style.fontSize || '') + ' ' + style.fontFamily, text: text, textAlign: style.textAlign, textBaseline: style.textBaseline, fill: new (external_ol_style_Fill_default())({ color: style.foreColor }), stroke: new (external_ol_style_Stroke_default())({ color: style.backColor }), offsetX: style.offsetX, offsetY: style.offsetY }) }) } /** * @function StyleUtils.dashStyle * @description 符号样式。 * @param {Object} style - 样式参数。 * @param {number} widthFactor - 宽度系数。 */ static dashStyle(style, widthFactor) { if (!style) { return []; } var w = style.strokeWidth * widthFactor; var str = style.strokeDashstyle || style.lineDash; switch (str) { case 'solid': return [0]; case 'dot': return [1, 4 * w]; case 'dash': return [4 * w, 4 * w]; case 'dashdot': return [4 * w, 4 * w, 1, 4 * w]; case 'longdash': return [8 * w, 4 * w]; case 'longdashdot': return [8 * w, 4 * w, 1, 4 * w]; default: if (!str) { return []; } if (Util.isArray(str)) { return str; } str = StringExt.trim(str).replace(/\s+/g, ","); return str.replace(/\[|\]/gi, "").split(","); } } /** * @function StyleUtils.getStyleFromiPortalMarker * @description 从 iPortal 标记获取样式。 * @param {Object} icon - 图标参数。 */ static getStyleFromiPortalMarker(icon) { if (icon.indexOf("./") == 0) { return null; } //兼容iportal示例的问题 // if (icon.indexOf("http://support.supermap.com.cn:8092/static/portal") == 0) { // icon = icon.replace("http://support.supermap.com.cn:8092/static/portal", "http://support.supermap.com.cn:8092/apps/viewer/static"); // } return new (external_ol_style_Style_default())({ image: new (external_ol_style_Icon_default())({ src: icon, opacity: 1, size: [48, 43], anchor: [0.5, 1] }) }); } /** * @function StyleUtils.getStyleFromiPortalStyle * @description 从 iPortal 标记获取样式。 * @param {Object} iPortalStyle - iportal 样式。 * @param {string} type - 样式类型。 * @param {Object} fStyle - 要素样式。 */ static getStyleFromiPortalStyle(iPortalStyle, type, fStyle) { var featureStyle = fStyle ? JSON.parse(fStyle) : null; var me = this; if (type === 'Point' || type === 'MultiPoint') { var pointStyle = featureStyle || iPortalStyle.pointStyle; if (pointStyle.externalGraphic) { if (pointStyle.externalGraphic.indexOf("./") == 0) { return null; } //兼容iportal示例的问题 // if (pointStyle.externalGraphic.indexOf("http://support.supermap.com.cn:8092/static/portal") == 0) { // pointStyle.externalGraphic = pointStyle.externalGraphic.replace("http://support.supermap.com.cn:8092/static/portal", "http://support.supermap.com.cn:8092/apps/viewer/static"); // } return new (external_ol_style_Style_default())({ image: new (external_ol_style_Icon_default())({ src: pointStyle.externalGraphic, opacity: pointStyle.graphicOpacity, size: [pointStyle.graphicWidth, pointStyle.graphicHeight] //anchor: [-pointStyle.graphicXOffset / pointStyle.graphicWidth, -pointStyle.graphicYOffset / pointStyle.graphicHeight] }) }); } return new (external_ol_style_Style_default())({ image: new (external_ol_style_Circle_default())({ fill: new (external_ol_style_Fill_default())({ color: me.hexToRgba(pointStyle.fillColor, pointStyle.fillOpacity) }), stroke: new (external_ol_style_Stroke_default())({ color: me.hexToRgba(pointStyle.strokeColor, pointStyle.strokeOpacity), lineCap: pointStyle.strokeLineCap, lineDash: this.dashStyle(pointStyle, 1), width: pointStyle.strokeWidth }), radius: pointStyle.pointRadius }) }); } if (type === 'LineString' || type === 'MultiLineString' || type === 'Box') { var lineStyle = featureStyle || iPortalStyle.lineStyle; return new (external_ol_style_Style_default())({ stroke: new (external_ol_style_Stroke_default())({ color: me.hexToRgba(lineStyle.strokeColor, lineStyle.strokeOpacity), lineCap: lineStyle.strokeLineCap, lineDash: this.dashStyle(lineStyle, 1), width: lineStyle.strokeWidth }) }); } if (type === 'Polygon' || type === 'MultiPolygon') { var polygonStyle = featureStyle || iPortalStyle.polygonStyle; return new (external_ol_style_Style_default())({ fill: new (external_ol_style_Fill_default())({ color: me.hexToRgba(polygonStyle.fillColor, polygonStyle.fillOpacity) }), stroke: new (external_ol_style_Stroke_default())({ color: me.hexToRgba(polygonStyle.strokeColor, polygonStyle.strokeOpacity), lineCap: polygonStyle.strokeLineCap, lineDash: this.dashStyle(polygonStyle, 1), width: polygonStyle.strokeWidth }) }); } } /** * @function StyleUtils.hexToRgba * @description 十六进制转 RGBA 格式。 * @param {Object} hex - 十六进制格式参数。 * @param {number} opacity -Alpha 参数。 * @returns {string} 生成的 RGBA 格式。 */ static hexToRgba(hex, opacity) { var color = [], rgba = []; hex = hex.replace(/#/, ""); if (hex.length == 3) { var tmp = []; for (let i = 0; i < 3; i++) { tmp.push(hex.charAt(i) + hex.charAt(i)); } hex = tmp.join(""); } for (let i = 0; i < 6; i += 2) { color[i] = "0x" + hex.substr(i, 2); rgba.push(parseInt(Number(color[i]))); } rgba.push(opacity); return "rgba(" + rgba.join(",") + ")"; } /** * @function StyleUtils.getDefaultStyle * @description 获取默认风格 * @param {string} type - 类型参数。 * @returns {string} */ static getDefaultStyle(type) { var style = {}; var canvasStyle = DeafultCanvasStyle[type]; for (var prop in canvasStyle) { var val = canvasStyle[prop]; style[prop] = val; } return style; } /** * @function StyleUtils.getDefaultStyle * @description 将样式对象转换成openlayer要求的ol.style * @param {string} style - 样式对象 * @param {string} type - feature的类型 * @returns {Promise} */ static async toOpenLayersStyle(style, type) { style = style || this.getDefaultStyle(); let olStyle = new (external_ol_style_Style_default())(); let newImage, newFill, newStroke; let { fillColor, fillOpacity, strokeColor, strokeWidth, strokeOpacity, radius, lineCap, src, scale, offsetX, offsetY, //size, //imgSize, anchor } = style; let fillColorArray = this.hexToRgb(fillColor); if (fillColorArray) { fillColorArray.push(fillOpacity); } let strokeColorArray = this.hexToRgb(strokeColor); if (strokeColorArray) { strokeColorArray.push(strokeOpacity); } if (type === "POINT") { if (src) { if (/.+(\.svg$)/.test(src)) { if (!this.svgDiv) { this.svgDiv = document.createElement('div'); document.body.appendChild(this.svgDiv); } await this.getCanvasFromSVG(src, this.svgDiv, (canvas) => { newImage = new (external_ol_style_Icon_default())({ img: canvas, scale: radius / canvas.width, imgSize: [canvas.width, canvas.height], anchor: [0.5, 0.5] }) }) } else { newImage = new (external_ol_style_Icon_default())({ src: src, scale: scale, anchor: anchor }); } } else { newImage = new (external_ol_style_Circle_default())({ radius, fill: new (external_ol_style_Fill_default())({ color: fillColorArray }), stroke: new (external_ol_style_Stroke_default())({ width: strokeWidth || ZERO, color: strokeColorArray }), displacement: this.getCircleDisplacement(radius, offsetX, offsetY) }); } olStyle.setImage(newImage); } else if (type === "LINE" || type === "LINESTRING" || type === 'MULTILINESTRING' || type === 'LINEARRING') { newStroke = new (external_ol_style_Stroke_default())({ width: strokeWidth || ZERO, color: strokeColorArray, lineCap: lineCap || 'round', lineDash: this.dashStyle(style, 1) }); olStyle.setStroke(newStroke); } else if (type === 'POLYGON' || type === 'MULTIPOLYGON' || type === 'REGION') { newFill = new (external_ol_style_Fill_default())({ color: fillColorArray }); newStroke = new (external_ol_style_Stroke_default())({ width: strokeWidth || ZERO, color: strokeColorArray, lineCap: lineCap || 'round', lineDash: this.dashStyle(style, 1) }); olStyle.setFill(newFill); olStyle.setStroke(newStroke); } else { let result = this.getCanvas(style); newImage = new (external_ol_style_Icon_default())({ img: result.canvas, imgSize: [result.width, result.height], scale: 1, anchor: [0.5, 0.5] }); olStyle.setImage(newImage); } return olStyle; } /** * @function StyleUtils.getIconAnchor * @description 获取图标的锚点 * @param {number} offsetX - X方向偏移分数 * @param {number} offsetY - Y方向偏移分数 * @returns {Array.} */ static getIconAnchor(offsetX=0.5, offsetY=0.5) { return [offsetX, offsetY]; } /** * @function StyleUtils.getCircleDisplacement * @description 获取圆圈的偏移 * @param {number} radius - 圆圈半径 * @param {number} offsetX - X方向偏移分数 * @param {number} offsetY - Y方向偏移分数 * @returns {Array.} */ static getCircleDisplacement(radius, offsetX=0, offsetY=0) { const dispX = radius*offsetX, dispY = radius*offsetY; return [dispX, -dispY]; } /** * @function StyleUtils.getTextOffset * @description 获取字体图标的偏移值 * @param {string} fontSize - 字体大小,如12px * @param {number} offsetX - X方向偏移分数 * @param {number} offsetY - Y方向偏移分数 * @returns {Object} */ static getTextOffset(fontSize, offsetX=0, offsetY=0) { const radius = fontSize.substr(0, fontSize.length - 2) / 2; return { x: radius*offsetX, y: radius*offsetY }; } /** * 获取文字标注对应的canvas * @param style * @returns {{canvas: *, width: number, height: number}} */ static getCanvas(style) { let canvas; if (style.canvas) { if (document.querySelector("#" + style.canvas)) { canvas = document.getElemntById(style.canvas); } else { canvas = this.createCanvas(style); } } else { //不存在canvas,当前feature canvas = this.createCanvas(style); style.canvas = canvas.id; } canvas.style.display = "none"; var ctx = canvas.getContext("2d"); //行高 let lineHeight = Number(style.font.replace(/[^0-9]/ig, "")); let textArray = style.text.split('\r\n'); let lenght = textArray.length; //在改变canvas大小后再绘制。否则会被清除 ctx.font = style.font; let size = this.drawRect(ctx, style, textArray, lineHeight, canvas); this.positionY = padding; if (lenght > 1) { textArray.forEach(function (text, i) { if (i !== 0) { this.positionY = this.positionY + lineHeight; } this.canvasTextAutoLine(text, style, ctx, lineHeight, size.width); }, this); } else { this.canvasTextAutoLine(textArray[0], style, ctx, lineHeight, size.width); } return { canvas: canvas, width: size.width, height: size.height }; } /** * 创建当前feature对应的canvas * @param {Object} style * @returns {HTMLElement} */ static createCanvas(style) { let div = document.createElement('div'); document.body.appendChild(div); let canvas = document.createElement('canvas'); canvas.id = style.canvas ? style.canvas : 'textCanvas' + core_Util_Util.newGuid(8); div.appendChild(canvas); return canvas; } /** * 绘制矩形边框背景 * @param ctx * @param style * @param textArray * @param lineHeight * @param canvas * @returns {{width: number, height: number}} */ static drawRect(ctx, style, textArray, lineHeight, canvas) { let backgroundFill = style.backgroundFill, maxWidth = style.maxWidth - doublePadding; let width, height = 0, lineCount = 0, lineWidths = []; //100的宽度,去掉左右两边3padding textArray.forEach(function (arrText) { let line = '', isOverMax; lineCount++; for (var n = 0; n < arrText.length; n++) { let textLine = line + arrText[n]; let metrics = ctx.measureText(textLine); let textWidth = metrics.width; if ((textWidth > maxWidth && n > 0) || arrText[n] === '\n') { line = arrText[n]; lineCount++; //有换行,记录当前换行的width isOverMax = true; } else { line = textLine; width = textWidth; } } if (isOverMax) { lineWidths.push(maxWidth); } else { lineWidths.push(width); } }, this); width = this.getCanvasWidth(lineWidths, maxWidth); height = lineCount * lineHeight; height += doublePadding; canvas.width = width; canvas.height = height; ctx.fillStyle = backgroundFill; ctx.fillRect(0, 0, width, height); return { width: width, height: height } } /** * 获取自适应的宽度(如果没有超过最大宽度,就用文字的宽度) * @param lineWidths * @param maxWidth * @returns {number} */ static getCanvasWidth(lineWidths, maxWidth) { let width = 0; for (let i = 0; i < lineWidths.length; i++) { let lineW = lineWidths[i]; if (lineW >= maxWidth) { //有任何一行超过最大高度,就用最大高度 return maxWidth + doublePadding; } else if (lineW > width) { //自己换行,就要比较每行的最大宽度 width = lineW; } } return width + doublePadding; } /** * 绘制文字,解决换行问题 * @param text * @param style * @param ctx * @param lineHeight */ static canvasTextAutoLine(text, style, ctx, lineHeight, canvasWidth) { // 字符分隔为数组 ctx.font = style.font; let textAlign = style.textAlign; let x = this.getPositionX(textAlign, canvasWidth); let arrText = text.split(''); let line = '', fillColor = style.fillColor; //每一行限制的高度 let maxWidth = style.maxWidth - doublePadding; for (var n = 0; n < arrText.length; n++) { let testLine = line + arrText[n]; let metrics = ctx.measureText(testLine); let testWidth = metrics.width; if ((testWidth > maxWidth && n > 0) || arrText[n] === '\n') { ctx.fillStyle = fillColor; ctx.textAlign = textAlign; ctx.textBaseline = "top"; ctx.fillText(line, x, this.positionY); line = arrText[n]; this.positionY += lineHeight; } else { line = testLine; } } ctx.fillStyle = fillColor; ctx.textAlign = textAlign; ctx.textBaseline = "top"; ctx.fillText(line, x, this.positionY); } /** * 得到绘制的起点位置,根据align不同,位置也不同 * @param textAlign * @returns {number} */ static getPositionX(textAlign, canvasWidth) { let x; let width = canvasWidth - doublePadding; //减去padding switch (textAlign) { case 'center': x = width / 2; break; case 'right': x = width; break; default: x = 8; break; } return x; } /** * @function StyleUtils.hexToRgb * @description 将16进制的颜色,转换成rgb格式 * @param {string} hexColor 16进制颜色 * @returns {string} rgb格式的颜色 */ static hexToRgb(hexColor) { if (!hexColor) { return; } var s = hexColor.replace('#', '').split(''); var rgb = [s[0] + s[1], s[2] + s[3], s[4] + s[5]]; rgb = rgb.map(function (hex) { return parseInt(hex, 16); }); return rgb; } /** * @function StyleUtils.formatRGB * @description 将颜色数组转换成标准的rgb颜色格式 * @param {Array} colorArray - 颜色数组 * @returns {string} 'rgb(0,0,0)'或者 'rgba(0,0,0,0)' */ static formatRGB(colorArray) { let rgb; if (colorArray.length === 3) { rgb = 'rgb('; colorArray.forEach(function (color, index) { index === 2 ? rgb += color : rgb += color + ','; }); } else { rgb = 'rgba('; colorArray.forEach(function (color, index) { index === 3 ? rgb += color : rgb += color + ','; }); } rgb += ")" return rgb; } /** * @function StyleUtils.getCanvasFromSVG * @description 将SVG转换成Canvas * @param {string} svgUrl - 颜色数组 * @param {Object} divDom - div的dom对象 * @param {function} callBack - 转换成功执行的回调函数 */ static async getCanvasFromSVG(svgUrl, divDom, callBack) { //一个图层对应一个canvas const canvgs = window.canvg && window.canvg.default ? window.canvg.default : (external_function_try_return_canvg_catch_e_return_default()); let canvas = document.createElement('canvas'); canvas.id = 'dataviz-canvas-' + core_Util_Util.newGuid(8); canvas.style.display = "none"; divDom.appendChild(canvas); try { const ctx = canvas.getContext('2d'); const v = await canvgs.from(ctx, svgUrl, { ignoreMouse: true, ignoreAnimation: true, forceRedraw: () => false }) v.start(); if (canvas.width > 300 || canvas.height > 300) { return; } callBack(canvas); } catch (e) { return; } } /** * @function StyleUtils.stopCanvg * @description 调用Canvg实例的stop(); */ static stopCanvg() { this.canvgsV.forEach(v => v.stop()); this.canvgsV = []; } /** * @function StyleUtils.getMarkerDefaultStyle 获取默认标注图层feature的样式 * @param {string} featureType feature的类型 * @param {string} server 当前地图前缀 * @returns {Object} style对象 */ static getMarkerDefaultStyle(featureType, server) { let style; switch (featureType) { case 'POINT': style = { src: `${server}apps/dataviz/static/imgs/markers/mark_red.png`, scale: 1, anchor: [0.5, 1] }; break; case 'LINE': case 'LINESTRING': case 'MULTILINESTRING': style = { strokeColor: '#3498db', strokeOpacity: 1, strokeWidth: 5, lineCap: 'round', lineDash: 'solid' }; break; case 'REGION': case 'POLYGON': case 'MULTIPOLYGON': style = { fillColor: '#1abd9c', fillOpacity: 1, strokeColor: '#3498db', strokeOpacity: 1, strokeWidth: 3, lineCap: 'round', lineDash: 'solid' }; break; } return style; } /** * @function StyleUtils.getOpenlayerStyle 获取专题图对应的openlayers格式的style * @param {string} styleParams 样式参数 * @param {string} featureType feature类型 * @param {boolean} isRank 是否为等级符号 * @returns {Promise} */ static async getOpenlayersStyle(styleParams, featureType, isRank) { let style; if (styleParams.type === "BASIC_POINT") { style = await this.toOpenLayersStyle(styleParams, featureType); } else if (styleParams.type === "SYMBOL_POINT") { style = this.getSymbolStyle(styleParams, isRank); } else if (styleParams.type === "SVG_POINT") { style = await this.getSVGStyle(styleParams); } else if (styleParams.type === 'IMAGE_POINT') { style = this.getImageStyle(styleParams); } return style; } /** * @function StyleUtils.getSymbolStyle 获取符号样式 * @param {Object} parameters - 样式参数 * @returns {Object} style对象 */ static getSymbolStyle(parameters, isRank) { let text = ''; if (parameters.unicode) { text = String.fromCharCode(parseInt(parameters.unicode.replace(/^&#x/, ''), 16)); } // 填充色 + 透明度 let fillColor = StyleUtils.hexToRgb(parameters.fillColor); fillColor.push(parameters.fillOpacity); // 边框充色 + 透明度 let strokeColor = StyleUtils.hexToRgb(parameters.strokeColor); strokeColor.push(parameters.strokeOpacity); let fontSize = isRank ? 2 * parameters.radius + "px" : parameters.fontSize; const {offsetX, offsetY, rotation=0} = parameters; const offset = StyleUtils.getTextOffset(fontSize, offsetX, offsetY); return new (external_ol_style_Style_default())({ text: new (external_ol_style_Text_default())({ text: text, font: fontSize + " supermapol-icons", placement: 'point', textAlign: 'center', fill: new (external_ol_style_Fill_default())({ color: fillColor }), backgroundFill: new (external_ol_style_Fill_default())({ color: [0, 0, 0, 0] }), stroke: new (external_ol_style_Stroke_default())({ width: parameters.strokeWidth || 0.000001, color: strokeColor }), offsetX: offset.x, offsetY: offset.y, rotation }) }); } /** * @function StyleUtils.getSVGStyle 获取svg的样式 * @param {Object} styleParams - 样式参数 * @returns {Promise} */ static async getSVGStyle(styleParams) { let style, that = this; if (!that.svgDiv) { that.svgDiv = document.createElement('div'); document.body.appendChild(that.svgDiv); } const { url, radius, offsetX, offsetY, fillOpacity, rotation } = styleParams; let anchor = this.getIconAnchor(offsetX, offsetY); await StyleUtils.getCanvasFromSVG(url, that.svgDiv, function (canvas) { style = new (external_ol_style_Style_default())({ image: new (external_ol_style_Icon_default())({ img: that.setColorToCanvas(canvas, styleParams), scale: 2 * radius / canvas.width, imgSize: [canvas.width, canvas.height], anchor: anchor || [0.5, 0.5], opacity: fillOpacity, anchorOrigin: 'bottom-right', rotation }) }); }); return style; } /** * @function StyleUtils.setColorToCanvas 将颜色,透明度等样式设置到canvas上 * @param {Object} canvas - 渲染的canvas对象 * @param {Object} parameters - 样式参数 * @returns {Object} style对象 */ static setColorToCanvas(canvas, parameters) { let context = canvas.getContext('2d'); let fillColor = StyleUtils.hexToRgb(parameters.fillColor); fillColor && fillColor.push(parameters.fillOpacity); let strokeColor = StyleUtils.hexToRgb(parameters.strokeColor); strokeColor && strokeColor.push(parameters.strokeOpacity); context.fillStyle = StyleUtils.formatRGB(fillColor); context.fill(); context.strokeStyle = StyleUtils.formatRGB(strokeColor); context.lineWidth = parameters.strokeWidth; context.stroke(); return canvas; } /** * @function StyleUtils.getImageStyle 获取图片样式 * @param {Object} styleParams - 样式参数 * @returns {Object} style对象 */ static getImageStyle(styleParams) { let size = styleParams.imageInfo.size, scale = 2 * styleParams.radius / size.w; let imageInfo = styleParams.imageInfo; let imgDom = imageInfo.img; if (!imgDom || !imgDom.src) { imgDom = new Image(); //要组装成完整的url imgDom.src = imageInfo.url; } const { offsetX, offsetY, rotation } = styleParams; let anchor = this.getIconAnchor(offsetX, offsetY); return new (external_ol_style_Style_default())({ image: new (external_ol_style_Icon_default())({ img: imgDom, scale, imgSize: [size.w, size.h], anchor: anchor || [0.5, 0.5], anchorOrigin: 'bottom-right', rotation }) }); } /** * @function StyleUtils.getRoadPath 获取道路样式 * @param {Object} style - 样式参数 * @param {Object} outlineStyle - 轮廓样式参数 * @returns {Object} style对象 */ static getRoadPath(style, outlineStyle) { const { strokeWidth=ZERO, lineCap, strokeColor, strokeOpacity } = style; // 道路线都是solid let strokeColorArray = this.hexToRgb(strokeColor); strokeColorArray && strokeColorArray.push(strokeOpacity); var stroke = new (external_ol_style_Style_default())({ stroke: new (external_ol_style_Stroke_default())({ width: strokeWidth || ZERO, color: strokeColorArray, lineCap: lineCap || 'round', lineDash: [0] }) }); const { strokeColor: outlineColor } = outlineStyle; let outlineColorArray = this.hexToRgb(outlineColor); // opacity使用style的透明度。保持两根线透明度一致 outlineColorArray && outlineColorArray.push(strokeOpacity); let outlineWidth = strokeWidth === 0 ? ZERO : strokeWidth + 2; //外部宽度=内部样式宽度 + 2 var outlineStroke = new (external_ol_style_Style_default())({ stroke: new (external_ol_style_Stroke_default())({ width: outlineWidth, //外部宽度=内部样式宽度 + 2 color: outlineColorArray, lineCap: lineCap || 'round', lineDash: [0] }) }); return [outlineStroke, stroke]; } /** * @function StyleUtils.getPathway 获取铁路样式 * @param {Object} style - 样式参数 * @param {Object} outlineStyle - 轮廓样式参数 * @returns {Object} style对象 */ static getPathway(style, outlineStyle) { let { strokeWidth=ZERO, strokeColor, strokeOpacity } = style; // 道路线都是solid, lineCap都是直角 const lineDash = (w => [w, w + strokeWidth * 2])(4 * strokeWidth), lineCap= 'square'; let strokeColorArray = this.hexToRgb(strokeColor); strokeColorArray && strokeColorArray.push(strokeOpacity); var stroke = new (external_ol_style_Style_default())({ stroke: new (external_ol_style_Stroke_default())({ width: strokeWidth*0.5 || ZERO, color: strokeColorArray, lineCap, lineDash }) }); const { strokeColor: outlineColor } = outlineStyle; let outlineColorArray = this.hexToRgb(outlineColor); // opacity使用style的透明度。保持两根线透明度一致 outlineColorArray && outlineColorArray.push(strokeOpacity); var outlineStroke = new (external_ol_style_Style_default())({ stroke: new (external_ol_style_Stroke_default())({ width: strokeWidth || ZERO, color: outlineColorArray, lineCap }) }); return [outlineStroke, stroke]; } } ;// CONCATENATED MODULE: external "ol.Map" const external_ol_Map_namespaceObject = ol.Map; var external_ol_Map_default = /*#__PURE__*/__webpack_require__.n(external_ol_Map_namespaceObject); ;// CONCATENATED MODULE: external "ol.layer.Group" const external_ol_layer_Group_namespaceObject = ol.layer.Group; var external_ol_layer_Group_default = /*#__PURE__*/__webpack_require__.n(external_ol_layer_Group_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/core/MapExtend.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @function MapExtend * @description 扩展 OpenLayers 的一些原始方法。 * @private */ var MapExtend = function () { const fun = function (layer, coordinate, resolution, callback, pixel, e) { if (layer instanceof (external_ol_layer_Group_default())) { layer.getLayers().forEach(function (subLayer) { fun(subLayer, coordinate, resolution, callback, pixel, e) }); } else { //当前高效率点图层满足筛选条件/并且可视时,可被选中: if (layer.getSource()._forEachFeatureAtCoordinate) { layer.getSource()._forEachFeatureAtCoordinate(coordinate, resolution, (feature) => { callback(feature, layer) }, pixel, e); } } } ;(external_ol_Map_default()).prototype.forEachFeatureAtPixelDefault = (external_ol_Map_default()).prototype.forEachFeatureAtPixel; ;(external_ol_Map_default()).prototype.forEachFeatureAtPixel = (external_ol_Map_default()).prototype.Tc = function (pixel, callback, opt_options, e) { //如果满足高效率图层选取要求优先返回高效率图层选中结果 const layerFilter = (opt_options && opt_options.layerFilter) ? opt_options.layerFilter : () => { return true; }; const layers = this.getLayers().getArray(); const resolution = this.getView().getResolution(); const coordinate = this.getCoordinateFromPixel(pixel); for (let i = 0; i < layers.length; i++) { const layer = layers[i]; if (layer.getVisible() && layerFilter.call(null, layer)) { fun(layer, coordinate, resolution, callback, pixel, e) } } return this.forEachFeatureAtPixelDefault(pixel, callback, opt_options); } }(); ;// CONCATENATED MODULE: ./src/openlayers/core/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: external "ol.source.TileImage" const external_ol_source_TileImage_namespaceObject = ol.source.TileImage; var external_ol_source_TileImage_default = /*#__PURE__*/__webpack_require__.n(external_ol_source_TileImage_namespaceObject); ;// CONCATENATED MODULE: external "ol.asserts" const external_ol_asserts_namespaceObject = ol.asserts; ;// CONCATENATED MODULE: external "ol.tilegrid.TileGrid" const external_ol_tilegrid_TileGrid_namespaceObject = ol.tilegrid.TileGrid; var external_ol_tilegrid_TileGrid_default = /*#__PURE__*/__webpack_require__.n(external_ol_tilegrid_TileGrid_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/mapping/BaiduMap.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class BaiduMap * @browsernamespace ol.source * @category ThirdPartyMap * @classdesc 百度地图图层源。 * @param {Object} opt_options - 参数。 * @param {string} [opt_options.url='http://online1.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles={styles}&udt=20170408'] - 服务地址。 * @param {string} [opt_options.tileProxy] - 代理地址。 * @param {boolean} [hidpi = false] - 是否使用高分辨率地图。 * @extends {ol.source.TileImage} * @usage */ class BaiduMap extends (external_ol_source_TileImage_default()) { constructor(opt_options) { var options = opt_options || {}; var attributions = options.attributions || "Map Data © 2018 Baidu - GS(2016)2089号 - Data © 长地万方 with © SuperMap iClient"; var tileGrid = BaiduMap.defaultTileGrid(); var crossOrigin = options.crossOrigin !== undefined ? options.crossOrigin : 'anonymous'; var url = options.url !== undefined ? options.url : 'http://online1.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles={styles}&udt=20170408'; var hidpi = options.hidpi || (window.devicePixelRatio || window.screen.deviceXDPI / window.screen.logicalXDPI) > 1; url = url.replace('{styles}', hidpi ? 'ph' : 'pl'); super({ attributions: attributions, cacheSize: options.cacheSize, crossOrigin: crossOrigin, opaque: options.opaque !== undefined ? options.opaque : true, maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19, reprojectionErrorThreshold: options.reprojectionErrorThreshold, tileLoadFunction: options.tileLoadFunction, projection: 'EPSG:3857', wrapX: options.wrapX, tilePixelRatio: hidpi ? 2 : 1, tileGrid: tileGrid, tileUrlFunction: tileUrlFunction }); if (options.tileProxy) { this.tileProxy = options.tileProxy; } var me = this; // eslint-disable-next-line no-unused-vars function tileUrlFunction(tileCoord, pixelRatio, projection) { var tempUrl = url .replace('{z}', tileCoord[0].toString()) .replace('{x}', tileCoord[1].toString()) .replace('{y}', function() { console.log(core_Util_Util.getOlVersion()); var y = ['4', '5'].indexOf(core_Util_Util.getOlVersion()) > -1 ? tileCoord[2] : -tileCoord[2] - 1; return y.toString(); }) .replace('{-y}', function() { var z = tileCoord[0]; var range = tileGrid.getFullTileRange(z); external_ol_asserts_namespaceObject.assert(range, 55); // The {-y} placeholder requires a tile grid with extent var y = range.getHeight() + tileCoord[2]; return y.toString(); }); //支持代理 if (me.tileProxy) { tempUrl = me.tileProxy + encodeURIComponent(tempUrl); } return tempUrl; } } // TODO 确认这个方法是否要开出去 /** * @function BaiduMap.defaultTileGrid * @description 获取默认瓦片格网。 * @returns {ol.tilegrid.TileGrid} 返回瓦片格网对象。 */ static defaultTileGrid() { var tileGird = new (external_ol_tilegrid_TileGrid_default())({ extent: [-33554432, -33554432, 33554432, 33554432], resolutions: [ 131072 * 2, 131072, 65536, 32768, 16284, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5 ], origin: [0, 0], minZoom: 3 }); return tileGird; } } ;// CONCATENATED MODULE: external "ol.source.Image" const external_ol_source_Image_namespaceObject = ol.source.Image; var external_ol_source_Image_default = /*#__PURE__*/__webpack_require__.n(external_ol_source_Image_namespaceObject); ;// CONCATENATED MODULE: external "ol.Image" const external_ol_Image_namespaceObject = ol.Image; var external_ol_Image_default = /*#__PURE__*/__webpack_require__.n(external_ol_Image_namespaceObject); ;// CONCATENATED MODULE: external "ol.format.GeoJSON" const external_ol_format_GeoJSON_namespaceObject = ol.format.GeoJSON; var external_ol_format_GeoJSON_default = /*#__PURE__*/__webpack_require__.n(external_ol_format_GeoJSON_namespaceObject); ;// CONCATENATED MODULE: external "ol.extent" const external_ol_extent_namespaceObject = ol.extent; ;// CONCATENATED MODULE: ./src/openlayers/mapping/ImageSuperMapRest.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageSuperMapRest * @browsernamespace ol.source * @category iServer Map Tile * @classdesc SuperMap iServer Image 图层源。 * @param {Object} options - 参数。 * @param {string} options.url - 地图服务地址,例如: http://{ip}:{port}/iserver/services/map-world/rest/maps/World。 * @param {ServerType} [options.serverType=SuperMap.ServerType.ISERVER] - 服务类型 ISERVER|IPORTAL|ONLINE。 * @param {boolean} [options.redirect=false] - 是否重定向。 * @param {boolean} [options.transparent=true] - 瓦片是否透明。 * @param {boolean} [options.antialias=false] - 是否反走样地图。 * @param {boolean} [options.cacheEnabled=true] - 是否使用服务端的缓存,true 表示使用服务端的缓存。 * @param {Object} [options.prjCoordSys] - 请求的地图的坐标参考系统。当此参数设置的坐标系统不同于地图的原有坐标系统时,系统会进行动态投影,并返回动态投影后的地图瓦片。例如:{"epsgCode":3857}。 * @param {string} [options.layersID] - 获取进行切片的地图图层 ID,即指定进行地图切片的图层,可以是临时图层集,也可以是当前地图中图层的组合。 * @param {boolean} [options.clipRegionEnabled = false] - 是否地图只显示该区域覆盖的部分。true 表示地图只显示该区域覆盖的部分。 * @param {ol.geom.Geometry} [options.clipRegion] - 地图显示裁剪的区域。是一个面对象,当 clipRegionEnabled = true 时有效,即地图只显示该区域覆盖的部分。 * @param {boolean} [options.overlapDisplayed=false] - 地图对象在同一范围内时,是否重叠显示。如果为 true,则同一范围内的对象会直接压盖;如果为 false 则通过 overlapDisplayedOptions 控制对象不压盖显示。 * @param {OverlapDisplayedOptions} [options.overlapDisplayedOptions] - 避免地图对象压盖显示的过滤选项,当 overlapDisplayed 为 false 时有效,用来增强对地图对象压盖时的处理。 * @param {boolean} [options.markerAngleFixed=false] - 指定点状符号的角度是否固定。 * @param {boolean} [options.textAngleFixed=false] - 文本角度是否固定。 * @param {boolean} [options.textOrientationFixed=false] - 文本朝向是否固定。 * @param {boolean} [options.paintBackground=false] - 是否绘制地图背景。 * @param {boolean} [options.maxVisibleTextSize] - 文本的最大可见尺寸,单位为像素。 * @param {boolean} [options.maxVisibleVertex] - 最大几何对象可见节点数。如果几何对象的节点数超过指定的个数,则超过的那部分节点不显示。 * @param {boolean} [options.minVisibleTextSize] - 文本的最小可见尺寸,单位为像素。 * @param {string} [options.tileversion] - 切片版本名称,_cache 为 true 时有效。 * @param {string} [options.tileProxy] - 代理地址。 * @param {NDVIParameter|HillshadeParameter} [options.rasterfunction] - 栅格分析参数。 * @param {string} [options.format = 'png'] - 瓦片表述类型,支持 "png" 、"webp"、"bmp" 、"jpg"、"gif" 等图片类型。 * @param {Function} [options.imageLoadFunction] - 加载图片的方法。默认为function(imageTile, src) {imageTile.getImage().src = src;}; * @param {string} [options.ratio=1.5] - 请求图片大小比例。 1 表示请求图片大小和地图视窗范围一致,2 表示请求图片大小是地图视窗范围的2倍,以此类推。 * @extends {ol.source.Image} * @usage */ class ImageSuperMapRest extends (external_ol_source_Image_default()) { constructor(options) { super({ attributions: options.attributions, imageSmoothing: options.imageSmoothing, projection: options.projection, resolutions: options.resolutions }); if (options.url === undefined) { return; } this.imageLoadFunction_ = options.imageLoadFunction !== undefined ? options.imageLoadFunction : external_ol_source_Image_namespaceObject.defaultImageLoadFunction; this._image = null; this.renderedRevision_ = 0; this._crossOrigin = options.crossOrigin !== undefined ? options.crossOrigin : null; this._url = options.url; this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5; options.attributions = options.attributions || "Map Data © SuperMap iServer with © SuperMap iClient"; options.format = options.format ? options.format : 'png'; this._layerUrl = Util.urlPathAppend(options.url, 'image.' + options.format); //为url添加安全认证信息片段 this._layerUrl = SecurityManager.appendCredential(this._layerUrl); const params = {}; //切片是否透明 const transparent = options.transparent !== undefined ? options.transparent : true; params['transparent'] = transparent; //是否使用缓存吗,默认为true const cacheEnabled = options.cacheEnabled !== undefined ? options.cacheEnabled : true; params['cacheEnabled'] = cacheEnabled; //如果有layersID,则是在使用专题图 if (options.layersID !== undefined) { params['layersID'] = options.layersID; } //是否重定向,默认为false let redirect = false; if (options.redirect !== undefined) { redirect = options.redirect; } params['redirect'] = redirect; if (options.prjCoordSys) { params['prjCoordSys'] = JSON.stringify(options.prjCoordSys); } if (options.clipRegionEnabled && options.clipRegion instanceof (external_ol_geom_Geometry_default())) { options.clipRegion = core_Util_Util.toSuperMapGeometry(new (external_ol_format_GeoJSON_default())().writeGeometryObject(options.clipRegion)); options.clipRegion = Util.toJSON(ServerGeometry.fromGeometry(options.clipRegion)); params['clipRegionEnabled'] = options.clipRegionEnabled; params['clipRegion'] = JSON.stringify(options.clipRegion); } if (!!options.overlapDisplayed && options.overlapDisplayedOptions) { // options.overlapDisplayedOptions = options.overlapDisplayedOptions; params['overlapDisplayed'] = options.overlapDisplayed; params['overlapDisplayedOptions'] = options.overlapDisplayedOptions.toString(); } if (cacheEnabled === true && options.tileversion) { params['tileversion'] = options.tileversion; } if (options.rasterfunction) { params['rasterfunction'] = JSON.stringify(options.rasterfunction); } //是否反走样地图,默认为false if (options.antialias !== undefined) { params['antialias'] = options.antialias; } if (options.markerAngleFixed !== undefined) { params['markerAngleFixed'] = options.markerAngleFixed; } if (options.textAngleFixed !== undefined) { params['textAngleFixed'] = options.textAngleFixed; } if (options.textOrientationFixed !== undefined) { params['textOrientationFixed'] = options.textOrientationFixed; } if (options.paintBackground !== undefined) { params['paintBackground'] = options.paintBackground; } if (!isNaN(options.maxVisibleTextSize)) { params['maxVisibleTextSize'] = +options.maxVisibleTextSize; } if (!isNaN(options.minVisibleTextSize)) { params['maxVisibleTextSize'] = +options.minVisibleTextSize; } if (!isNaN(options.maxVisibleVertex)) { params['maxVisibleVertex'] = Math.round(+options.maxVisibleVertex); } this._layerUrl = Util.urlAppend(this._layerUrl, Util.getParameterString(params)); //存储一个cacheEnabled this.cacheEnabled = cacheEnabled; if (options.tileProxy) { this.tileProxy = options.tileProxy; } } getImageInternal(extent, resolution, pixelRatio) { resolution = this.findNearestResolution(resolution); const imageResolution = resolution / pixelRatio; const center = (0,external_ol_extent_namespaceObject.getCenter)(extent); const viewWidth = Math.ceil((0,external_ol_extent_namespaceObject.getWidth)(extent) / imageResolution); const viewHeight = Math.ceil((0,external_ol_extent_namespaceObject.getHeight)(extent) / imageResolution); const viewExtent = (0,external_ol_extent_namespaceObject.getForViewAndSize)(center, imageResolution, 0, [viewWidth, viewHeight]); const requestWidth = Math.ceil((this.ratio_ * (0,external_ol_extent_namespaceObject.getWidth)(extent)) / imageResolution); const requestHeight = Math.ceil((this.ratio_ * (0,external_ol_extent_namespaceObject.getHeight)(extent)) / imageResolution); const requestExtent = (0,external_ol_extent_namespaceObject.getForViewAndSize)(center, imageResolution, 0, [requestWidth, requestHeight]); const image = this._image; if ( image && this.renderedRevision_ === this.getRevision() && image.getResolution() === resolution && image.getPixelRatio() === pixelRatio && (0,external_ol_extent_namespaceObject.containsExtent)(image.getExtent(), viewExtent) ) { return image; } const imageSize = [ Math.round((0,external_ol_extent_namespaceObject.getWidth)(requestExtent) / imageResolution), Math.round((0,external_ol_extent_namespaceObject.getHeight)(requestExtent) / imageResolution) ]; const imageUrl = this._getRequestUrl(requestExtent, imageSize); this._image = new (external_ol_Image_default())( requestExtent, resolution, pixelRatio, imageUrl, this._crossOrigin, this.imageLoadFunction_ ); this.renderedRevision_ = this.getRevision(); this._image.addEventListener('change', this.handleImageChange.bind(this)); return this._image; } _getRequestUrl(extent, imageSize) { const params = { width: imageSize[0], height: imageSize[1], viewBounds: { leftBottom: { x: extent[0], y: extent[1] }, rightTop: { x: extent[2], y: extent[3] } } }; //不启用缓存时启用时间戳 if (!this.cacheEnabled) { params['_t'] = new Date().getTime(); } let imageUrl = Util.urlAppend(this._layerUrl, Util.getParameterString(params)); //支持代理 if (this.tileProxy) { imageUrl = this.tileProxy + encodeURIComponent(imageUrl); } return imageUrl; } /** * @function ImageSuperMapRest.optionsFromMapJSON * @param {string} url - 地址。 * @param {Object} mapJSONObj - 地图 JSON。 * @description 获取地图 JSON 信息。 */ static optionsFromMapJSON(url, mapJSONObj) { var extent = [mapJSONObj.bounds.left, mapJSONObj.bounds.bottom, mapJSONObj.bounds.right, mapJSONObj.bounds.top]; var resolutions = getResolutions(); function getResolutions() { var level = 28; var dpi = 96; var width = extent[2] - extent[0]; var height = extent[3] - extent[1]; var tileSize = width >= height ? width : height; var maxReolution; if (tileSize === width) { maxReolution = tileSize / mapJSONObj.viewer.width; } else { maxReolution = tileSize / mapJSONObj.viewer.height; } var resolutions = []; var unit = Unit.METER; if (mapJSONObj.coordUnit === Unit.DEGREE) { unit = Unit.DEGREE; } if (mapJSONObj.visibleScales.length > 0) { for (let i = 0; i < mapJSONObj.visibleScales.length; i++) { resolutions.push(core_Util_Util.scaleToResolution(mapJSONObj.visibleScales[i], dpi, unit)); } } else { for (let i = 0; i < level; i++) { resolutions.push(maxReolution / Math.pow(2, i)); } } function sortNumber(a, b) { return b - a; } return resolutions.sort(sortNumber); } return { url,resolutions }; } } ;// CONCATENATED MODULE: external "ol.source.XYZ" const external_ol_source_XYZ_namespaceObject = ol.source.XYZ; var external_ol_source_XYZ_default = /*#__PURE__*/__webpack_require__.n(external_ol_source_XYZ_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/mapping/SuperMapCloud.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SuperMapCloud * @browsernamespace ol.source * @category ThirdPartyMap * @classdesc 超图云地图图层源。 * @param {Object} opt_options - 参数。 * @param {string} [opt_options.url='http://t2.dituhui.com/FileService/image?map={mapName}&type={type}&x={x}&y={y}&z={z}'] - 服务地址。 * @param {string} [opt_options.tileProxy] - 代理地址。 * @extends {ol.source.XYZ} * @usage */ class SuperMapCloud extends (external_ol_source_XYZ_default()) { constructor(opt_options) { var options = opt_options || {}; var attributions = options.attributions || "Map Data ©2014 SuperMap - GS(2014)6070号-data©Navinfo with © SuperMap iClient" var mapName = options.mapName || 'quanguo'; var mapType = options.mapType || 'web'; var url = options.url || 'http://t2.dituhui.com/FileService/image?map={mapName}&type={type}&x={x}&y={y}&z={z}'; url = url.replace('{mapName}', mapName).replace('{type}', mapType); var superOptions = { attributions: attributions, cacheSize: options.cacheSize, crossOrigin: options.crossOrigin, opaque: options.opaque === undefined ? true : options.opaque, maxZoom: options.maxZoom || 18, reprojectionErrorThreshold: options.reprojectionErrorThreshold, url: url, wrapX: options.wrapX }; //需要代理时走自定义 tileLoadFunction,否则走默认的tileLoadFunction if (options.tileProxy) { superOptions.tileLoadFunction = tileLoadFunction; } super(superOptions); if (options.tileProxy) { this.tileProxy = options.tileProxy; } //需要代理时,走以下代码 var me = this; function tileLoadFunction(imageTile, src) { //支持代理 imageTile.getImage().src = me.tileProxy + encodeURIComponent(src); } } } ;// CONCATENATED MODULE: external "ol.source.WMTS" const external_ol_source_WMTS_namespaceObject = ol.source.WMTS; var external_ol_source_WMTS_default = /*#__PURE__*/__webpack_require__.n(external_ol_source_WMTS_namespaceObject); ;// CONCATENATED MODULE: external "ol.tilegrid.WMTS" const external_ol_tilegrid_WMTS_namespaceObject = ol.tilegrid.WMTS; var external_ol_tilegrid_WMTS_default = /*#__PURE__*/__webpack_require__.n(external_ol_tilegrid_WMTS_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/mapping/Tianditu.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Tianditu * @browsernamespace ol.source * @category ThirdPartyMap * @classdesc 天地图图层源。 * @param {Object} opt_options - 参数。 * @param {string} [opt_options.url='http://t{0-7}.tianditu.gov.cn/{layer}_{proj}/wmts?'] - 服务地址。 * @param {string} opt_options.key - 天地图服务密钥。详见{@link http://lbs.tianditu.gov.cn/server/MapService.html} * @param {string} [opt_options.layerType='vec'] - 图层类型。(vec:矢量图层,img:影像图层,ter:地形图层) * @param {string} [opt_options.attributions] - 版权描述信息。 * @param {number} [opt_options.cacheSize = 2048] - 缓冲大小。 * @param {function} [opt_options.tileLoadFunction] - 切片加载完成后执行函数。 * @param {string} [opt_options.style] - 图层风格。 * @param {string} [opt_options.format='tiles'] - 格式。 * @param {boolean} [opt_options.isLabel] - 是否是标注图层。 * @param {boolean} [opt_options.opaque=true] - 是否透明。 * @param {string} [opt_options.tileProxy] - 代理地址。 * @extends {ol.source.WMTS} * @usage */ class Tianditu extends (external_ol_source_WMTS_default()) { constructor(opt_options) { var layerLabelMap = { "vec": "cva", "ter": "cta", "img": "cia" } var layerZoomMap = { "vec": 18, "ter": 14, "img": 18 } var options = opt_options || {}; var attributions = options.attributions || "Map Data with " + "© SuperMap iClient" options.layerType = options.layerType || "vec"; options.layerType = options.isLabel ? layerLabelMap[options.layerType] : options.layerType; options.matrixSet = (options.projection === 'EPSG:4326' || options.projection === 'EPSG:4490') ? "c" : "w"; if (!options.url && !options.urls) { options.url = "http://t{0-7}.tianditu.gov.cn/{layer}_{proj}/wmts?" } if (options.key) { options.url = `${options.url}tk=${options.key}`; } options.url = options.url.replace("{layer}", options.layerType).replace("{proj}", options.matrixSet); var tileGrid = options.tileGrid || Tianditu.getTileGrid(options.projection || 'EPSG:3857'); var crossOrigin = options.crossOrigin !== undefined ? options.crossOrigin : 'anonymous'; var superOptions = { version: options.version || '1.0.0', format: options.format || 'tiles', dimensions: options.dimensions || {}, layer: options.layerType, matrixSet: options.matrixSet, tileGrid: tileGrid, style: options.style || 'default', attributions: attributions, cacheSize: options.cacheSize, crossOrigin: crossOrigin, opaque: options.opaque === undefined ? true : options.opaque, maxZoom: layerZoomMap[options.layerType], reprojectionErrorThreshold: options.reprojectionErrorThreshold, url: options.url, urls: options.urls, projection: options.projection || 'EPSG:3857', wrapX: options.wrapX }; //需要代理时走自定义 tileLoadFunction,否则走默认的tileLoadFunction if (options.tileProxy) { superOptions.tileLoadFunction = tileLoadFunction; } super(superOptions); if (options.tileProxy) { this.tileProxy = options.tileProxy; } //需要代理时,走以下代码 var me = this; function tileLoadFunction(imageTile, src) { //支持代理 imageTile.getImage().src = me.tileProxy + encodeURIComponent(src); } } /** * @function Tianditu.getTileGrid * @description 获取瓦片网格。 * @param {string} projection - 投影参考对象。 * @returns {ol.tilegrid.WMTS} 返回瓦片网格对象。 */ static getTileGrid(projection) { if (projection === "EPSG:4326" || projection === "EPSG:4490") { return Tianditu.default4326TileGrid(); } return Tianditu.default3857TileGrid(); } /** * @function Tianditu.default4326TileGrid * @description 获取默认 4326 网格瓦片。 * @returns {ol.tilegrid.WMTS} 返回默认 4326 网格瓦片对象。 */ static default4326TileGrid() { var tdt_WGS84_resolutions = []; var matrixIds = []; for (var i = 1; i < 19; i++) { tdt_WGS84_resolutions.push(0.703125 * 2 / (Math.pow(2, i))); matrixIds.push(i); } var tileGird = new (external_ol_tilegrid_WMTS_default())({ extent: [-180, -90, 180, 90], resolutions: tdt_WGS84_resolutions, origin: [-180, 90], matrixIds: matrixIds, minZoom: 1 }); return tileGird; } /** * @function Tianditu.default3857TileGrid * @description 获取默认 3857 网格瓦片。 * @returns {ol.tilegrid.WMTS} 返回默认 3857 网格瓦片对象。 */ static default3857TileGrid() { var tdt_Mercator_resolutions = []; var matrixIds = []; for (var i = 1; i < 19; i++) { tdt_Mercator_resolutions.push(78271.5169640203125 * 2 / (Math.pow(2, i))); matrixIds.push(i); } var tileGird = new (external_ol_tilegrid_WMTS_default())({ extent: [-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892], resolutions: tdt_Mercator_resolutions, matrixIds: matrixIds, origin: [-20037508.3427892, 20037508.3427892], minZoom: 1 }); return tileGird; } } ;// CONCATENATED MODULE: external "ol.size" const external_ol_size_namespaceObject = ol.size; ;// CONCATENATED MODULE: external "ol.tilegrid" const external_ol_tilegrid_namespaceObject = ol.tilegrid; ;// CONCATENATED MODULE: ./src/openlayers/mapping/TileSuperMapRest.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TileSuperMapRest * @browsernamespace ol.source * @category iServer Map Tile * @classdesc SuperMap iServer TileImage 图层源。 * @param {Object} options - 参数。 * @param {string} options.url - 服务地址,例如: http://{ip}:{port}/iserver/services/map-world/rest/maps/World。 * @param {ol.tilegrid.TileGrid} [options.tileGrid] - 瓦片网格对象。当不指定时,会通过 options.extent 或投影范围生成。 * @param {boolean} [options.redirect = false] - 是否重定向。 * @param {boolean} [options.transparent = true] - 瓦片是否透明。 * @param {boolean} [options.cacheEnabled = true] - 是否使用服务端的缓存。 * @param {Object} [options.prjCoordSys] - 请求的地图的坐标参考系统。当此参数设置的坐标系统不同于地图的原有坐标系统时,系统会进行动态投影,并返回动态投影后的地图瓦片。例如:{"epsgCode":3857}。 * @param {string} [options.layersID] - 获取进行切片的地图图层 ID,即指定进行地图切片的图层,可以是临时图层集,也可以是当前地图中图层的组合。 * @param {boolean} [options.clipRegionEnabled = false] - 是否只地图只显示该区域覆盖的部分。true 表示地图只显示该区域覆盖的部分。 * @param {ol.geom.Geometry} [options.clipRegion] - 地图显示裁剪的区域。是一个面对象,当 clipRegionEnabled = true 时有效,即地图只显示该区域覆盖的部分。 * @param {boolean} [options.overlapDisplayed = false] - 地图对象在同一范围内时,是否重叠显示。如果为 true,则同一范围内的对象会直接压盖;如果为 false 则通过 overlapDisplayedOptions 控制对象不压盖显示。 * @param {OverlapDisplayedOptions} [options.overlapDisplayedOptions] - 避免地图对象压盖显示的过滤选项,当 overlapDisplayed 为 false 时有效,用来增强对地图对象压盖时的处理。 * @param {string} [options.tileversion] - 切片版本名称,_cache 为 true 时有效。 * @param {string} [options.tileProxy] - 服务代理地址。 * @param {string} [options.format = 'png'] - 瓦片表述类型,支持 "png" 、"webp"、"bmp" 、"jpg"、"gif" 等图片类型。 * @param {(NDVIParameter|HillshadeParameter)} [options.rasterfunction] - 栅格分析参数。 * @extends {ol.source.TileImage} * @usage */ class TileSuperMapRest extends (external_ol_source_TileImage_default()) { constructor(options) { options = options || {}; options.attributions = options.attributions || "Map Data © SuperMap iServer with © SuperMap iClient"; options.format = options.format ? options.format : 'png'; super({ attributions: options.attributions, cacheSize: options.cacheSize, crossOrigin: options.crossOrigin, logo: core_Util_Util.getOlVersion() === '4' ? options.logo : null, opaque: options.opaque, projection: options.projection, reprojectionErrorThreshold: options.reprojectionErrorThreshold, state: options.state, tileClass: options.tileClass, tileGrid: options.tileGrid, tileLoadFunction: options.tileLoadFunction, tilePixelRatio: options.tilePixelRatio, tileUrlFunction: tileUrlFunction, wrapX: options.wrapX !== undefined ? options.wrapX : false, cacheEnabled: options.cacheEnabled, layersID: options.layersID }); if (options.tileProxy) { this.tileProxy = options.tileProxy; } this.options = options; this._url = options.url; //当前切片在切片集中的index this.tileSetsIndex = -1; this.tempIndex = -1; this.dpi = this.options.dpi || 96; var me = this; var layerUrl = Util.urlPathAppend(options.url, 'tileImage.' + options.format); /** * @function TileSuperMapRest.prototype.getAllRequestParams * @description 获取全部请求参数。 */ function getAllRequestParams() { var me = this, params = {}; params['redirect'] = options.redirect !== undefined ? options.redirect : false; //切片是否透明 params['transparent'] = options.transparent !== undefined ? options.transparent : true; params['cacheEnabled'] = !(options.cacheEnabled === false); //存储一个cacheEnabled参数 me.cacheEnabled = params['cacheEnabled']; params['_cache'] = params['cacheEnabled']; //设置切片原点 if (this.origin) { params['origin'] = JSON.stringify({ x: this.origin[0], y: this.origin[1] }); } if (options.prjCoordSys) { params['prjCoordSys'] = JSON.stringify(options.prjCoordSys); } if (options.layersID) { params['layersID'] = options.layersID.toString(); } if (options.clipRegion instanceof (external_ol_geom_Geometry_default())) { options.clipRegionEnabled = true; options.clipRegion = core_Util_Util.toSuperMapGeometry(new (external_ol_format_GeoJSON_default())().writeGeometryObject(options.clipRegion)); options.clipRegion = Util.toJSON(ServerGeometry.fromGeometry(options.clipRegion)); params['clipRegionEnabled'] = options.clipRegionEnabled; params['clipRegion'] = JSON.stringify(options.clipRegion); } if (!options.overlapDisplayed) { params['overlapDisplayed'] = false; if (options.overlapDisplayedOptions) { params['overlapDisplayedOptions'] = me.overlapDisplayedOptions.toString(); } } else { params['overlapDisplayed'] = true; } if (params.cacheEnabled && options.tileversion) { params['tileversion'] = options.tileversion.toString(); } if (options.rasterfunction) { params['rasterfunction'] = JSON.stringify(options.rasterfunction); } return params; } /** * @function TileSuperMapRest.prototype.getFullRequestUrl * @description 获取完整的请求地址。 */ function getFullRequestUrl() { if (this._paramsChanged) { this._layerUrl = createLayerUrl.call(this); this._paramsChanged = false; } return this._layerUrl || createLayerUrl.call(this); } /** * @function TileSuperMapRest.prototype.createLayerUrl * @description 获取新建图层地址。 */ function createLayerUrl() { this.requestParams = this.requestParams || getAllRequestParams.call(this); this._layerUrl = Util.urlAppend(layerUrl, Util.getParameterString(this.requestParams)); //为url添加安全认证信息片段 this._layerUrl = SecurityManager.appendCredential(this._layerUrl); return this._layerUrl; } function tileUrlFunction(tileCoord, pixelRatio, projection) { if (!me.tileGrid) { if (options.extent) { me.tileGrid = TileSuperMapRest.createTileGrid(options.extent); if (me.resolutions) { me.tileGrid.resolutions = me.resolutions; } } else { if (projection.getCode() === 'EPSG:3857') { me.tileGrid = TileSuperMapRest.createTileGrid([ -20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892 ]); me.extent = [-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892]; } if (projection.getCode() === 'EPSG:4326') { me.tileGrid = TileSuperMapRest.createTileGrid([-180, -90, 180, 90]); me.extent = [-180, -90, 180, 90]; } } } me.origin = me.tileGrid.getOrigin(0); var z = tileCoord[0]; var x = tileCoord[1]; var y = ['4', '5'].indexOf(core_Util_Util.getOlVersion()) > -1 ? -tileCoord[2] - 1 : tileCoord[2]; var resolution = me.tileGrid.getResolution(z); var dpi = me.dpi || 96; var unit = projection.getUnits() || Unit.DEGREE; // OGC WKT 解析出单位是 degree if (unit === 'degrees' || unit === 'degree') { unit = Unit.DEGREE; } //通过wkt方式自定义坐标系的时候,是meter if (unit === 'm' || unit === 'meter') { unit = Unit.METER; } var scale = core_Util_Util.resolutionToScale(resolution, dpi, unit); var tileSize = external_ol_size_namespaceObject.toSize(me.tileGrid.getTileSize(z, me.tmpSize)); var layerUrl = getFullRequestUrl.call(me); var url = layerUrl + encodeURI( '&x=' + x + '&y=' + y + '&width=' + tileSize[0] + '&height=' + tileSize[1] + '&scale=' + scale ); //支持代理 if (me.tileProxy) { url = me.tileProxy + encodeURIComponent(url); } if (!me.cacheEnabled) { url += '&_t=' + new Date().getTime(); } return url; } } /** * @function TileSuperMapRest.prototype.setTileSetsInfo * @description 设置瓦片集信息。 * @param {Object} tileSets - 瓦片集合。 */ setTileSetsInfo(tileSets) { this.tileSets = tileSets; if (core_Util_Util.isArray(this.tileSets)) { this.tileSets = tileSets[0]; } if (!this.tileSets) { return; } this.dispatchEvent({ type: 'tilesetsinfoloaded', value: { tileVersions: this.tileSets.tileVersions } }); this.changeTilesVersion(); } /** * @function TileSuperMapRest.prototype.lastTilesVersion * @description 请求上一个版本切片,并重新绘制。 */ lastTilesVersion() { this.tempIndex = this.tileSetsIndex - 1; this.changeTilesVersion(); } /** * @function TileSuperMapRest.prototype.nextTilesVersion * @description 请求下一个版本切片,并重新绘制。 */ nextTilesVersion() { this.tempIndex = this.tileSetsIndex + 1; this.changeTilesVersion(); } /** * @function TileSuperMapRest.prototype.changeTilesVersion * @description 切换到某一版本的切片,并重绘。通过 this.tempIndex 保存需要切换的版本索引。 */ changeTilesVersion() { var me = this; //切片版本集信息是否存在 if (me.tileSets == null) { return; } if (me.tempIndex === me.tileSetsIndex || this.tempIndex < 0) { return; } //检测index是否可用 var tileVersions = me.tileSets.tileVersions; if (tileVersions && me.tempIndex < tileVersions.length && me.tempIndex >= 0) { var name = tileVersions[me.tempIndex].name; var result = me.mergeTileVersionParam(name); if (result) { me.tileSetsIndex = me.tempIndex; me.dispatchEvent({ type: 'tileversionschanged', value: { tileVersion: tileVersions[me.tempIndex] } }); } } } /** * @function TileSuperMapRest.prototype.updateCurrentTileSetsIndex * @description 更新当前切片集索引,目前主要提供给控件使用。 * @param {number} index - 索引号。 */ updateCurrentTileSetsIndex(index) { this.tempIndex = index; } /** * @function TileSuperMapRest.prototype.mergeTileVersionParam * @description 更改 URL 请求参数中的切片版本号,并重绘。 * @param {Object} version - 版本信息。 * @returns {boolean} 是否成功。 */ mergeTileVersionParam(version) { if (version) { this.requestParams['tileversion'] = version; this._paramsChanged = true; this.refresh(); return true; } return false; } /** * @function TileSuperMapRest.optionsFromMapJSON * @description 从 MapJSON 中获取参数对象。 * @param {string} url - 服务地址。 * @param {Object} mapJSONObj - 地图 JSON 对象。 */ static optionsFromMapJSON(url, mapJSONObj) { var options = {}; options.url = url; options.crossOrigin = 'anonymous'; var extent = [mapJSONObj.bounds.left, mapJSONObj.bounds.bottom, mapJSONObj.bounds.right, mapJSONObj.bounds.top]; const { visibleScales, bounds, dpi, coordUnit } = mapJSONObj; var resolutions = core_Util_Util.scalesToResolutions(visibleScales, bounds, dpi, coordUnit); options.tileGrid = new (external_ol_tilegrid_TileGrid_default())({ extent: extent, resolutions: resolutions }); return options; } /** * @function TileSuperMapRest.createTileGrid * @description 创建切片网格。 * @param {number} extent - 长度。 * @param {number} maxZoom - 最大的放大级别。 * @param {number} minZoom - 最小的放大级别。 * @param {number} tileSize - 瓦片的尺寸。 * @param {number} origin - 原点。 * */ static createTileGrid(extent, maxZoom, minZoom, tileSize, origin) { var tilegrid = external_ol_tilegrid_namespaceObject.createXYZ({ extent: extent, maxZoom: maxZoom, minZoom: minZoom, tileSize: tileSize }); return new (external_ol_tilegrid_TileGrid_default())({ extent: extent, minZoom: minZoom, origin: origin, resolutions: tilegrid.getResolutions(), tileSize: tilegrid.getTileSize() }); } } // EXTERNAL MODULE: ./node_modules/proj4/dist/proj4-src.js var proj4_src = __webpack_require__(785); var proj4_src_default = /*#__PURE__*/__webpack_require__.n(proj4_src); ;// CONCATENATED MODULE: ./src/common/util/FilterCondition.js function getParseSpecialCharacter() { // 特殊字符字典 const directory = ['(', ')', '(', ')', ',', ',']; const res = {}; directory.forEach((item, index) => { res[item] = `$${index}` }); return res; } function parseSpecialCharacter(str) { const directory = getParseSpecialCharacter(); for (let key in directory) { const replaceValue = directory[key]; const pattern = new RegExp(`\\${key}`, 'g'); // eslint-disable-next-line while (pattern.test(str)) { str = str.replace(pattern, replaceValue); } } return str; } function parseCondition(filterCondition, keys) { const str = filterCondition.replace(/&|\||>|<|=|!/g, ' '); const arr = str.split(' ').filter((item) => item); let result = filterCondition; arr.forEach((item) => { const key = keys.find((val) => val === item); if (startsWithNumber(item) && key) { result = result.replace(key, '$' + key); } if (key) { const res = parseSpecialCharacter(key); result = result.replace(key, res); } }); return result; } // 处理jsonsqlfeature, 加前缀 function parseConditionFeature(feature) { let copyValue = {}; for (let key in feature) { let copyKey = key; if (startsWithNumber(key)) { copyKey = '$' + key; } copyKey = parseSpecialCharacter(copyKey); copyValue[copyKey] = feature[key]; } return copyValue; } function startsWithNumber(str) { return /^\d/.test(str); } ;// CONCATENATED MODULE: external "ol.geom.Point" const external_ol_geom_Point_namespaceObject = ol.geom.Point; var external_ol_geom_Point_default = /*#__PURE__*/__webpack_require__.n(external_ol_geom_Point_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/services/QueryService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class QueryService * @category iServer Map QueryResults * @classdesc 地图查询服务类。 * 提供:范围查询,SQL 查询,几何查询,距离查询。 * @extends {ServiceBase} * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * new QueryService(url) * .queryByBounds(param,function(result){ * //doSomething * }) * @usage */ class QueryService_QueryService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function QueryService.prototype.queryByBounds * @description bounds 查询地图服务。 * @param {QueryByBoundsParameters} params - Bounds 查询参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 * @returns {QueryService} */ queryByBounds(params, callback, resultFormat) { var me = this; var queryService = new QueryByBoundsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); queryService.processAsync(me._processParams(params)); } /** * @function QueryService.prototype.queryByDistance * @description 地图距离查询服务。 * @param {QueryByDistanceParameters} params - Distance 查询参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ queryByDistance(params, callback, resultFormat) { var me = this; var queryByDistanceService = new QueryByDistanceService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); queryByDistanceService.processAsync(me._processParams(params)); } /** * @function QueryService.prototype.queryBySQL * @description 地图 SQL 查询服务。 * @param {QueryBySQLParameters} params - SQL 查询参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ queryBySQL(params, callback, resultFormat) { var me = this; var queryBySQLService = new QueryBySQLService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); queryBySQLService.processAsync(me._processParams(params)); } /** * @function QueryService.prototype.queryByGeometry * @description 地图几何查询服务。 * @param {QueryByGeometryParameters} params - Geometry 查询参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ queryByGeometry(params, callback, resultFormat) { var me = this; var queryByGeometryService = new QueryByGeometryService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); queryByGeometryService.processAsync(me._processParams(params)); } _processParams(params) { if (!params) { return {}; } params.returnContent = (params.returnContent == null) ? true : params.returnContent; if (params.queryParams && !core_Util_Util.isArray(params.queryParams)) { params.queryParams = [params.queryParams]; } if (params.bounds) { params.bounds = new Bounds( params.bounds[0], params.bounds[1], params.bounds[2], params.bounds[3] ); } if (params.geometry) { if (params.geometry instanceof (external_ol_geom_Point_default())) { params.geometry = new Point(params.geometry.getCoordinates()[0], params.geometry.getCoordinates()[1]); } else { params.geometry = core_Util_Util.toSuperMapGeometry(JSON.parse((new (external_ol_format_GeoJSON_default())()).writeGeometry(params.geometry))); } } return params; } _processFormat(resultFormat) { return (resultFormat) ? resultFormat : DataFormat.GEOJSON; } } ;// CONCATENATED MODULE: ./src/openlayers/services/FeatureService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FeatureService * @constructs FeatureService * @category iServer Data Feature * @classdesc 数据集类。提供:ID 查询,范围查询,SQL查询,几何查询,bounds 查询,缓冲区查询,地物编辑。 * @example * new FeatureService(url).getFeaturesByIDs(param,function(result){ * //doSomething * }) * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {ServiceBase} * @usage */ class FeatureService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function FeatureService.prototype.getFeaturesByIDs * @description 数据集 ID 查询服务。 * @param {GetFeaturesByIDsParameters} params - ID查询参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的数据格式。 */ getFeaturesByIDs(params, callback, resultFormat) { var me = this; var getFeaturesByIDsService = new GetFeaturesByIDsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); getFeaturesByIDsService.processAsync(me._processParams(params)); } /** * @function FeatureService.prototype.getFeaturesByBounds * @description 数据集 Bounds 查询服务。 * @param {GetFeaturesByBoundsParameters} params - 数据集范围查询参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的数据格式。 */ getFeaturesByBounds(params, callback, resultFormat) { var me = this; var getFeaturesByBoundsService = new GetFeaturesByBoundsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); getFeaturesByBoundsService.processAsync(me._processParams(params)); } /** * @function FeatureService.prototype.getFeaturesByBuffer * @description 数据集 Buffer 查询服务。 * @param {GetFeaturesByBufferParameters} params - 数据集缓冲区查询参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的数据格式。 */ getFeaturesByBuffer(params, callback, resultFormat) { var me = this; var getFeatureService = new GetFeaturesByBufferService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); getFeatureService.processAsync(me._processParams(params)); } /** * @function FeatureService.prototype.getFeaturesBySQL * @description 数据集 SQL 查询服务。 * @param {GetFeaturesBySQLParameters} params - 数据集 SQL 查询参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的数据格式。 */ getFeaturesBySQL(params, callback, resultFormat) { var me = this; var getFeatureBySQLService = new GetFeaturesBySQLService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); getFeatureBySQLService.processAsync(me._processParams(params)); } /** * @function FeatureService.prototype.getFeaturesByGeometry * @description 数据集几何查询服务类。 * @param {GetFeaturesByGeometryParameters} params - 数据集几何查询参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的数据格式。 */ getFeaturesByGeometry(params, callback, resultFormat) { var me = this; var getFeaturesByGeometryService = new GetFeaturesByGeometryService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); getFeaturesByGeometryService.processAsync(me._processParams(params)); } /** * @function FeatureService.prototype.editFeatures * @description 地物编辑服务。 * @param {EditFeaturesParameters} params - 数据服务中数据集添加、修改、删除参数类。 * @param {RequestCallback} callback - 回调函数。 */ editFeatures(params, callback) { if (!params || !params.dataSourceName || !params.dataSetName) { return; } var me = this, url = me.url, dataSourceName = params.dataSourceName, dataSetName = params.dataSetName; url = Util.urlPathAppend(url, "datasources/" + dataSourceName + "/datasets/" + dataSetName); var editFeatureService = new EditFeaturesService(url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback } }); editFeatureService.processAsync(me._processParams(params)); } _processParams(params) { if (!params) { return {}; } var me = this; params.returnContent = (params.returnContent == null) ? true : params.returnContent; params.fromIndex = params.fromIndex ? params.fromIndex : 0; params.toIndex = params.toIndex ? params.toIndex : -1; if (params.bounds) { params.bounds = core_Util_Util.toSuperMapBounds(params.bounds); } if (params.geometry) { params.geometry = core_Util_Util.toSuperMapGeometry(JSON.parse((new (external_ol_format_GeoJSON_default())()).writeGeometry(params.geometry))); } if (params.editType) { params.editType = params.editType.toLowerCase(); } if (params.features) { var features = []; if (core_Util_Util.isArray(params.features)) { params.features.map(function (feature) { features.push(me._createServerFeature(feature)); return feature; }); } else { features.push(me._createServerFeature(params.features)); } params.features = features; } return params; } _createServerFeature(geoFeature) { var feature = {}, fieldNames = [], fieldValues = []; var properties = geoFeature.getProperties(); for (var key in properties) { if (key === geoFeature.getGeometryName()) { continue; } fieldNames.push(key); fieldValues.push(properties[key]); } feature.fieldNames = fieldNames; feature.fieldValues = fieldValues; if (geoFeature.getId()) { feature.id = geoFeature.getId(); } feature.geometry = core_Util_Util.toSuperMapGeometry((new (external_ol_format_GeoJSON_default())()).writeFeatureObject(geoFeature)); return feature; } _processFormat(resultFormat) { return (resultFormat) ? resultFormat : DataFormat.GEOJSON; } } ;// CONCATENATED MODULE: ./src/openlayers/mapping/webmap/Util.js function getFeatureProperties(features) { let properties = []; if (Util_isArray(features) && features.length) { features.forEach((feature) => { let property = feature.get('attributes'); property && properties.push(property); }); } return properties; } function getFeatureBySQL(url, datasetNames, serviceOptions, processCompleted, processFaild, targetEpsgCode, restDataSingleRequestCount) { getFeatureBySQLWithConcurrent(url, datasetNames, processCompleted, processFaild, serviceOptions, targetEpsgCode, restDataSingleRequestCount); } function queryFeatureBySQL( url, layerName, attributeFilter, fields, epsgCode, processCompleted, processFaild, startRecord, recordLength, onlyAttribute ) { const queryParam = new FilterParameter({ name: layerName, attributeFilter: attributeFilter }); if (fields) { queryParam.fields = fields; } const params = { queryParams: [queryParam] }; if (onlyAttribute) { params.queryOption = QueryOption.ATTRIBUTE; } startRecord && (params.startRecord = startRecord); recordLength && (params.expectCount = recordLength); if (epsgCode) { params.prjCoordSys = { epsgCode: epsgCode }; } const queryBySQLParams = new QueryBySQLParameters(params); const queryBySQLService = new QueryService_QueryService(url); queryBySQLService.queryBySQL(queryBySQLParams, function (data) { data.type === 'processCompleted' ? processCompleted(data) : processFaild(data); }); } function getFeatureBySQLWithConcurrent( url, datasetNames, processCompleted, processFailed, serviceOptions, targetEpsgCode, restDataSingleRequestCount ) { let queryParameter = new FilterParameter({ name: datasetNames.join().replace(':', '@') }); let maxFeatures = restDataSingleRequestCount || 1000, // 每次请求数据量 firstResult, // 存储每次请求的结果 allRequest = []; // 存储发出的请求Promise // 发送请求获取获取总数据量 _getReasult(url, queryParameter, datasetNames, 0, 1, 1, serviceOptions, targetEpsgCode) .then((result) => { firstResult = result; let totalCount = result.result.totalCount; if (totalCount > 1) { // 开始并发请求 for (let i = 1; i < totalCount; ) { allRequest.push( _getReasult( url, queryParameter, datasetNames, i, i + maxFeatures, maxFeatures, serviceOptions, targetEpsgCode ) ); i += maxFeatures; } // 所有请求结束 Promise.all(allRequest) .then((results) => { // 结果合并 results.forEach((result) => { if (result.type === 'processCompleted' && result.result.features && result.result.features.features) { result.result.features.features.forEach((feature) => { firstResult.result.features.features.push(feature); }); } else { // todo 提示 部分数据请求失败 firstResult.someRequestFailed = true; } }); processCompleted(firstResult); }) .catch((error) => { processFailed(error); }); } else { processCompleted(result); } }) .catch((error) => { processFailed(error); }); } function _getFeaturesBySQLParameters( queryParameter, datasetNames, fromIndex, toIndex, maxFeatures, targetEpsgCode ) { return new GetFeaturesBySQLParameters({ queryParameter, datasetNames, fromIndex, toIndex, maxFeatures, returnContent: true, targetEpsgCode }); } function _getReasult( url, queryParameter, datasetNames, fromIndex, toIndex, maxFeatures, serviceOptions, targetEpsgCode ) { return new Promise((resolve, reject) => { new FeatureService(url, serviceOptions).getFeaturesBySQL( _getFeaturesBySQLParameters(queryParameter, datasetNames, fromIndex, toIndex, maxFeatures, targetEpsgCode), (result) => { let featuresResult = result.result; //[bug] wt任务编号: 5223 if (result.type === 'processCompleted' && featuresResult && featuresResult.features) { resolve(result); } else { reject(result); } } ); }); } function Util_isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } ;// CONCATENATED MODULE: ./src/openlayers/services/DataFlowService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DataFlowService * @category iServer DataFlow * @classdesc 数据流服务。 * @extends {ServiceBase} * @example * new DataFlowService(url).queryChart(param,function(result){ * //doSomething * }) * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @param {GeoJSONObject} [options.geometry] - 指定几何范围,该范围内的要素才能被订阅。 * @param {Object} [options.excludeField] - 排除字段。 * @usage */ class DataFlowService extends ServiceBase { constructor(url, options) { options = options || {}; if (options.projection) { options.prjCoordSys = options.projection; } super(url, options); this.dataFlow = new DataFlowService_DataFlowService(url, options); this.dataFlow.events.on({ "broadcastSocketConnected": this._defaultEvent, "broadcastSocketError": this._defaultEvent, "broadcastFailed": this._defaultEvent, "broadcastSucceeded": this._defaultEvent, "subscribeSocketConnected": this._defaultEvent, "subscribeSocketError": this._defaultEvent, "messageSucceeded": this._defaultEvent, "setFilterParamSucceeded": this._defaultEvent, scope: this }); } /** * @function DataFlowService.prototype.initBroadcast * @description 初始化广播。 * @returns {DataFlowService} */ initBroadcast() { this.dataFlow.initBroadcast(); return this; } /** * @function DataFlowService.prototype.broadcast * @description 加载广播数据。 * @param {JSONObject} obj - JSON 格式的要素数据。 */ broadcast(obj) { this.dataFlow.broadcast(obj); } /** * @function DataFlowService.prototype.initSubscribe * @description 初始化订阅数据。 */ initSubscribe() { this.dataFlow.initSubscribe(); return this; } /** * @function DataFlowService.prototype.setExcludeField * @description 设置排除字段。 * @param {Object} excludeField - 排除字段。 */ setExcludeField(excludeField) { this.dataFlow.setExcludeField(excludeField); this.options.excludeField = excludeField; return this; } /** * @function DataFlowService.prototype.setGeometry * @description 设置添加的几何要素数据。 * @param {GeoJSONObject} geometry - 指定几何范围,该范围内的要素才能被订阅。 */ setGeometry(geometry) { this.dataFlow.setGeometry(geometry); this.options.geometry = geometry; return this; } /** * @function DataFlowService.prototype.unSubscribe * @description 结束订阅数据。 */ unSubscribe() { this.dataFlow.unSubscribe(); } /** * @function DataFlowService.prototype.unBroadcast * @description 结束加载广播。 */ unBroadcast() { this.dataFlow.unBroadcast(); } _defaultEvent(e) { this.dispatchEvent({type: e.eventType || e.type, value: e}); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/DataFlow.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DataFlow * @browsernamespace ol.source * @category iServer DataFlow * @classdesc 数据流图层源。订阅SuperMap iServer 数据流服务,并将订阅得到的数据根据 `options.idField` 自动更新。与 {@link ol.layer.Vector} 结合使用可以实现SuperMap iServer 数据流上图、根据`options.idField`自动更新。 * @param {Object} opt_options - 参数。 * @param {string} opt_options.ws - SuperMap iServer 数据流服务地址,例如:http://localhost:8090/iserver/services/dataflowTest/dataflow。 * @param {string} [opt_options.idField = 'id'] - 要素属性中表示唯一标识的字段。 * @param {GeoJSONObject} [opt_options.geometry] - 指定几何范围,该范围内的要素才能被订阅。 * @param {Object} [opt_options.prjCoordSys] - 请求的地图的坐标参考系统。当此参数设置的坐标系统不同于地图的原有坐标系统时,系统会进行动态投影,并返回动态投影后的地图瓦片。例如:{"epsgCode":3857}。 * @param {Object} [opt_options.excludeField] - 排除字段。 * @extends {ol.source.Vector} * @example * var source = new DataFlow({ * ws: urlDataFlow, * idField:"objectId" * }); * var layer = new ol.layer.Vector({ * source: source, * }); * @usage */ class DataFlow extends (external_ol_source_Vector_default()) { constructor(opt_options) { var options = opt_options ? opt_options : {}; super(options); this.idField = options.idField || "id"; this.dataService = new DataFlowService(options.ws, { geometry: options.geometry, prjCoordSys: options.prjCoordSys, excludeField: options.excludeField }).initSubscribe(); var me = this; me.dataService.on("subscribeSocketConnected", function(e) { me.dispatchEvent({ type: "subscribeSucceeded", value: e }); }); me.dataService.on("messageSucceeded", function(msg) { me._onMessageSuccessed(msg); }); me.dataService.on("setFilterParamSucceeded", function(msg) { me.dispatchEvent({ type: "setFilterParamSucceeded", value: msg }); }); this.featureCache = {}; } // /** // * @function DataFlow.prototype.setPrjCoordSys // * @description 设置坐标参考系。 // * @param {Object} prjCoordSys - 参考系。 // */ // setPrjCoordSys(prjCoordSys) { // this.dataService.setPrjCoordSys(prjCoordSys); // this.prjCoordSys = prjCoordSys; // return this; // } /** * @function DataFlow.prototype.setExcludeField * @description 设置唯一字段。 * @param {Object} excludeField - 排除字段。 */ setExcludeField(excludeField) { this.dataService.setExcludeField(excludeField); this.excludeField = excludeField; return this; } /** * @function DataFlow.prototype.setGeometry * @description 设置几何图形。 * @param {Object} geometry - 要素图形。 */ setGeometry(geometry) { this.dataService.setGeometry(geometry); this.geometry = geometry; return this; } _onMessageSuccessed(msg) { //this.clear(); var feature = new (external_ol_format_GeoJSON_default())().readFeature(msg.value.featureResult); var geoID = feature.get(this.idField); if (geoID !== undefined && this.featureCache[geoID]) { this.featureCache[geoID].setGeometry(feature.getGeometry()); this.featureCache[geoID].setProperties(feature.getProperties()); this.changed(); } else { this.addFeature(feature); this.featureCache[geoID] = feature; } this.dispatchEvent({ type: "dataupdated", value: { source: this, data: feature } }); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/theme/ThemeFeature.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeFeature * @category Visualization Theme * @classdesc 专题图要素类。 * @param {Object} geometry - 要量算的几何对象,支持 {@link ol.geom.Geometry} 和 GeometryGeoText 标签数组类型 geometry = [x,y,text]。 * @param {Object} [attributes] - 属性。 * @usage */ class ThemeFeature { constructor(geometry, attributes) { this.geometry = geometry; this.attributes = attributes; } /** * @function ThemeFeature.prototype.toFeature * @description 转为矢量要素。 */ toFeature() { var geometry = this.geometry; if (geometry instanceof (external_ol_geom_Geometry_default())) { //先把数据属性与要素合并 let featureOption = this.attributes; featureOption.geometry = geometry; let olFeature = new (external_ol_Feature_default())(featureOption); return new GeoJSON().read((new (external_ol_format_GeoJSON_default())()).writeFeature(olFeature), "Feature"); } else if (geometry.length === 3) { geometry = new GeoText(geometry[0], geometry[1], geometry[2]); return new Vector(geometry, this.attributes); } } } ;// CONCATENATED MODULE: external "ol.source.ImageCanvas" const external_ol_source_ImageCanvas_namespaceObject = ol.source.ImageCanvas; var external_ol_source_ImageCanvas_default = /*#__PURE__*/__webpack_require__.n(external_ol_source_ImageCanvas_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/overlay/theme/Theme.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Theme * @browsernamespace ol.source * @category Visualization Theme * @classdesc 专题图基类。 * @param {string} name - 专题图图层名称。 * @param {Object} opt_option - 参数。 * @param {ol.Map} opt_option.map - 当前 openlayers 的 Map 对象。 * @param {string} [opt_option.id] - 专题图层 ID。默认使用 CommonUtil.createUniqueID("themeLayer_") 创建专题图层 ID。 * @param {number} [opt_option.opacity=1] - 图层透明度。 * @param {string} [opt_option.logo] - Logo(openLayers 5.0.0 及更高版本不再支持此参数)。 * @param {ol.proj.Projection} [opt_option.projection] - 投影信息。 * @param {number} [opt_option.ratio=1.5] - 视图比,1 表示画布是地图视口的大小,2 表示地图视口的宽度和高度的两倍,依此类推。必须是 1 或更高。 * @param {Array} [opt_option.resolutions] - 分辨率数组。 * @param {ol.source.State} [opt_option.state] - 资源状态。 * @param {(string|Object)} [opt_option.attributions='Map Data © SuperMap iServer with © SuperMap iClient'] - 版权信息。 * @extends {ol.source.ImageCanvas} * @usage */ class theme_Theme_Theme extends (external_ol_source_ImageCanvas_default()) { constructor(name, opt_options) { var options = opt_options ? opt_options : {}; super({ attributions: options.attributions || "Map Data © SuperMap iServer with © SuperMap iClient", canvasFunction: canvasFunctionInternal_, logo: core_Util_Util.getOlVersion() === '4' ? options.logo : null, projection: options.projection, ratio: options.ratio, resolutions: options.resolutions, state: options.state }); /** * @function Theme.prototype.on * @description 添加专题要素事件监听。支持的事件包括: click、mousedown、mousemove、mouseout、mouseover、mouseup。 * @param {string} event - 事件名称。 * @param {RequestCallback} callback - 事件回调函数。 */ this.on = this.onInternal; this.id = options.id ? options.id : Util.createUniqueID("themeLayer_"); function canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars var mapWidth = size[0] * pixelRatio; var mapHeight = size[1] * pixelRatio; if (!this.context) { this.context = core_Util_Util.createCanvasContext2D(mapWidth, mapHeight); } if (!this.features) { return this.context.canvas; } this.pixelRatio = pixelRatio; var width = this.map.getSize()[0] * pixelRatio; var height = this.map.getSize()[1] * pixelRatio; this.offset = [(mapWidth - width) / 2 / pixelRatio, (mapHeight - height) / 2 / pixelRatio]; if (!this.notFirst) { this.redrawThematicFeatures(extent); this.notFirst = true; } this.div.id = this.id; this.div.className = "themeLayer"; this.div.style.width = mapWidth + "px"; this.div.style.height = mapHeight + "px"; this.map.getViewport().appendChild(this.div); this.renderer.resize(); this.map.getViewport().removeChild(this.div); this.themeCanvas = this.renderer.painter.root.getElementsByTagName('canvas')[0]; this.themeCanvas.width = mapWidth; this.themeCanvas.height = mapHeight; this.themeCanvas.style.width = mapWidth + "px"; this.themeCanvas.style.height = mapHeight + "px"; this.themeCanvas.getContext('2d').clearRect(0, 0, mapWidth, mapHeight); var highLightContext = this.renderer.painter._layers.hover.ctx; var highlightCanvas = highLightContext.canvas; var copyHighLightContext = core_Util_Util.createCanvasContext2D(mapWidth, mapHeight); copyHighLightContext.drawImage(highlightCanvas, 0, 0, highlightCanvas.width, highlightCanvas.height, 0, 0, mapWidth, mapHeight); this.redrawThematicFeatures(extent); var canvas = this.context.canvas; this.context.clearRect(0, 0, canvas.width, canvas.height); canvas.width = mapWidth; canvas.height = mapHeight; canvas.style.width = mapWidth + "px"; canvas.style.height = mapHeight + "px"; this.context.drawImage(this.themeCanvas, 0, 0); this.context.drawImage(copyHighLightContext.canvas, 0, 0); return this.context.canvas; } this.canvasFunctionInternal_ = canvasFunctionInternal_; this.EVENT_TYPES = ["loadstart", "loadend", "loadcancel", "visibilitychanged", "move", "moveend", "added", "removed", "tileloaded", "beforefeaturesadded", "featuresadded", "featuresremoved"]; this.features = []; this.TFEvents = options.TFEvents || []; this.map = options.map; var size = this.map.getSize(); this.div = document.createElement('div'); this.map.getViewport().appendChild(this.div); this.div.style.width = size[0] + "px"; this.div.style.height = size[1] + "px"; this.setOpacity(options.opacity); this.levelRenderer = new LevelRenderer(); this.movingOffset = [0, 0]; this.renderer = this.levelRenderer.init(this.div); this.map.getViewport().removeChild(this.div); this.renderer.clear(); //处理用户预先(在图层添加到 map 前)监听的事件 this.addTFEvents(); } /** * @function Theme.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.EVENT_TYPES = null; this.isBaseLayer = null; this.TFEvents = null; this.destroyFeatures(); this.features = null; if (this.renderer) { this.renderer.dispose(); } this.renderer = null; this.levelRenderer = null; this.movingOffset = null; this.currentMousePosition = null; } /** * @function Theme.prototype.destroyFeatures * @description 销毁要素。 * @param {Array.|FeatureVector} features - 将被销毁的要素。 */ destroyFeatures(features) { var all = (features == undefined); if (all) { features = this.features; } if (features) { this.removeFeatures(features); if (!Array.isArray(features)) { features = [features]; } for (var i = features.length - 1; i >= 0; i--) { features[i].destroy(); } } } /** * @function Theme.prototype.setOpacity * @description 设置图层的不透明度,取值[0-1]之间。 * @param {number} opacity - 不透明度。 */ setOpacity(opacity) { if (opacity !== this.opacity) { this.opacity = opacity; var element = this.div; Util.modifyDOMElement(element, null, null, null, null, null, null, opacity); if (this.map !== null) { this.dispatchEvent({type: 'changelayer', value: {layer: this, property: "opacity"}}); } } } /** * @function Theme.prototype.addFeatures * @param {(Array.|Array.|Array.|ThemeFeature|GeoJSONObject|ol.Feature)} features - 待添加要素。 * @description 抽象方法,可实例化子类必须实现此方法。向专题图图层中添加数据, * 专题图仅接收 FeatureVector 类型数据, * feature 将储存于 features 属性中,其存储形式为数组。 */ addFeatures(features) { // eslint-disable-line no-unused-vars } /** * @function Theme.prototype.removeFeatures * @param {(Array.|FeatureVector|Function)} features - 要删除 feature 的数组或用来过滤的回调函数。 * @description 从专题图中删除 feature。这个函数删除所有传递进来的矢量要素。 * 参数中的 features 数组中的每一项,必须是已经添加到当前图层中的 feature, * 如果无法确定 feature 数组,则可以调用 removeAllFeatures 来删除所有 feature。 * 如果要删除的 feature 数组中的元素特别多,推荐使用 removeAllFeatures, * 删除所有 feature 后再重新添加。这样效率会更高。 */ removeFeatures(features) { var me = this; if (!features) { return; } if (features === me.features) { return me.removeAllFeatures(); } if (!Util.isArray(features) && !(typeof features === 'function')) { features = [features]; } var featuresFailRemoved = []; for (var i = 0; i < me.features.length; i++) { var feature = me.features[i]; //如果我们传入的feature在features数组中没有的话,则不进行删除, //并将其放入未删除的数组中。 if (features && typeof features === 'function') { if (features(feature)) { me.features.splice(i--, 1); } } else { var findex = Util.indexOf(features, feature); if (findex === -1) { featuresFailRemoved.push(feature); } else { me.features.splice(i--, 1); } } } var drawFeatures = []; for (var hex = 0, len = this.features.length; hex < len; hex++) { feature = this.features[hex]; drawFeatures.push(feature); } this.features = []; this.addFeatures(drawFeatures); //绘制专题要素 if (this.renderer) { this.redrawThematicFeatures(this.map.getView().calculateExtent()); } var succeed = featuresFailRemoved.length == 0 ? true : false; this.dispatchEvent({type: "featuresremoved", value: {features: featuresFailRemoved, succeed: succeed}}); } /** * @function Theme.prototype.removeAllFeatures * @description 清除当前图层所有的矢量要素。 */ removeAllFeatures() { if (this.renderer) { this.renderer.clear(); } this.features = []; this.dispatchEvent({type: 'featuresremoved', value: {features: [], succeed: true}}); } /** * @function Theme.prototype.getFeatures * @description 查看当前图层中的有效数据。 * @param {Function} [filter] - 根据条件过滤要素的回调函数。 * @returns {Array.} 用户加入图层的有效数据。 */ getFeatures(filter) { var len = this.features.length; var clonedFeatures = []; for (var i = 0; i < len; ++i) { if (!filter || (filter && typeof filter === 'function' && filter(this.features[i]))) { clonedFeatures.push(this.features[i]); } } return clonedFeatures; } /** * @function Theme.prototype.getFeatureBy * @description 在专题图的要素数组 features 里面遍历每一个 feature,当 feature[property] === value 时, * 返回此 feature(并且只返回第一个)。 * @param {string} property - feature 的某个属性名称。 * @param {string} value - property 所对应的值。 * @returns {FeatureVector} 第一个匹配属性和值的矢量要素。 */ getFeatureBy(property, value) { var feature = null; for (var id in this.features) { if (this.features[id][property] === value) { feature = this.features[id]; //feature = this.features[id].clone(); break; } } return feature; } /** * @function Theme.prototype.getFeatureById * @description 通过给定一个 ID,返回对应的矢量要素。 * @param {string} featureId - 矢量要素的属性 ID。 * @returns {FeatureVector} 对应 ID 的 feature,如果不存在则返回 null。 */ getFeatureById(featureId) { return this.getFeatureBy('id', featureId); } /** * @function Theme.prototype.getFeaturesByAttribute * @description 通过给定一个属性的 key 值和 value 值,返回所有匹配的要素数组。 * @param {string} attrName - 属性的 key。 * @param {string} attrValue - 矢量要素的属性 ID。 * @returns {Array.} 一个匹配的 feature 数组。 */ getFeaturesByAttribute(attrName, attrValue) { var feature, foundFeatures = []; for (var id in this.features) { feature = this.features[id]; //feature = this.features[id].clone(); if (feature && feature.attributes) { if (feature.attributes[attrName] === attrValue) { foundFeatures.push(feature); } } } return foundFeatures; } /** * @function Theme.prototype.redrawThematicFeatures * @description 抽象方法,可实例化子类必须实现此方法。重绘专题要素。 * @param {Array} extent - 当前级别下计算出的地图范围。 */ redrawThematicFeatures(extent) { //eslint-disable-line no-unused-vars } /** * @private * @function Theme.prototype.onInternal * @description 添加专题要素事件监听。支持的事件包括: click、mousedown、mousemove、mouseout、mouseover、mouseup。 * @param {string} event - 事件名称。 * @param {RequestCallback} callback - 事件回调函数。 */ onInternal(event, callback) { var cb = callback; if (!this.renderer) { var evn = []; evn.push(event); evn.push(cb); this.TFEvents.push(evn); } else { this.renderer.on(event, cb); } } /** * @function Theme.prototype.fire * @description 添加专题要素事件监听。 * @param {string} type - 事件类型。 * @param {string} event - 事件名称。 */ fire(type, event) { if (!this.offset) { return; } event = event.originalEvent; var x = this.getX(event); var y = this.getY(event); var rotation = -this.map.getView().getRotation(); var center = this.map.getPixelFromCoordinate(this.map.getView().getCenter()); var scaledP = this.scale([x, y], center, this.pixelRatio); var rotatedP = this.rotate(scaledP, rotation, center); var resultP = [rotatedP[0] + this.offset[0], rotatedP[1] + this.offset[1]]; var offsetEvent = document.createEvent('Event'); offsetEvent.initEvent('pointermove', true, true); offsetEvent.offsetX = resultP[0]; offsetEvent.offsetY = resultP[1]; offsetEvent.layerX = resultP[0]; offsetEvent.layerY = resultP[1]; offsetEvent.clientX = resultP[0]; offsetEvent.clientY = resultP[1]; offsetEvent.x = x; offsetEvent.y = y; if (type === 'click') { this.renderer.handler._clickHandler(offsetEvent); } if (type === 'dblclick') { this.renderer.handler._dblclickHandler(offsetEvent); } if (type === 'onmousewheel') { this.renderer.handler._mousewheelHandler(offsetEvent); } if (type === 'mousemove') { this.renderer.handler._mousemoveHandler(offsetEvent); this.changed(); } if (type === 'onmouseout') { this.renderer.handler._mouseoutHandler(offsetEvent); } if (type === 'onmousedown') { this.renderer.handler._mousedownHandler(offsetEvent); } if (type === 'onmouseup') { this.renderer.handler._mouseupHandler(offsetEvent); } } getX(e) { return typeof e.zrenderX != 'undefined' && e.zrenderX || typeof e.offsetX != 'undefined' && e.offsetX || typeof e.layerX != 'undefined' && e.layerX || typeof e.clientX != 'undefined' && e.clientX; } getY(e) { return typeof e.zrenderY != 'undefined' && e.zrenderY || typeof e.offsetY != 'undefined' && e.offsetY || typeof e.layerY != 'undefined' && e.layerY || typeof e.clientY != 'undefined' && e.clientY; } /** * @function Theme.prototype.un * @description 移除专题要素事件监听。 * @param {string} event - 事件名称。 * @param {RequestCallback} callback - 事件回调函数。 */ un(event, callback) { var cb = callback; if (!this.renderer) { var tfEs = this.TFEvents; var len = tfEs.length; var newtfEs = []; for (var i = 0; i < len; i++) { var tfEs_i = tfEs[i]; if (!(tfEs_i[0] === event && tfEs_i[1] === cb)) { newtfEs.push(tfEs_i) } } this.TFEvents = newtfEs; } else { this.renderer.un(event, cb); } } /** * @function Theme.prototype.addTFEvents * @description 将图层添加到地图上之前用户要求添加的事件监听添加到图层。 * @private */ addTFEvents() { var tfEs = this.TFEvents; var len = tfEs.length; for (var i = 0; i < len; i++) { this.renderer.on(tfEs[i][0], tfEs[i][1]); } } /** * @function Theme.prototype.getLocalXY * @description 获取坐标系统。 * @param {Object} coordinate - 坐标位置。 * @returns {Array.} 像素坐标数组。 */ getLocalXY(coordinate) { var pixelP, map = this.map; if (coordinate instanceof Point || coordinate instanceof GeoText) { pixelP = map.getPixelFromCoordinate([coordinate.x, coordinate.y]); } if (coordinate instanceof LonLat) { pixelP = map.getPixelFromCoordinate([coordinate.lon, coordinate.lat]); } var rotation = -map.getView().getRotation(); var center = map.getPixelFromCoordinate(map.getView().getCenter()); var rotatedP = pixelP; if (this.pixelRatio) { rotatedP = this.scale(pixelP, center, this.pixelRatio); } if (pixelP && center) { rotatedP = this.rotate(rotatedP, rotation, center); } if (this.offset && rotatedP) { return [rotatedP[0] + this.offset[0], rotatedP[1] + this.offset[1]]; } return rotatedP; } /** * @function Theme.prototype.rotate * @description 获取某像素坐标点 pixelP 绕中心 center 逆时针旋转 rotation 弧度后的像素点坐标。 * @param {number} pixelP - 像素坐标点位置。 * @param {number} rotation - 旋转角度。 * @param {number} center - 中心位置。 * @returns {Array.} 旋转后的像素坐标数组。 */ rotate(pixelP, rotation, center) { var x = Math.cos(rotation) * (pixelP[0] - center[0]) - Math.sin(rotation) * (pixelP[1] - center[1]) + center[0]; var y = Math.sin(rotation) * (pixelP[0] - center[0]) + Math.cos(rotation) * (pixelP[1] - center[1]) + center[1]; return [x, y]; } /** * @function Theme.prototype.scale * @description 获取某像素坐标点 pixelP 相对于中心 center 进行缩放 scaleRatio 倍后的像素点坐标。 * @param {Object} pixelP - 像素点。 * @param {Object} center - 中心点。 * @param {number} scaleRatio - 缩放倍数。 * @returns {Array.} 返回数组型比例。 */ scale(pixelP, center, scaleRatio) { var x = (pixelP[0] - center[0]) * scaleRatio + center[0]; var y = (pixelP[1] - center[1]) * scaleRatio + center[1]; return [x, y]; } /** * @function Theme.prototype.toiClientFeature * @description 转为 iClient 要素。 * @param {(Array.|Array.|Array.|ThemeFeature|GeoJSONObject|ol.Feature)} features - 待转要素。 * @returns {Array.} 转换后的 iClient 要素。 */ toiClientFeature(features) { if (!Util.isArray(features)) { features = [features]; } let featuresTemp = []; for (let i = 0; i < features.length; i++) { if (features[i] instanceof ThemeFeature) { // ThemeFeature 类型 featuresTemp.push(features[i].toFeature()); continue; } else if (features[i] instanceof (external_ol_Feature_default())) { //ol.Feature 数据类型 //_toFeature 统一处理 ol.Feature 所有 geometry 类型 featuresTemp.push(this._toFeature(features[i])); continue; } else if (features[i] instanceof Vector) { // 若是 FeatureVector 直接返回 featuresTemp.push(features[i]); continue; } else if (features[i].geometry && features[i].geometry.parts) { //iServer服务器返回数据格式 featuresTemp.push(ServerFeature.fromJson(features[i]).toFeature()); } else if (["FeatureCollection", "Feature", "Geometry"].indexOf(features[i].type) != -1) { //GeoJSON 规范数据类型 const format = new GeoJSON(); featuresTemp = featuresTemp.concat(format.read(features[i])); } else { throw new Error(`features[${i}]'s type is not be supported.`); } } return featuresTemp; } /** * @function Theme.prototype.toFeature * @deprecated * @description 转为 iClient 要素,该方法将被弃用,由 {@link Theme#toiClientFeature} 代替。 * @param {(Array.|Array.|Array.|ThemeFeature|GeoJSONObject|ol.Feature)} features - 待转要素。 * @returns {Array.} 转换后的 iClient 要素。 */ toFeature(features) { return this.toiClientFeature(features); } //统一处理 ol.feature所有 geometry 类型 _toFeature(feature) { let geoFeature = (new (external_ol_format_GeoJSON_default())()).writeFeature(feature); return new GeoJSON().read(geoFeature, "Feature"); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/Graph.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Graph * @browsernamespace ol.source * @category Visualization Theme * @classdesc 统计专题图图层基类。 * @param {string} chartsType - 图表类别。 * @param {string} name - 图层名称。 * @param {Object} opt_options - 参数。 * @param {ol.Map} opt_options.map - 当前 Map 对象。 * @param {string} opt_options.chartsType - 图表类型。目前可用:"Bar","Bar3D","Line","Point","Pie","Ring"。 * @param {Object} opt_options.chartsSetting - 各类型图表的 chartsSetting 对象可设属性请参考具体图表模型类的注释中对 chartsSetting 对象可设属性的描述。chartsSetting 对象通常都具有以下几个基础可设属性。 * @param {number} opt_options.chartsSetting.width - 专题要素(图表)宽度。 * @param {number} opt_options.chartsSetting.height - 专题要素(图表)高度。 * @param {Array.} opt_options.chartsSetting.codomain - 值域,长度为 2 的一维数组,第一个元素表示值域下限,第二个元素表示值域上限。 * @param {number} [opt_options.chartsSetting.XOffset] - 专题要素(图表)在 X 方向上的偏移值,单位像素。 * @param {number} [opt_options.chartsSetting.YOffset] - 专题要素(图表)在 Y 方向上的偏移值,单位像素。 * @param {Array.} [opt_options.chartsSetting.dataViewBoxParameter] - 数据视图框 dataViewBox 参数,它是指图表框 chartBox(由图表位置、图表宽度、图表高度构成的图表范围框)在左、下,右,上四个方向上的内偏距值,长度为 4 的一维数组。 * @param {number} [opt_options.chartsSetting.decimalNumber] - 数据值数组 dataValues 元素值小数位数,数据的小数位处理参数,取值范围:[0, 16]。如果不设置此参数,在取数据值时不对数据做小数位处理。 * @param {string} opt_options.themeFields - 指定创建专题图字段。 * @param {string} [opt_options.id] - 专题图层 ID。默认使用 CommonUtil.createUniqueID("themeLayer_") 创建专题图层 ID。 * @param {number} [opt_options.opacity = 1] - 图层透明度。 * @param {string} [opt_options.logo] - Logo(openLayers 5.0.0 及更高版本不再支持此参数)。 * @param {ol.proj.Projection} [opt_options.projection] - {@link ol.proj.Projection} 投影信息。 * @param {number} [opt_options.ratio=1.5] - 视图比, 1 表示画布是地图视口的大小,2 表示地图视口的宽度和高度的两倍,依此类推。必须是 1 或更高。 * @param {Array.} [opt_options.resolutions] - 分辨率数组。 * @param {boolean} [opt_options.isOverLay=true] - 是否进行压盖处理,如果设为 true,图表绘制过程中将隐藏对已在图层中绘制的图表产生压盖的图表。 * @param {ol.source.State} [opt_options.state] - 资源状态。 * @param {(string|Object)} [opt_options.attributions='Map Data © SuperMap iServer with © SuperMap iClient'] - 版权信息。 * @extends {Theme} * @usage */ class Graph_Graph extends theme_Theme_Theme { constructor(name, chartsType, opt_options) { super(name, opt_options); this.chartsSetting = opt_options.chartsSetting || {}; this.themeFields = opt_options.themeFields || null; this.overlayWeightField = opt_options.overlayWeightField || null; this.isOverLay = opt_options.isOverLay === undefined ? true : opt_options.isOverLay; this.charts = opt_options.charts || []; this.cache = opt_options.cache || {}; this.chartsType = chartsType; } /** * @function Graph.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.chartsType = null; this.chartsSetting = null; this.themeFields = null; this.overlayWeightField = null; this.isOverLay = null; theme_Theme_Theme.prototype.destroy.apply(this, arguments); // charts cache 为缓存,需要在父类destory后置为null(父类destory中有方法会初始化缓存参数) this.charts = null; this.cache = null; } /** * @function Graph.prototype.setChartsType * @description 设置图表类型,此函数可动态改变图表类型。在调用此函数前请通过 chartsSetting 为新类型的图表做相关配置。 * @param {string} chartsType - 图表类型。目前可用:"Bar","Bar3D","Line","Point","Pie","Ring"。 */ setChartsType(chartsType) { this.chartsType = chartsType; this.redraw(); } /** * @function Graph.prototype.addFeatures * @description 向专题图图层中添加数据。 * @param {(ServerFeature|ThemeFeature)} features - 待添加的要素。 */ addFeatures(features) { var ret = this.dispatchEvent({ type: 'beforefeaturesadded', value: { features: features } }); if (ret === false) { return; } //转换 features 形式 this.features = this.toiClientFeature(features); //绘制专题要素 if (this.renderer) { this.changed(); } } /** * @function Graph.prototype.redrawThematicFeatures * @description 重绘所有专题要素。 * 此方法包含绘制专题要素的所有步骤,包含用户数据到专题要素的转换,抽稀,缓存等步骤。 * 地图漫游时调用此方法进行图层刷新。 * @param {Object} extent - 重绘的范围。 * */ redrawThematicFeatures(extent) { //清除当前所有可视元素 this.renderer.clearAll(); var features = this.features; for (var i = 0, len = features.length; i < len; i++) { var feature = features[i]; // 要素范围判断 var feaBounds = feature.geometry.getBounds(); //剔除当前视图(地理)范围以外的数据 if (extent) { var bounds = new Bounds(extent[0], extent[1], extent[2], extent[3]); if (!bounds.intersectsBounds(feaBounds)) { continue; } } var cache = this.cache; // 用 feature id 做缓存标识 var cacheField = feature.id; // 数据对应的图表是否已缓存,没缓存则重新创建图表 if (cache[cacheField]) { continue; } cache[cacheField] = cacheField; var chart = this.createThematicFeature(feature); // 压盖处理权重值 if (chart && this.overlayWeightField) { if (feature.attributes[this.overlayWeightField] && !isNaN(feature.attributes[this.overlayWeightField])) { chart["__overlayWeight"] = feature.attributes[this.overlayWeightField]; } } if (chart) { this.charts.push(chart); } } this.drawCharts(); } /** * @function Graph.prototype.createThematicFeature * @description 向专题图图层中添加数据, 支持的 feature 类型为:iServer 返回的 feature JSON 对象。 * @param {ServerFeature} feature - 待添加的要素。 * */ createThematicFeature(feature) { var thematicFeature; // 检查图表创建条件并创建图形 if (Theme_Theme[this.chartsType] && this.themeFields && this.chartsSetting) { thematicFeature = new Theme_Theme[this.chartsType](feature, this, this.themeFields, this.chartsSetting); } // thematicFeature 是否创建成功 if (!thematicFeature) { return false; } // 对专题要素执行图形装载 thematicFeature.assembleShapes(); return thematicFeature; } /** * @function Graph.prototype.drawCharts * @description 绘制图表。包含压盖处理。 * */ drawCharts() { // 判断 rendere r就绪 if (!this.renderer) { return; } var charts = this.charts; // 图表权重值处理 if (this.overlayWeightField) { charts.sort(function (cs, ce) { if (typeof (cs["__overlayWeight"]) == "undefined" && typeof (ce["__overlayWeight"]) == "undefined") { return 0; } else if (typeof (cs["__overlayWeight"]) != "undefined" && typeof (ce["__overlayWeight"]) == "undefined") { return -1; } else if (typeof (cs["__overlayWeight"]) == "undefined" && typeof (ce["__overlayWeight"]) != "undefined") { return 1; } else if (typeof (cs["__overlayWeight"]) != "undefined" && typeof (ce["__overlayWeight"]) != "undefined") { if (parseFloat(cs["__overlayWeight"]) < parseFloat(ce["__overlayWeight"])) { return 1; } else { return -1; } } return 0; }); } // 不进行避让 if (!this.isOverLay) { for (var m = 0, len_m = charts.length; m < len_m; m++) { var chart_m = charts[m]; // 图形参考位置 (reSetLocation 会更新 chartBounds) var shapeROP_m = chart_m.resetLocation(); // 添加图形 var shapes_m = chart_m.shapes; for (var n = 0, slen_n = shapes_m.length; n < slen_n; n++) { shapes_m[n].refOriginalPosition = shapeROP_m; this.renderer.addShape(shapes_m[n]); } } } else { // 压盖判断所需 chartsBounds 集合 var chartsBounds = []; var extent = this.map.getView().calculateExtent(); var mapBounds = new Bounds(extent[0], extent[1], extent[2], extent[3]); // 获取地图像素 bounds var mapPxLT = this.getLocalXY(new LonLat(mapBounds.left, mapBounds.top)); var mapPxRB = this.getLocalXY(new LonLat(mapBounds.right, mapBounds.bottom)); var mBounds = new Bounds(mapPxLT[0], mapPxRB[1], mapPxRB[0], mapPxLT[1]); // 压盖处理 & 添加图形 for (var i = 0, len = charts.length; i < len; i++) { var chart = charts[i]; // 图形参考位置 (reSetLocation 会更新 chartBounds) var shapeROP = chart.resetLocation(); // 图表框 var cbs = chart.chartBounds; var cBounds = [{ "x": cbs.left, "y": cbs.top }, { "x": cbs.left, "y": cbs.bottom }, { "x": cbs.right, "y": cbs.bottom }, { "x": cbs.right, "y": cbs.top }, { "x": cbs.left, "y": cbs.top }]; // 地图范围外不绘制 if (mBounds) { if (!this.isChartInMap(mBounds, cBounds)) { continue; } } // 是否压盖 var isOL = false; if (i !== 0) { for (let j = 0; j < chartsBounds.length; j++) { //压盖判断 if (this.isQuadrilateralOverLap(cBounds, chartsBounds[j])) { isOL = true; break; } } } if (isOL) { continue; } else { chartsBounds.push(cBounds); } // 添加图形 var shapes = chart.shapes; for (let j = 0, slen = shapes.length; j < slen; j++) { shapes[j].refOriginalPosition = shapeROP; this.renderer.addShape(shapes[j]); } } } // 绘制图形 this.renderer.render(); } /** * @function Graph.prototype.getShapesByFeatureID * @description 通过 FeatureID 获取 feature 关联的所有图形。如果不传入此参数,函数将返回所有图形。 * @param {number} featureID - 要素 ID。 */ getShapesByFeatureID(featureID) { var list = []; var shapeList = this.renderer.getAllShapes(); if (!featureID) { return shapeList } for (var i = 0, len = shapeList.length; i < len; i++) { var si = shapeList[i]; if (si.refDataID && featureID === si.refDataID) { list.push(si); } } return list; } /** * @function Graph.prototype.isQuadrilateralOverLap * @description 判断两个四边形是否有压盖。 * @param {Array.} quadrilateral - 四边形节点数组。 * @param {Array.} quadrilateral2 - 第二个四边形节点数组。 */ isQuadrilateralOverLap(quadrilateral, quadrilateral2) { var quadLen = quadrilateral.length, quad2Len = quadrilateral2.length; if (quadLen !== 5 || quad2Len !== 5) { return null; } //不是四边形 var OverLap = false; //如果两四边形互不包含对方的节点,则两个四边形不相交 for (let i = 0; i < quadLen; i++) { if (this.isPointInPoly(quadrilateral[i], quadrilateral2)) { OverLap = true; break; } } for (let i = 0; i < quad2Len; i++) { if (this.isPointInPoly(quadrilateral2[i], quadrilateral)) { OverLap = true; break; } } //加上两矩形十字相交的情况 for (let i = 0; i < quadLen - 1; i++) { if (OverLap) { break; } for (let j = 0; j < quad2Len - 1; j++) { var isLineIn = Util.lineIntersection(quadrilateral[i], quadrilateral[i + 1], quadrilateral2[j], quadrilateral2[j + 1]); if (isLineIn.CLASS_NAME === "SuperMap.Geometry.Point") { OverLap = true; break; } } } return OverLap; } /** * @function Graph.prototype.isPointInPoly * @description 判断一个点是否在多边形里面(射线法)。 * @param {Object} pt - 需要判定的点对象,该对象含有属性 x(横坐标),属性 y(纵坐标)。 * @param {Array.} poly - 多边形节点数组。 */ isPointInPoly(pt, poly) { for (var isIn = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) { ((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y)) && (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x) && (isIn = !isIn); } return isIn; } /** * @function Graph.prototype.isChartInMap * @description 判断图表是否在地图里。 * @param {Bounds} mapPxBounds - 地图像素范围。 * @param {Array.} chartPxBounds - 图表范围的四边形节点数组。 */ isChartInMap(mapPxBounds, chartPxBounds) { var mb = mapPxBounds; var isIn = false; for (var i = 0, len = chartPxBounds.length; i < len; i++) { var cb = chartPxBounds[i]; if (cb.x >= mb.left && cb.x <= mb.right && cb.y >= mb.top && cb.y <= mb.bottom) { isIn = true; break; } } return isIn; } /** * @function Graph.prototype.clearCache * @description 清除缓存。 */ clearCache() { this.cache = {}; this.charts = []; } /** * @function Graph.prototype.removeFeatures * @description 从专题图中删除 feature。这个函数删除所有传递进来的矢量要素。参数中的 features 数组中的每一项,必须是已经添加到当前图层中的 feature。 * @param {Array.|FeatureVector|Function} features - 要删除的要素。 */ removeFeatures(features) { this.clearCache(); super.removeFeatures(features); } /** * @function Graph.prototype.removeAllFeatures * @description 移除所有的要素。 */ removeAllFeatures() { this.clearCache(); super.removeAllFeatures(); } /** * @function Graph.prototype.redraw * @description 重绘该图层。 */ redraw() { this.clearCache(); if (this.renderer) { this.redrawThematicFeatures(this.map.getView().calculateExtent()); return true; } return false } /** * @function Graph.prototype.clear * @description 清除的内容包括数据(features)、专题要素、缓存。 */ clear() { if (this.renderer) { this.renderer.clearAll(); this.renderer.refresh(); } this.removeAllFeatures(); this.clearCache(); } canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars return theme_Theme_Theme.prototype.canvasFunctionInternal_.apply(this, arguments); } } ;// CONCATENATED MODULE: external "ol.style.RegularShape" const external_ol_style_RegularShape_namespaceObject = ol.style.RegularShape; var external_ol_style_RegularShape_default = /*#__PURE__*/__webpack_require__.n(external_ol_style_RegularShape_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/overlay/graphic/CloverShape.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class CloverShape * @browsernamespace ol.style * @category Visualization Graphic * @classdesc 三叶草要素风格。 * @extends {ol.style.RegularShape} * @param {Object} options - 三叶草形要素风格参数。 * @param {number} [options.angle=30] - 三叶草每个扇叶的圆心角,单位弧度。 * @param {number} [options.count=3] - 扇叶数量。 * @param {ol.style.Fill} [options.fill] - 填充样式。 * @param {number} [options.strokeOpacity] - 透明度。 * @param {number} [options.fillOpacity] - 填充透明度。 * @param {number} [options.radius] - 半径。 * @param {ol.style.Stroke} [options.stroke] - 边框样式。 * @param {string} [options.stroke.color='#3388ff'] - 边框颜色。 * @param {number} [options.stroke.width=1] - 边框宽度。 * @usage */ class CloverShape extends (external_ol_style_RegularShape_default()) { constructor(options) { if (options.stroke) { options.stroke.color = options.stroke.getColor() || "#3388ff"; options.stroke.width = options.stroke.getWidth() || 1; } else { options.stroke = new (external_ol_style_Stroke_default())({ color: "#3388ff", width: 1 }) } if (options.fill) { options.fill.color = options.fill.getColor() || "#66ccff"; } else { options.fill = new (external_ol_style_Fill_default())({ color: "#66ccff" }) } super({ angle: options.angle || 60, stroke: options.stroke, fill: options.fill, radius: options.radius || 10, rotation: options.rotation || 0 }); this.count_ = options.count || 3; this.strokeOpacity = options.strokeOpacity || 1; this.fillOpacity = options.fillOpacity || 1; this._pixelRatio = window ? window.devicePixelRatio : 1; this._canvas = this.getImage(this._pixelRatio); this._ctx = this._canvas.getContext('2d'); this._render(); } _render() { //起始角度 var sAngle = 0; var eAngle = this.getAngle(); this.spaceAngle = 360 / this.count_ - this.getAngle(); if (this.spaceAngle < 0) { return; } this._ctx.setTransform(this._pixelRatio, 0, 0, this._pixelRatio, 0, 0); this._ctx.translate(0, 0); this._ctx.beginPath(); for (var i = 0; i < this.count_; i++) { this._drawSector(this._ctx, this.getAnchor()[0], this.getAnchor()[1], this.getRadius(), sAngle, eAngle); sAngle = eAngle + this.spaceAngle; eAngle = sAngle + this.getAngle(); } this._fillStroke(); this._ctx.closePath(); } /** * @function CloverShape.prototype.drawSector * @description 绘制扇形。 * @param {CanvasRenderingContext2D} ctx - context 对象。 * @param {number} x - 中心点 x。 * @param {number} y - 中心点 y。 * @param {number} r - 中心点 r。 * @param {number} sAngle - 扇叶起始角度。 * @param {number} eAngle - 扇叶终止角度。 */ _drawSector(ctx, x, y, r, sAngle, eAngle) { //角度转换 sAngle = sAngle / 180 * Math.PI; eAngle = eAngle / 180 * Math.PI; ctx.moveTo(x, y); ctx.lineTo(x + r * Math.cos(sAngle), y + r * Math.sin(sAngle)); ctx.arc(x, y, r, sAngle, eAngle); ctx.lineTo(x, y); } _fillStroke() { if (this.getFill()) { this._ctx.globalAlpha = this.fillOpacity; this._ctx.fillStyle = this.getFill().color; this._ctx.fill(); } if (this.getStroke() && this.weight !== 0) { this._ctx.globalAlpha = this.strokeOpacity; this._ctx.lineWidth = this.getStroke().width; this._ctx.strokeStyle = this.getStroke().color; this._ctx.lineCap = this.getStroke().lineCap; this._ctx.lineJoin = this.getStroke().lineJoin; this._ctx.stroke(); } } /** * @function CloverShape.prototype.getCount * @description 获取扇叶数量。 */ getCount() { return this.count_; } /** * @function CloverShape.prototype.getSpaceAngle * @description 获取扇叶间隔角度。 */ getSpaceAngle() { return this.spaceAngle; } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/graphic/HitCloverShape.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class HitCloverShape * @browsernamespace ol.style * @category Visualization Graphic * @classdesc 三叶草要素高亮风格。 * @extends {CloverShape} * @param {Object} options - 三叶草形要素风格参数。 * @param {number} options.sAngle - 扇叶起始角度。 * @param {number} options.eAngle - 扇叶终止角度。 * @param {number} [options.angle = 30] - 三叶草每个扇叶的圆心角,单位弧度。 * @param {ol.style.Fill} [options.fill] - 填充样式。 * @param {ol.style.Stroke} [options.stroke] - 边框样式。 * @param {number} [options.strokeOpacity] - 透明度。 * @param {number} [options.fillOpacity] - 填充透明度。 * @param {number} [options.radius] - 半径。 * @usage */ class HitCloverShape extends CloverShape { constructor(options) { super(options); this.sAngle = options.sAngle; this.eAngle = options.eAngle; this._render(); } _render() { // draw the circle on the canvas this._ctx.clearRect(0, 0, this.getImage().width, this.getImage().height); // reset transform this._ctx.setTransform(this._pixelRatio, 0, 0, this._pixelRatio, 0, 0); this._ctx.translate(0, 0); this._ctx.beginPath(); this._drawSector(this._ctx, this.getAnchor()[0], this.getAnchor()[1], this.getRadius(), this.sAngle, this.eAngle); this._fillStroke(); this._ctx.closePath(); } /** * @function HitCloverShape.prototype.getSAngle * @description 获取扇叶起始角度。 */ getSAngle() { return this.sAngle; } /** * @function HitCloverShape.prototype.getEAngle * @description 获取扇叶终止角度。 */ getEAngle() { return this.eAngle; } } ;// CONCATENATED MODULE: external "ol.Object" const external_ol_Object_namespaceObject = ol.Object; var external_ol_Object_default = /*#__PURE__*/__webpack_require__.n(external_ol_Object_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/overlay/graphic/WebGLRenderer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ const emptyFunc = () => false; const CSS_TRANSFORM = (function () { let div = document.createElement('div'); let props = [ 'transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ]; for (let i = 0; i < props.length; i++) { let prop = props[i]; if (div.style[prop] !== undefined) { return prop; } } return props[0]; })(); /** * @private * @class GraphicWebGLRenderer * @classdesc 高效率点图层 webgl 渲染器。 * @category Visualization Graphic * @extends {ol.Object} * @param {ol.source.Graphic} layer - 高效率点图层。 * @param {Object} options - 图层参数。 * @param {number} options.width - 地图宽度。 * @param {number} options.height - 地图高度。 * @param {HTMLElement} options.container - 放置渲染器的父元素。 * @param {Array.} [options.color=[0, 0, 0, 255]] - 颜色,目前只支持 rgba 数组。 * @param {number} [options.radius=10] - 半径。 * @param {number} [options.opacity=0.8] - 不透明度。 * @param {Array} [options.highlightColor] - 高亮颜色,目前只支持 rgba 数组。 * @param {number} [options.radiusScale = 1] - 点放大倍数。 * @param {number} [options.radiusMinPixels = 0] - 半径最小值(像素)。 * @param {number} [options.radiusMaxPixels = Number.MAX_SAFE_INTEGER] - 半径最大值(像素)。 * @param {number} [options.strokeWidth = 1] - 边框大小。 * @param {boolean} [options.outline = false] - 是否显示边框。 * @param {function} [options.onClick] - 点击事件。 * @param {function} [options.onHover] - 悬停事件。 */ class GraphicWebGLRenderer extends (external_ol_Object_default()) { constructor(layer, options) { super(); this.layer = layer; this.map = layer.map; let opt = options || {}; Util.extend(this, opt); let pixelRatio = this.pixelRatio = window ? window.devicePixelRatio : 1; this.width = this.map.getSize()[0] * pixelRatio; this.height = this.map.getSize()[1] * pixelRatio; this.center = this.map.getView().getCenter(); this._initContainer(); this._registerEvents(); } _registerEvents() { let map = this.map; let view = map.getView(); map.on('change:size', this._resizeEvent.bind(this), this); view.on('change:resolution', this._moveEndEvent.bind(this), this); view.on('change:center', this._moveEvent.bind(this), this); view.on('change:rotation', this._moveEndEvent.bind(this), this); map.on('moveend', this._moveEndEvent.bind(this), this) } _resizeEvent() { this._resize(); this._clearAndRedraw(); } _moveEvent() { let oldCenterPixel = this.map.getPixelFromCoordinate(this.center); let newCenterPixel = this.map.getPixelFromCoordinate(this.map.getView().getCenter()); let offset = [oldCenterPixel[0] - newCenterPixel[0], oldCenterPixel[1] - newCenterPixel[1]]; this._canvas.style[CSS_TRANSFORM] = 'translate(' + Math.round(offset[0]) + 'px,' + Math.round(offset[1]) + 'px)'; } _moveEndEvent() { this._canvas.style[CSS_TRANSFORM] = 'translate(0,0)'; this.center = this.map.getView().getCenter(); this._clearAndRedraw(); } _clearAndRedraw() { this._clearBuffer(); this.layer.changed(); } _resize() { const size = this.map.getSize(); const width = size[0] * this.pixelRatio; const height = size[1] * this.pixelRatio; this._canvas.width = width; this._canvas.height = height; this._canvas.style.width = width + 'px'; this._canvas.style.height = height + 'px'; } _clearBuffer() { if (!this.deckGL) { return; } let lm = this.deckGL.layerManager; lm && lm.context.gl.clear(lm.context.gl.COLOR_BUFFER_BIT); return this; } /** * @private * @function GraphicWebGLRenderer.prototype.getCanvas * @description 返回画布。 * @returns {HTMLCanvasElement} canvas 对象。 */ getCanvas() { return this._canvas; } /** * @private * @function GraphicWebGLRenderer.prototype.update * @description 更新图层,数据或者样式改变后调用。 */ update(graphics) { if (graphics && graphics.length > -1) { this._data = graphics; } if (!this._renderLayer) { return; } this._renderLayer.setChangeFlags({ dataChanged: true, propsChanged: true, viewportChanged: true, updateTriggersChanged: true }); this._refreshData(); let state = this._getLayerState(); state.data = this._data || []; this._renderLayer.setNeedsRedraw(true); this._renderLayer.setState(state); } /** * @private * @function GraphicWebGLRenderer.prototype.drawGraphics * @description 绘制点要素。 */ drawGraphics(graphics) { this._data = graphics ? graphics : this._data ? this._data : []; if (!this._renderLayer) { this._createInnerRender(); } this._clearBuffer(); this._draw(); } _initContainer() { this._canvas = this._createCanvas(this.width, this.height); this._layerContainer = this.container; this._wrapper = document.createElement('div'); this._wrapper.className = "deck-wrapper"; this._wrapper.style.position = "absolute"; this._wrapper.style.top = "0"; this._wrapper.style.left = "0"; this._wrapper.appendChild(this._canvas); this._layerContainer && this._layerContainer.appendChild(this._wrapper); } _createCanvas(width, height) { let canvas = document.createElement('canvas'); canvas.oncontextmenu = emptyFunc; canvas.width = width; canvas.height = height; canvas.style.width = width + "px"; canvas.style.height = height + "px"; return canvas; } _createInnerRender() { let me = this; let state = this._getLayerState(); let { color, radius, opacity, highlightColor, radiusScale, radiusMinPixels, radiusMaxPixels, strokeWidth, outline } = state; radius = this._pixelToMeter(radius); let innerLayerOptions = { id: 'scatter-plot', data: [], pickable: Boolean(this.onClick) || Boolean(this.onHover), autoHighlight: true, color: color, opacity: opacity, radius: radius, radiusScale: radiusScale, highlightColor: highlightColor, radiusMinPixels: radiusMinPixels, radiusMaxPixels: radiusMaxPixels, strokeWidth: strokeWidth, outline: outline, getPosition(point) { if (!point) { return [0, 0, 0]; } let geometry = point.getGeometry(); let coordinates = geometry && geometry.getCoordinates(); coordinates = me._project(coordinates); return coordinates && [coordinates[0], coordinates[1], 0]; }, getColor(point) { let defaultStyle = me._getLayerDefaultStyle(); let style = point && point.getStyle(); return style && style.getColor && style.getColor() || defaultStyle.color }, getRadius(point) { let defaultStyle = me._getLayerDefaultStyle(); let style = point && point.getStyle(); return style && style.getRadius && style.getRadius() || defaultStyle.radius }, updateTriggers: { getColor: [color], getRadius: [radius] } }; me._renderLayer = new window.DeckGL.ScatterplotLayer(innerLayerOptions); } _getLayerDefaultStyle() { let { color, opacity, radius, radiusScale, radiusMinPixels, radiusMaxPixels, strokeWidth, outline } = this._getLayerState(); radius = this._pixelToMeter(radius); return { color, opacity, radius, radiusScale, radiusMinPixels, radiusMaxPixels, strokeWidth, outline } } _getLayerState() { let state = this.layer.getLayerState(); let view = this.map.getView(); let projection = view.getProjection().getCode(); let center = external_ol_proj_namespaceObject.transform([state.longitude, state.latitude], projection, 'EPSG:4326') state.longitude = center[0]; state.latitude = center[1]; state.zoom = state.zoom - 1; return state; } _draw() { this._refreshData(); let state = this._getLayerState(); state.data = this._data || []; let deckOptions = {}; for (let key in state) { deckOptions[key] = state[key]; } this._renderLayer.setNeedsRedraw(true); deckOptions.layers = [this._renderLayer]; deckOptions.canvas = this._canvas; if (this.onBeforeRender) { deckOptions.onBeforeRender = this.onBeforeRender.bind(this); } if (this.onAfterRender) { deckOptions.onAfterRender = this.onAfterRender.bind(this); } if (!this.deckGL) { this.deckGL = new window.DeckGL.experimental.DeckGLJS(deckOptions); } else { this.deckGL.setProps(deckOptions); } } _refreshData() { let graphics = this._data || []; let sGraphics = !core_Util_Util.isArray(graphics) ? [graphics] : [].concat(graphics); //this.layer.props.data不能被重新赋值,只能在原数组上进行操作 if (!this._renderLayer.props.data) { this._renderLayer.props.data = []; } this._renderLayer.props.data.length = 0; for (let j = 0; j < sGraphics.length; j++) { this._renderLayer.props.data.push(sGraphics[j]); } this._data = this._renderLayer.props.data; } _project(coordinates) { let view = this.map.getView(); let projection = view.getProjection().getCode(); if ("EPSG:4326" === projection) { return coordinates; } return external_ol_proj_namespaceObject.transform(coordinates, projection, 'EPSG:4326'); } _pixelToMeter(pixel) { let view = this.map.getView(); let projection = view.getProjection(); let unit = projection.getUnits() || 'degrees'; if (unit === 'degrees') { unit = Unit.DEGREE; } if (unit === 'm') { unit = Unit.METER; } const res = view.getResolution(); if (unit === Unit.DEGREE) { let meterRes= res*(Math.PI * 6378137 / 180); return pixel * meterRes; }else{ return pixel * res; } } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/graphic/CanvasRenderer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ //获取某像素坐标点pixelP相对于中心center进行缩放scaleRatio倍后的像素点坐标。 function scale(pixelP, center, scaleRatio) { let x = (pixelP[0] - center[0]) * scaleRatio + center[0]; let y = (pixelP[1] - center[1]) * scaleRatio + center[1]; return [x, y]; } /** * @private * @class GraphicCanvasRenderer * @classdesc 高效率点图层 canvas 渲染器。 * @category Visualization Graphic * @extends {ol.Object} * @param {Graphic} layer - 高效率点图层。 * @param {Object} options - 图层参数。 * @param {number} options.width - 地图宽度。 * @param {number} options.height - 地图高度。 * @param {HTMLElement} options.container - 放置渲染器的父元素。 * @param {Array.} [options.colo=[0, 0, 0, 255]] - 颜色,目前只支持rgba数组。默认[0, 0, 0, 255], * @param {number} [options.radius=10] - 半径。 * @param {number} [options.opacity=0.8] - 不透明度。 * @param {Array} [options.highlightColor] - 高亮颜色,目前只支持rgba数组。 * @param {number} [options.radiusScale] - 点放大倍数。 * @param {number} [options.radiusMinPixels] - 半径最小值(像素)。 * @param {number} [options.radiusMaxPixels] - 半径最大值(像素)。 * @param {number} [options.strokeWidth] - 边框大小。 * @param {boolean} [options.outline] - 是否显示边框。 * @param {function} [options.onClick] - 点击事件。 * @param {function} [options.onHover] - 悬停事件。 */ class GraphicCanvasRenderer extends (external_ol_Object_default()) { constructor(layer, options) { super(); this.layer = layer; this.map = layer.map; let opt = options || {}; Util.extend(this, opt); this.highLightStyle = this.layer.highLightStyle; this.mapWidth = this.size[0] / this.pixelRatio; this.mapHeight = this.size[1] / this.pixelRatio; this.width = this.map.getSize()[0]; this.height = this.map.getSize()[1]; this.context = core_Util_Util.createCanvasContext2D(this.mapWidth, this.mapHeight); this.context.scale(this.pixelRatio, this.pixelRatio); this.canvas = this.context.canvas; this.canvas.style.width = this.width + 'px'; this.canvas.style.height = this.height + 'px'; this._registerEvents(); } _registerEvents() { this.map.on('change:size', this._resizeEvent.bind(this), this); } _resizeEvent() { this._resize(); this._clearAndRedraw(); } _resize() { let size = this.map.getSize(); let width = size[0]; let height = size[1]; let xRatio = width / this.width; let yRatio = height / this.height; this.width = width; this.height = height; this.mapWidth = this.mapWidth * xRatio; this.mapHeight = this.mapHeight * yRatio; this.canvas.width = this.mapWidth; this.canvas.height = this.mapHeight; this.canvas.style.width = this.width + 'px'; this.canvas.style.height = this.height + 'px'; } _clearAndRedraw() { this._clearBuffer(); this.layer.changed(); } update() { this.layer.changed(); } _clearBuffer() {} /** * @private * @function GraphicCanvasRenderer.prototype.getCanvas * @description 返回画布。 * @returns {HTMLCanvasElement} canvas 对象。 */ getCanvas() { return this.canvas; } /** * @private * @function GraphicCanvasRenderer.prototype.drawGraphics * @description 绘制点要素。 */ drawGraphics(graphics) { this.graphics_ = graphics || []; let mapWidth = this.mapWidth; let mapHeight = this.mapHeight; let vectorContext = external_ol_render_namespaceObject.toContext(this.context, { size: [mapWidth, mapHeight], pixelRatio: this.pixelRatio }); let defaultStyle = this.layer._getDefaultStyle(); let me = this, layer = me.layer, map = layer.map; graphics.map(function (graphic) { let style = graphic.getStyle() || defaultStyle; if (me.selected === graphic) { let defaultHighLightStyle = style; if (style instanceof external_ol_style_namespaceObject.Circle) { defaultHighLightStyle = new external_ol_style_namespaceObject.Circle({ radius: style.getRadius(), fill: new external_ol_style_namespaceObject.Fill({ color: 'rgba(0, 153, 255, 1)' }), stroke: style.getStroke(), snapToPixel: core_Util_Util.getOlVersion() === '4' ? style.getSnapToPixel() : null }); } else if (style instanceof external_ol_style_namespaceObject.RegularShape) { defaultHighLightStyle = new external_ol_style_namespaceObject.RegularShape({ radius: style.getRadius(), radius2: style.getRadius2(), points: style.getPoints(), angle: style.getAngle(), snapToPixel: core_Util_Util.getOlVersion() === '4' ? style.getSnapToPixel() : null, rotation: style.getRotation(), rotateWithView: style.getRotateWithView(), fill: new external_ol_style_namespaceObject.Fill({ color: 'rgba(0, 153, 255, 1)' }), stroke: style.getStroke() }); } style = me.highLightStyle || defaultHighLightStyle; } vectorContext.setStyle( new external_ol_style_namespaceObject.Style({ image: style }) ); let geometry = graphic.getGeometry(); let coordinate = geometry.getCoordinates(); let center = map.getView().getCenter(); let mapCenterPx = map.getPixelFromCoordinate(center); let resolution = map.getView().getResolution(); let x = (coordinate[0] - center[0]) / resolution; let y = (center[1] - coordinate[1]) / resolution; let scaledP = [x + mapCenterPx[0], y + mapCenterPx[1]]; scaledP = scale(scaledP, mapCenterPx, 1); //处理放大或缩小级别*/ let result = [scaledP[0] + me.offset[0], scaledP[1] + me.offset[1]]; let pixelGeometry = new (external_ol_geom_Point_default())(result); vectorContext.drawGeometry(pixelGeometry); return graphic; }); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/graphic/Graphic.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class OverlayGraphic * @browsernamespace ol * @aliasclass Graphic * @category Visualization Graphic * @classdesc 高效率点图层点要素类。 * @param {ol.geom.Point} geometry - 几何对象。 * @param {Object} [attributes] - 要素属性。 * @extends {ol.Object} * @usage */ class Graphic_Graphic extends (external_ol_Object_default()) { constructor(geometry, attributes) { super(); if (geometry instanceof (external_ol_geom_Geometry_default())) { this.geometry_ = geometry; } this.attributes = attributes; this.setStyle(); } /** * @function OverlayGraphic.prototype.clone * @description 克隆当前要素。 * @returns {OverlayGraphic} 克隆后的要素。 */ clone() { var clone = new Graphic_Graphic(); clone.setId(this.id); clone.setGeometry(this.geometry_); clone.setAttributes(this.attributes); clone.setStyle(this.style_); return clone; } /** * @function OverlayGraphic.prototype.getId * @description 获取当前 ID。 * @returns {string} ID。 */ getId() { return this.id; } /** * @function OverlayGraphic.prototype.setId * @description 设置当前要素 ID。 * @param {string} id - 要素 ID。 */ setId(id) { this.id = id; } /** * @function OverlayGraphic.prototype.getGeometry * @description 获取当前要素几何信息。 * @returns {ol.geom.Point} 要素几何信息。 */ getGeometry() { return this.geometry_; } /** * @function OverlayGraphic.prototype.setGeometry * @description 设置当前要素几何信息。 * @param {ol.geom.Point} geometry - 要素几何信息。 */ setGeometry(geometry) { this.geometry_ = geometry; } /** * @function OverlayGraphic.prototype.setAttributes * @description 设置要素属性。 * @param {Object} attributes - 属性对象。 */ setAttributes(attributes) { this.attributes = attributes; } /** * @function OverlayGraphic.prototype.getAttributes * @description 获取要素属性。 * @returns {Object} 要素属性。 */ getAttributes() { return this.attributes; } /** * @function OverlayGraphic.prototype.getStyle * @description 获取样式。 * @returns {ol.style.Image} ol.style.Image 子类样式对象。 */ getStyle() { return this.style_; } /** * @function OverlayGraphic.prototype.setStyle * @description 设置样式。 * @param {ol.style.Image} style - 样式,ol/style/Image 子类样式对象。 */ setStyle(style) { if (!this.style && !style) { return; } this.style_ = style; this.styleFunction_ = !style ? undefined : Graphic_Graphic.createStyleFunction(new (external_ol_style_Style_default())({ image: style })); this.changed(); } /** * @function OverlayGraphic.prototype.getStyleFunction * @description 获取样式函数。 * @returns {function} 样式函数。 */ getStyleFunction() { return this.styleFunction_; } /** * @function OverlayGraphic.createStyleFunction * @description 新建样式函数。 * @param {Object} obj - 对象参数。 */ static createStyleFunction(obj) { var styleFunction; if (typeof obj === 'function') { if (obj.length == 2) { styleFunction = function (resolution) { return (obj)(this, resolution); }; } else { styleFunction = obj; } } else { var styles; if (Array.isArray(obj)) { styles = obj; } else { styles = [obj]; } styleFunction = function () { return styles; }; } return styleFunction; } /** * @function OverlayGraphic.prototype.destroy * @description 清除参数值。 */ destroy() { this.id = null; this.geometry_ = null; this.attributes = null; this.style_ = null; } } ;// CONCATENATED MODULE: external "ol.geom.Polygon" const external_ol_geom_Polygon_namespaceObject = ol.geom.Polygon; var external_ol_geom_Polygon_default = /*#__PURE__*/__webpack_require__.n(external_ol_geom_Polygon_namespaceObject); ;// CONCATENATED MODULE: external "ol.layer.Image" const external_ol_layer_Image_namespaceObject = ol.layer.Image; var external_ol_layer_Image_default = /*#__PURE__*/__webpack_require__.n(external_ol_layer_Image_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/overlay/Graphic.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ const defaultProps = { color: [0, 0, 0, 255], opacity: 0.8, radius: 10, radiusScale: 1, radiusMinPixels: 0, radiusMaxPixels: Number.MAX_SAFE_INTEGER, strokeWidth: 1, outline: false }; const Renderer = ['canvas', 'webgl']; /** * @class Graphic * @browsernamespace ol.source * @category Visualization Graphic * @classdesc 高效率点图层源。 * @param {Object} options - 参数。 * @param {ol.Map} options.map - openlayers 地图对象。 * @param {OverlayGraphic} options.graphics - 高效率点图层点要素。 * @param {string} [options.render ='canvas'] - 指定使用的渲染器。可选值:"webgl","canvas"(webgl 渲染目前只支持散点)。 * @param {boolean} [options.isHighLight=true] - 事件响应是否支持要素高亮。 * @param {ol.style.Style} [options.highLightStyle=defaultHighLightStyle] - 高亮风格。 * @param {Array.} [options.color=[0, 0, 0, 255]] - 要素颜色。当 {@link OverlayGraphic} 的 style 参数传入设置了 fill 的 {@link HitCloverShape} 或 {@link CloverShape},此参数无效。 * @param {Array.} [options.highlightColor] - webgl 渲染时要素高亮颜色。 * @param {number} [options.opacity=0.8] - 要素透明度。当 {@link OverlayGraphic} 的 style 参数传入设置了 fillOpacity 或 strokeOpacity 的 {@link HitCloverShape} 或 {@link CloverShape},此参数无效。 * @param {number} [options.radius=10] - 要素半径,单位像素。当 {@link OverlayGraphic} 的 style 参数传入设置了 radius 的 {@link HitCloverShape} 或 {@link CloverShape},此参数无效。 * @param {number} [options.radiusScale=1] - webgl 渲染时的要素放大倍数。 * @param {number} [options.radiusMinPixels=0] - webgl 渲染时的要素半径最小值(像素)。 * @param {number} [options.radiusMaxPixels=Number.MAX_SAFE_INTEGER] - webgl 渲染时的要素半径最大值(像素)。 * @param {number} [options.strokeWidth=1] - 边框大小。 * @param {boolean} [options.outline=false] - 是否显示边框。 * @param {function} [options.onHover] - 图层鼠标悬停响应事件(只有 webgl 渲染时有用)。 * @param {function} [options.onClick] - 图层鼠标点击响应事件(webgl、canvas 渲染时都有用)。 * @extends {ol.source.ImageCanvas} * @usage */ class Graphic extends (external_ol_source_ImageCanvas_default()) { constructor(options) { super({ attributions: options.attributions, canvasFunction: canvasFunctionInternal_, logo: core_Util_Util.getOlVersion() === '4' ? options.logo : null, projection: options.projection, ratio: options.ratio, resolutions: options.resolutions, state: options.state }); this.graphics = [].concat(options.graphics); this.map = options.map; Util.extend(this, options); this.render = options.render || Renderer[0]; if (!core_Util_Util.supportWebGL2()) { this.render = Renderer[0]; } this.highLightStyle = options.highLightStyle; //是否支持高亮,默认支持 this.isHighLight = typeof options.isHighLight === 'undefined' ? true : options.isHighLight; this.hitGraphicLayer = null; this._forEachFeatureAtCoordinate = _forEachFeatureAtCoordinate; this._options = options; const me = this; if (options.onClick) { me.map.on('click', function(e) { if (me.isDeckGLRender) { const params = me.renderer.deckGL.pickObject({ x: e.pixel[0], y: e.pixel[1] }); options.onClick(params); return; } const graphic = me.findGraphicByPixel(e, me); if (graphic) { options.onClick(graphic, e); if (me.isHighLight) { me._highLight( graphic.getGeometry().getCoordinates(), new (external_ol_style_Style_default())({ image: graphic.getStyle() }).getImage(), graphic, e.pixel ); } } }); } me.map.on('pointermove', function(e) { if (me.isDeckGLRender) { const params = me.renderer.deckGL.pickObject({ x: e.pixel[0], y: e.pixel[1] }); if (options.onHover) { options.onHover(params); } } }); //eslint-disable-next-line no-unused-vars function canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { var mapWidth = size[0] / pixelRatio; var mapHeight = size[1] / pixelRatio; var width = me.map.getSize()[0]; var height = me.map.getSize()[1]; if (!me.renderer) { me.renderer = createRenderer(size, pixelRatio); } me.renderer.mapWidth = mapWidth; me.renderer.mapHeight = mapHeight; me.renderer.pixelRatio = pixelRatio; me.renderer.offset = [(mapWidth - width) / 2, (mapHeight - height) / 2]; let graphics = this.getGraphicsInExtent(extent); me.renderer._clearBuffer(); me.renderer.selected = this.selected; me.renderer.drawGraphics(graphics); me.isDeckGLRender = me.renderer instanceof GraphicWebGLRenderer; if(me.isDeckGLRender){ if (!me.context) { me.context = core_Util_Util.createCanvasContext2D(mapWidth, mapHeight); } return me.context.canvas; } return me.renderer.getCanvas(); } function createRenderer(size, pixelRatio) { let renderer; if (me.render === Renderer[0]) { renderer = new GraphicCanvasRenderer(me, { size, pixelRatio }); } else { let optDefault = Util.extend({}, defaultProps); let opt = Util.extend(optDefault, { color: me.color, opacity: me.opacity, radius: me.radius, radiusScale: me.radiusScale, radiusMinPixels: me.radiusMinPixels, radiusMaxPixels: me.radiusMaxPixels, strokeWidth: me.strokeWidth, outline: me.outline, onClick: me.onClick, onHover: me.onHover }); opt = Util.extend(me, opt); opt.pixelRatio = pixelRatio; opt.container = me.map.getViewport().getElementsByClassName('ol-overlaycontainer')[0]; opt.onBeforeRender = function() { return false; }; opt.onAfterRender = function() { return false; }; renderer = new GraphicWebGLRenderer(me, opt); } return renderer; } /** * @private * @function Graphic.prototype._forEachFeatureAtCoordinate * @description 获取在视图上的要素。 * @param {string} coordinate -坐标。 * @param {number} resolution -分辨率。 * @param {RequestCallback} callback -回调函数。 * @param {ol.Pixel} evtPixel - 当前选中的屏幕像素坐标。 */ function _forEachFeatureAtCoordinate(coordinate, resolution, callback, evtPixel, e) { let graphics = me.getGraphicsInExtent(); // FIX 无法高亮元素 me._highLightClose(); for (let i = graphics.length - 1; i >= 0; i--) { let style = graphics[i].getStyle(); if (!style) { return; } //已经被高亮的graphics 不被选选中 if (style instanceof HitCloverShape) { continue; } let center = graphics[i].getGeometry().getCoordinates(); let image = new (external_ol_style_Style_default())({ image: style }).getImage(); let contain = false; //icl-1047 当只有一个叶片的时候,判断是否选中的逻辑处理的更准确一点 if (image instanceof CloverShape && image.getCount() === 1) { const ratation = (image.getRotation() * 180) / Math.PI; const angle = Number.parseFloat(image.getAngle()); const r = image.getRadius() * resolution; //if(image.getAngle() ) let geo = null; if (angle > 355) { geo = new (external_ol_style_Circle_default())(center, r); } else { const coors = []; coors.push(center); const perAngle = angle / 8; for (let index = 0; index < 8; index++) { const radian = ((ratation + index * perAngle) / 180) * Math.PI; coors.push([center[0] + r * Math.cos(radian), center[1] - r * Math.sin(radian)]); } coors.push(center); geo = new (external_ol_geom_Polygon_default())([coors]); } if (geo.intersectsCoordinate(this.map.getCoordinateFromPixel(evtPixel))) { contain = true; } } else { let extent = []; extent[0] = center[0] - image.getAnchor()[0] * resolution; extent[2] = center[0] + image.getAnchor()[0] * resolution; extent[1] = center[1] - image.getAnchor()[1] * resolution; extent[3] = center[1] + image.getAnchor()[1] * resolution; if (external_ol_extent_namespaceObject.containsCoordinate(extent, coordinate)) { contain = true; } } if (contain === true) { if (callback) { callback(graphics[i], e); } continue; } // if (me.isHighLight) { // // me._highLightClose(); // } } return undefined; } } findGraphicByPixel(e, me) { const features = me.map.getFeaturesAtPixel(e.pixel) || []; for (let index = 0; index < features.length; index++) { const graphic = features[index]; if (me.graphics.indexOf(graphic) > -1) { return graphic; } } return undefined; } /** * @function Graphic.prototype.setGraphics * @description 设置绘制的点要素,会覆盖之前的所有要素。 * @param {Array.} graphics - 点要素对象数组。 */ setGraphics(graphics) { this.graphics = this.graphics || []; this.graphics.length = 0; let sGraphics = !core_Util_Util.isArray(graphics) ? [graphics] : [].concat(graphics); this.graphics = [].concat(sGraphics); this.update(); } /** * @function Graphic.prototype.addGraphics * @description 追加点要素,不会覆盖之前的要素。 * @param {Array.} graphics - 点要素对象数组。 */ addGraphics(graphics) { this.graphics = this.graphics || []; let sGraphics = !core_Util_Util.isArray(graphics) ? [graphics] : [].concat(graphics); this.graphics = this.graphics.concat(sGraphics); this.update(); } /** * @function Graphic.prototype.getGraphicBy * @description 在 Vector 的要素数组 graphics 里面遍历每一个 graphic,当 graphic[property]===value 时,返回此 graphic(并且只返回第一个)。 * @param {string} property - graphic 的属性名称。 * @param {string} value - property 所对应的值。 * @returns {OverlayGraphic} 一个匹配的 graphic。 */ getGraphicBy(property, value) { let graphic = null; for (let index in this.graphics) { if (this.graphics[index][property] === value) { graphic = this.graphics[index]; break; } } return graphic; } /** * @function Graphic.prototype.getGraphicById * @description 通过给定一个 ID,返回对应的矢量要素。 * @param {string} graphicId - 矢量要素的属性 ID。 * @returns {OverlayGraphic} 一个匹配的 graphic。 */ getGraphicById(graphicId) { return this.getGraphicBy('id', graphicId); } /** * @function Graphic.prototype.getGraphicsByAttribute * @description 通过给定一个属性的 key 值和 value 值,返回所有匹配的要素数组。 * @param {string} attrName - graphic 的某个属性名称。 * @param {string} attrValue - property 所对应的值。 * @returns {Array.} 一个匹配的 graphic 数组。 */ getGraphicsByAttribute(attrName, attrValue) { var graphic, foundgraphics = []; for (let index in this.graphics) { graphic = this.graphics[index]; if (graphic && graphic.attributes) { if (graphic.attributes[attrName] === attrValue) { foundgraphics.push(graphic); } } } return foundgraphics; } /** * @function Graphic.prototype.removeGraphics * @description 删除要素数组,默认将删除所有要素。 * @param {Array.} [graphics] - 删除的 graphics 数组。 */ removeGraphics(graphics = null) { //当 graphics 为 null 、为空数组,或 === this.graphics,则清除所有要素 if (!graphics || graphics.length === 0 || graphics === this.graphics) { this.graphics.length = 0; this.update(); return; } if (!Util.isArray(graphics)) { graphics = [graphics]; } for (let i = graphics.length - 1; i >= 0; i--) { let graphic = graphics[i]; //如果我们传入的grapchic在graphics数组中没有的话,则不进行删除, //并将其放入未删除的数组中。 let findex = Util.indexOf(this.graphics, graphic); if (findex === -1) { continue; } this.graphics.splice(findex, 1); } //删除完成后重新设置 setGraphics,以更新 this.update(); } /** * @function Graphic.prototype.clear * @description 释放图层资源。 */ clear() { this.removeGraphics(); } /** * @function Graphic.prototype.update * @description 更新图层。 */ update() { this.renderer.update(this.graphics, this._getDefaultStyle()); } _getDefaultStyle() { const target = {}; if (this.color) { target.fill = new (external_ol_style_Fill_default())({ color: this.toRGBA(this.color) }); } if (this.radius) { target.radius = this.radius; } if (this.outline) { target.stroke = new (external_ol_style_Fill_default())({ color: this.toRGBA(this.color), width: this.strokeWidth }); } return new (external_ol_style_Circle_default())(target); } toRGBA(colorArray) { return `rgba(${colorArray[0]},${colorArray[1]},${colorArray[2]},${(colorArray[3] || 255) / 255})`; } /** * @function Graphic.prototype.setStyle * @description 设置图层要素整体样式(接口仅在 webgl 渲染时有用)。 * @param {Object} styleOptions - 样式对象。 * @param {Array.} [styleOptions.color=[0, 0, 0, 255]] - 点颜色。 * @param {number} [styleOptions.radius=10] - 点半径。 * @param {number} [styleOptions.opacity=0.8] - 不透明度。 * @param {Array} [styleOptions.highlightColor] - 高亮颜色,目前只支持 rgba 数组。 * @param {number} [styleOptions.radiusScale=1] - 点放大倍数。 * @param {number} [styleOptions.radiusMinPixels=0] - 半径最小值(像素)。 * @param {number} [styleOptions.radiusMaxPixels=Number.MAX_SAFE_INTEGER] - 半径最大值(像素)。 * @param {number} [styleOptions.strokeWidth=1] - 边框大小。 * @param {boolean} [styleOptions.outline=false] - 是否显示边框。 */ setStyle(styleOptions) { let self = this; let styleOpt = { color: self.color, radius: self.radius, opacity: self.opacity, highlightColor: self.highlightColor, radiusScale: self.radiusScale, radiusMinPixels: self.radiusMinPixels, radiusMaxPixels: self.radiusMaxPixels, strokeWidth: self.strokeWidth, outline: self.outline }; Util.extend(self, Util.extend(styleOpt, styleOptions)); self.update(); } /** * @function Graphic.prototype.getLayerState * @description 获取当前地图及图层状态。 * @returns {Object} 地图及图层状态,包含地图状态信息和本图层相关状态。 */ getLayerState() { let map = this.map; let width = map.getSize()[0]; let height = map.getSize()[1]; let view = map.getView(); let center = view.getCenter(); let longitude = center[0]; let latitude = center[1]; let zoom = view.getZoom(); let maxZoom = view.getMaxZoom(); let rotationRadians = view.getRotation(); let rotation = (-rotationRadians * 180) / Math.PI; let mapViewport = { longitude: longitude, latitude: latitude, zoom: zoom, maxZoom: maxZoom, pitch: 0, bearing: rotation }; let state = {}; for (let key in mapViewport) { state[key] = mapViewport[key]; } state.width = width; state.height = height; state.color = this.color; state.radius = this.radius; state.opacity = this.opacity; state.highlightColor = this.highlightColor; state.radiusScale = this.radiusScale; state.radiusMinPixels = this.radiusMinPixels; state.radiusMaxPixels = this.radiusMaxPixels; state.strokeWidth = this.strokeWidth; state.outline = this.outline; return state; } /** * @function Graphic.prototype._highLightClose * @description 关闭高亮要素显示。 * @private */ _highLightClose() { this.selected = null; if (this.hitGraphicLayer) { this.map.removeLayer(this.hitGraphicLayer); this.hitGraphicLayer = null; } this.changed(); } /** * @function Graphic.prototype._highLight * @description 高亮显示选中要素。 * @param {Array.} center - 中心点。 * @param {ol.style.Style} image - 点样式。 * @param {OverlayGraphic} selectGraphic - 高效率点图层点要素。 * @param {ol.Pixel} evtPixel - 当前选中的屏幕像素坐标。 * @private */ _highLight(center, image, selectGraphic, evtPixel) { if (selectGraphic.getStyle() instanceof CloverShape) { if (this.hitGraphicLayer) { this.map.removeLayer(this.hitGraphicLayer); this.hitGraphicLayer = null; } var pixel = this.map.getPixelFromCoordinate([center[0], center[1]]); //点击点与中心点的角度 evtPixel = evtPixel || [0, 0]; var angle = (Math.atan2(evtPixel[1] - pixel[1], evtPixel[0] - pixel[0]) / Math.PI) * 180; angle = angle > 0 ? angle : 360 + angle; //确定扇叶 var index = Math.ceil(angle / (image.getAngle() + image.getSpaceAngle())); //扇叶的起始角度 var sAngle = (index - 1) * (image.getAngle() + image.getSpaceAngle()); //渲染参数 var opts = { stroke: new (external_ol_style_Stroke_default())({ color: '#ff0000', width: 1 }), fill: new (external_ol_style_Fill_default())({ color: '#0099ff' }), radius: image.getRadius(), angle: image.getAngle(), eAngle: sAngle + image.getAngle(), sAngle: sAngle, rotation: image.getRotation() }; if (this.highLightStyle && this.highLightStyle instanceof HitCloverShape) { opts.stroke = this.highLightStyle.getStroke(); opts.fill = this.highLightStyle.getFill(); opts.radius = this.highLightStyle.getRadius(); opts.angle = this.highLightStyle.getAngle(); } var hitGraphic = new Graphic_Graphic(new (external_ol_geom_Point_default())(center)); hitGraphic.setStyle(new HitCloverShape(opts)); this.hitGraphicLayer = new (external_ol_layer_Image_default())({ source: new Graphic({ map: this.map, graphics: [hitGraphic] }) }); this.map.addLayer(this.hitGraphicLayer); } else { this.selected = selectGraphic; this.changed(); } } /** * @function Graphic.prototype.getGraphicsInExtent * @description 在指定范围中获取几何要素面积。 * @param {Object} extent - 长度范围。 */ getGraphicsInExtent(extent) { var graphics = []; if (!extent) { this.graphics.forEach(graphic => { graphics.push(graphic); }); return graphics; } this.graphics.forEach(graphic => { if (external_ol_extent_namespaceObject.containsExtent(extent, graphic.getGeometry().getExtent())) { graphics.push(graphic); } }); return graphics; } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/theme/GeoFeature.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class GeoFeature * @browsernamespace ol.source * @category Visualization Theme * @classdesc 地理几何专题要素型专题图层基类。 * @param {string} name - 图层名称。 * @param {Object} opt_options - 参数。 * @param {ol.Map} opt_options.map - 当前 OpenLayers Map 对象。 * @param {string} [opt_options.id] - 专题图层 ID。默认使用 CommonUtil.createUniqueID("themeLayer_") 创建专题图层 ID。 * @param {number} [opt_options.opacity=1] - 图层透明度。 * @param {string} [opt_options.logo] - Logo(openLayers 5.0.0 及更高版本不再支持此参数)。 * @param {ol.proj.Projection} [opt_options.projection] - 投影信息。 * @param {number} [opt_options.ratio=1.5] - 视图比,1 表示画布是地图视口的大小,2 表示地图视口的宽度和高度的两倍,依此类推。必须是 1 或更高。 * @param {Array} [opt_options.resolutions] - 分辨率数组。 * @param {ol.source.State} [opt_options.state] - 资源状态。 * @param {Object} [opt_options.style] - 专题图样式。 * @param {Object} [opt_options.styleGroups] - 各专题类型样式组。 * @param {boolean} [opt_options.isHoverAble=false] - 是否开启 hover 事件。 * @param {Object} [opt_options.highlightStyle] - 开启 hover 事件后,触发的样式风格。 * @param {(string|Object)} [opt_options.attributions='Map Data © SuperMap iServer with © SuperMap iClient'] - 版权信息。 * @extends {Theme} * @usage */ class GeoFeature extends theme_Theme_Theme { constructor(name, opt_options) { super(name, opt_options); this.cache = opt_options.cache || {}; this.cacheFields = opt_options.cacheFields || []; this.style = opt_options.style || {}; this.maxCacheCount = opt_options.maxCacheCount || 0; this.isCustomSetMaxCacheCount = opt_options.isCustomSetMaxCacheCount === undefined ? false : opt_options.isCustomSetMaxCacheCount; this.nodesClipPixel = opt_options.nodesClipPixel || 2; this.isHoverAble = opt_options.isHoverAble === undefined ? false : opt_options.isHoverAble; this.isMultiHover = opt_options.isMultiHover === undefined ? false : opt_options.isMultiHover; this.isClickAble = opt_options.isClickAble === undefined ? true : opt_options.isClickAble; this.highlightStyle = opt_options.highlightStyle || null; this.isAllowFeatureStyle = opt_options.isAllowFeatureStyle === undefined ? false : opt_options.isAllowFeatureStyle; } /** * @function GeoFeature.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.maxCacheCount = null; this.isCustomSetMaxCacheCount = null; this.nodesClipPixel = null; this.isHoverAble = null; this.isMultiHover = null; this.isClickAble = null; this.cache = null; this.cacheFields = null; this.style = null; this.highlightStyle = null; this.isAllowFeatureStyle = null; } /** * @function GeoFeature.prototype.addFeatures * @description 添加要素。 * @param {(Array.|Array.|Array.|ThemeFeature|GeoJSONObject|ol.Feature)} features - 要素对象。 */ addFeatures(features) { this.dispatchEvent({type: 'beforefeaturesadded', value: {features: features}}); //转换 features 形式 this.features = this.toiClientFeature(features); if (!this.isCustomSetMaxCacheCount) { this.maxCacheCount = this.features.length * 5; } //绘制专题要素 if (this.renderer) { this.changed(); } } /** * @function GeoFeature.prototype.removeFeatures * @description 从专题图中删除 feature。这个函数删除所有传递进来的矢量要素。 * @param {(Array.|FeatureVector|Function)} features - 待删除的要素对象或用于过滤的回调函数。 */ removeFeatures(features) { // eslint-disable-line no-unused-vars this.clearCache(); theme_Theme_Theme.prototype.removeFeatures.call(this, features); } /** * @function GeoFeature.prototype.removeAllFeatures * @description 清除当前图层所有的矢量要素。 */ removeAllFeatures() { this.clearCache(); theme_Theme_Theme.prototype.removeAllFeatures.apply(this, arguments); } /** * @function GeoFeature.prototype.redrawThematicFeatures * @description 重绘所有专题要素。 * @param {Object} extent - 视图范围数据。 */ redrawThematicFeatures(extent) { //获取高亮专题要素对应的用户 id var hoverone = this.renderer.getHoverOne(); var hoverFid = null; if (hoverone && hoverone.refDataID) { hoverFid = hoverone.refDataID; } //清除当前所有可视元素 this.renderer.clearAll(); var features = this.features; var cache = this.cache; var cacheFields = this.cacheFields; var cmZoom = this.map.getView().getZoom(); var maxCC = this.maxCacheCount; for (var i = 0, len = features.length; i < len; i++) { var feature = features[i]; if (!feature.geometry) { continue; } var feaBounds = feature.geometry.getBounds(); //剔除当前视图(地理)范围以外的数据 if (extent) { var bounds = new Bounds(extent[0], extent[1], extent[2], extent[3]); if (!bounds.intersectsBounds(feaBounds)) { continue; } } //缓存字段 var fields = feature.id + "_zoom_" + cmZoom.toString(); var thematicFeature; //判断专题要素缓存是否存在 if (cache[fields]) { cache[fields].updateAndAddShapes(); } else { //如果专题要素缓存不存在,创建专题要素 thematicFeature = this.createThematicFeature(features[i]); //检查 thematicFeature 是否有可视化图形 if (thematicFeature.getShapesCount() < 1) { continue; } //加入缓存 cache[fields] = thematicFeature; cacheFields.push(fields); //缓存数量限制 if (cacheFields.length > maxCC) { var fieldsTemp = cacheFields[0]; cacheFields.splice(0, 1); delete cache[fieldsTemp]; } } } this.renderer.render(); //地图漫游后,重新高亮图形 if (hoverFid && this.isHoverAble && this.isMultiHover) { var hShapes = this.getShapesByFeatureID(hoverFid); this.renderer.updateHoverShapes(hShapes); } } /** * @function GeoFeature.prototype.createThematicFeature * @description 创建专题要素。 * @param {Object} feature - 要素对象。 * @returns {Array.} 返回矢量要素。 */ createThematicFeature(feature) { var style = Util.copyAttributesWithClip(this.style); if (feature.style && this.isAllowFeatureStyle === true) { style = Util.copyAttributesWithClip(feature.style); } //创建专题要素时的可选参数 var options = {}; options.nodesClipPixel = this.nodesClipPixel; options.isHoverAble = this.isHoverAble; options.isMultiHover = this.isMultiHover; options.isClickAble = this.isClickAble; options.highlightStyle = ShapeFactory.transformStyle(this.highlightStyle); //将数据转为专题要素(Vector) var thematicFeature = new ThemeVector(feature, this, ShapeFactory.transformStyle(style), options); //直接添加图形到渲染器 for (var m = 0; m < thematicFeature.shapes.length; m++) { this.renderer.addShape(thematicFeature.shapes[m]); } return thematicFeature; } canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars return theme_Theme_Theme.prototype.canvasFunctionInternal_.apply(this, arguments); } /** * @function GeoFeature.prototype.clearCache * @description 清除缓存。 */ clearCache() { this.cache = {}; this.cacheFields = []; } /** * @function GeoFeature.prototype.clear * @description 清除的内容包括数据(features)、专题要素、缓存。 */ clear() { this.renderer.clearAll(); this.renderer.refresh(); this.removeAllFeatures(); this.clearCache(); } /** * @function GeoFeature.prototype.getCacheCount * @description 获取当前缓存数量。 * @returns {number} 返回当前缓存数量。 */ getCacheCount() { return this.cacheFields.length; } /** * @function GeoFeature.prototype.setMaxCacheCount * @param {number} cacheCount - 缓存总数。 * @description 设置最大缓存条数。 */ setMaxCacheCount(cacheCount) { if (!isNaN(cacheCount)) { this.maxCacheCount = cacheCount; this.isCustomSetMaxCacheCount = true; } } /** * @function GeoFeature.prototype.getShapesByFeatureID * @param {number} featureID - 要素 ID。 * @description 通过 FeatureID 获取 feature 关联的所有图形。如果不传入此参数,函数将返回所有图形。 * @returns {Array} 返回图形数组。 */ getShapesByFeatureID(featureID) { var list = []; var shapeList = this.renderer.getAllShapes(); if (!featureID) { return shapeList } for (var i = 0, len = shapeList.length; i < len; i++) { var si = shapeList[i]; if (si.refDataID && featureID === si.refDataID) { list.push(si); } } return list; } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/Label.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Label * @browsernamespace ol.source * @category Visualization Theme * @classdesc 标签专题图图层源。 * @param {string} name - 名称。 * @param {Object} opt_options - 参数。 * @param {ol.Map} opt_options.map - 当前 Map 对象。 * @param {string} [opt_options.id] - 专题图层 ID。默认使用 CommonUtil.createUniqueID("themeLayer_") 创建专题图层 ID。 * @param {number} [opt_options.opacity=1] - 图层透明度。 * @param {string|Object} [opt_options.attributions] - 版权信息。 * @param {string} [opt_options.logo] - Logo(openLayers 5.0.0 及更高版本不再支持此参数)。 * @param {ol.proj.Projection} [opt_options.projection] - 投影信息。 * @param {number} [opt_options.ratio=1.5] - 视图比,1 表示画布是地图视口的大小,2 表示地图视口的宽度和高度的两倍,依此类推。必须是1或更高。 * @param {Array.} [opt_options.resolutions] - 分辨率数组。 * @param {ol.source.State} [opt_options.state] - 资源状态。 * @param {string} [opt_options.themeField] - 指定创建专题图字段。 * @param {Object} [opt_options.style] - 专题图样式。 * @param {Object} [opt_options.styleGroups] - 各专题类型样式组。 * @param {boolean} [opt_options.isHoverAble = false] - 是否开启 hover 事件。 * @param {Object} [opt_options.highlightStyle] - 开启 hover 事件后,触发的样式风格。 * @extends {GeoFeature} * @usage */ class Label_Label extends GeoFeature { constructor(name, opt_options) { super(name, opt_options); this.isOverLay = opt_options.isOverLay != null ? opt_options.isOverLay : true; this.isAvoid = opt_options.isAvoid != null ? opt_options.isAvoid : true; this.style = opt_options.style; this.themeField = opt_options.themeField; this.styleGroups = opt_options.styleGroups; this.defaultStyle = { //默认文本样式 fontColor: "#000000", fontOpacity: 1, fontSize: "12px", fontStyle: "normal", fontWeight: "normal", labelAlign: "cm", labelXOffset: 0, labelYOffset: 0, labelRotation: 0, //默认背景框样式 fill: false, fillColor: "#ee9900", fillOpacity: 0.4, stroke: false, strokeColor: "#ee9900", strokeOpacity: 1, strokeWidth: 1, strokeLinecap: "round", strokeDashstyle: "solid", //对用户隐藏但必须保持此值的属性 //cursor: "pointer", labelSelect: true, //用 _isGeoTextStrategyStyle 标记此style,携带此类style的要素特指GeoText策略中的标签要素 _isGeoTextStrategyStyle: true }; //获取标签像素 bounds 的方式。0 - 表示通过文本类容和文本风格计算获取像素范围,现在支持中文、英文; 1 - 表示通过绘制的文本标签获取像素范围,支持各个语种的文字范围获取,但性能消耗较大(尤其是采用SVG渲染)。默认值为0。 this.getPxBoundsMode = 0; this.labelFeatures = []; } /** * @function Label.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.style = null; this.themeField = null; this.styleGroups = null; super.destroy(); } /** * @private * @function Label.prototype.createThematicFeature * @description 创建专题要素。 * @param {FeatureVector} feature - 矢量要素。 * @returns {FeatureThemeVector} 专题图矢量要素。 */ createThematicFeature(feature) { //赋 style var style = this.getStyleByData(feature); //创建专题要素时的可选参数 var options = {}; options.nodesClipPixel = this.nodesClipPixel; options.isHoverAble = this.isHoverAble; options.isMultiHover = this.isMultiHover; options.isClickAble = this.isClickAble; options.highlightStyle = ShapeFactory.transformStyle(this.highlightStyle); //将数据转为专题要素(Vector) var thematicFeature = new ThemeVector(feature, this, ShapeFactory.transformStyle(style), options); //直接添加图形到渲染器 for (var m = 0; m < thematicFeature.shapes.length; m++) { this.renderer.addShape(thematicFeature.shapes[m]); } return thematicFeature; } /** * @function Label.prototype.redrawThematicFeatures * @description 重绘所有专题要素。 * 此方法包含绘制专题要素的所有步骤,包含用户数据到专题要素的转换,抽稀,缓存等步骤。 * 地图漫游时调用此方法进行图层刷新。 * @param {Array.} bounds - 重绘范围。 */ redrawThematicFeatures(bounds) { if (this.features.length > 0 && this.labelFeatures.length === 0) { var feats = this.setLabelsStyle(this.features); for (var i = 0, len = feats.length; i < len; i++) { this.labelFeatures.push(feats[i]); } } this.features = this.getDrawnLabels(this.labelFeatures); super.redrawThematicFeatures.call(this, bounds); } /** * @function Label.prototype.removeFeatures * @description 从专题图中删除 feature。这个函数删除所有传递进来的矢量要素。 * @param {(Array.|FeatureVector|Function)} features - 待删除的要素对象或用于过滤的回调函数。 */ removeFeatures(features) { // eslint-disable-line no-unused-vars this.labelFeatures = []; super.removeFeatures.call(this, features); } /** * @function Label.prototype.removeAllFeatures * @description 清除当前图层所有的矢量要素。 */ removeAllFeatures() { this.labelFeatures = []; super.removeAllFeatures.call(this, arguments); } /** * @function Label.prototype.getDrawnLabels * @description 获取经(压盖)处理后将要绘制在图层上的标签要素。 * @param {Array.} labelFeatures - 所有标签要素的数组。 * @returns {Array.} 最终要绘制的标签要素数组。 */ getDrawnLabels(labelFeatures) { var feas = [], //最终要绘制的标签要素集 fea, //最终要绘制的标签要素 fi, //临时标签要素,用户的第i个标签 labelsB = [], //不产生压盖的标签要素范围集 styTmp, //用于临时存储要素style的变量 feaSty, //标签要素最终的style // styleTemp用于屏蔽文本style中带有偏移性质style属性,偏移已经在计算bounds的过程中参与了运算, // 所以在最终按照bounds来绘制标签时,需屏蔽style中带有偏移性质属性,否则文本的偏移量将扩大一倍。 styleTemp = { labelAlign: "cm", labelXOffset: 0, labelYOffset: 0 }; var map = this.map; var mapSize = map.getSize(); mapSize = { x: mapSize[0], y: mapSize[1] }; var zoom = map.getView().getZoom(); //对用户的每个标签要素进行处理与判断 for (var i = 0, len = labelFeatures.length; i < len; i++) { fi = labelFeatures[i]; //检查fi的style在避让中是否被改变,如果改变,重新设置要素的style if (fi.isStyleChange) { fi = this.setStyle(fi); } //标签最终的中心点像素位置 (偏移后) var loc = this.getLabelPxLocation(fi); //过滤掉地图范围外的标签 (偏移后) if ((loc.x >= 0 && loc.x <= mapSize.x) && (loc.y >= 0 && loc.y <= mapSize.y)) { //根据当前地图缩放级别过滤标签 if (fi.style.minZoomLevel > -1) { if (zoom <= fi.style.minZoomLevel) { continue; } } if (fi.style.maxZoomLevel > -1) { if (zoom > fi.style.maxZoomLevel) { continue; } } //计算标签bounds var boundsQuad = null; if (fi.isStyleChange) { fi.isStyleChange = null; boundsQuad = this.calculateLabelBounds(fi, loc); } else { if (fi.geometry.bsInfo.w && fi.geometry.bsInfo.h) { //使用calculateLabelBounds2可以提高bounds的计算效率,尤其是在getPxBoundsMode = 1时 boundsQuad = this.calculateLabelBounds2(fi, loc); } else { boundsQuad = this.calculateLabelBounds(fi, loc); } } //避让处理 -start var mapViewBounds = new Bounds(0, mapSize.y, mapSize.x, 0), //地图像素范围 quadlen = boundsQuad.length; if (this.isAvoid) { var avoidInfo = this.getAvoidInfo(mapViewBounds, boundsQuad); //避让信息 if (avoidInfo) { //横向(x方向)上的避让 if (avoidInfo.aspectW === "left") { fi.style.labelXOffset += avoidInfo.offsetX; for (let j = 0; j < quadlen; j++) { boundsQuad[j].x += avoidInfo.offsetX; } } else if (avoidInfo.aspectW === "right") { fi.style.labelXOffset += (-avoidInfo.offsetX); for (let j = 0; j < quadlen; j++) { boundsQuad[j].x += (-avoidInfo.offsetX); } } //纵向(y方向)上的避让 if (avoidInfo.aspectH === "top") { fi.style.labelYOffset += avoidInfo.offsetY; for (let j = 0; j < quadlen; j++) { boundsQuad[j].y += avoidInfo.offsetY; } } else if (avoidInfo.aspectH === "bottom") { fi.style.labelYOffset += (-avoidInfo.offsetY); for (let j = 0; j < quadlen; j++) { boundsQuad[j].y += (-avoidInfo.offsetY); } } //如果style发生变化,记录下来 fi.isStyleChange = true; } } //避让处理 -end //压盖处理 -start if (this.isOverLay) { //是否压盖 var isOL = false; if (i != 0) { for (let j = 0; j < labelsB.length; j++) { //压盖判断 if (this.isQuadrilateralOverLap(boundsQuad, labelsB[j])) { isOL = true; break; } } } if (isOL) { continue; } else { labelsB.push(boundsQuad); } } //压盖处理 -end //将标签像素范围转为地理范围 var geoBs = []; for (let j = 0; j < quadlen - 1; j++) { geoBs.push(map.getCoordinateFromPixel([boundsQuad[j].x, boundsQuad[j].y])); } //屏蔽有偏移性质的style属性,偏移量在算bounds时已经加入计算 var bounds = new Bounds(geoBs[3][0], geoBs[3][1], geoBs[1][0], [geoBs[1][1]]); var center = bounds.getCenterLonLat(); var label = new GeoText(center.lon, center.lat, fi.attributes[this.themeField]); label.calculateBounds(); styTmp = Util.cloneObject(fi.style); feaSty = Util.cloneObject(Util.copyAttributes(styTmp, styleTemp)); fea = new Vector(label, fi.attributes, feaSty); //赋予id fea.id = fi.id; fea.fid = fi.fid; feas.push(fea); } } //返回最终要绘制的标签要素 return feas; } /** * @function Label.prototype.getStyleByData * @description 根据用户数据(feature)设置专题要素的 Style。 * @param {FeatureVector} feat - 矢量要素对象。 * @returns {Array.} 专题要素的 Style。 */ getStyleByData(feat) { var feature = feat; feature.style = Util.copyAttributes(feature.style, this.defaultStyle); //将style赋给标签 if (this.style && this.style.fontSize && parseFloat(this.style.fontSize) < 12) { this.style.fontSize = "12px"; } feature.style = Util.copyAttributes(feature.style, this.style); if (this.themeField && this.styleGroups && feature.attributes) { var Sf = this.themeField; var attributes = feature.attributes; var groups = this.styleGroups; var isSfInAttrs = false; //指定的 groupField 是否是geotext的属性字段之一 var attr = null; //属性值 for (var property in attributes) { if (Sf === property) { isSfInAttrs = true; attr = attributes[property]; break; } } //判断属性值是否属于styleGroups的某一个范围,以便对标签分组 if (isSfInAttrs) { for (var i = 0, len = groups.length; i < len; i++) { if ((attr >= groups[i].start) && (attr < groups[i].end)) { var sty1 = groups[i].style; if (sty1 && sty1.fontSize && parseFloat(sty1.fontSize) < 12) { sty1.fontSize = "12px"; } feature.style = Util.copyAttributes(feature.style, sty1); } } } feature.style.label = feature.attributes[this.themeField] } return feature.style; } /** * @function Label.prototype.setLabelsStyle * @description 设置标签要素的 Style。 * @param {Array.} labelFeatures - 需要设置 Style 的标签要素数组。 * @returns {Array.} 赋予 Style 后的标签要素数组。 */ setLabelsStyle(labelFeatures) { var fea, labelFeas = []; for (var i = 0, len = labelFeatures.length; i < len; i++) { var feature = labelFeatures[i]; if (feature.geometry.CLASS_NAME === "SuperMap.Geometry.GeoText") { //设置标签的Style if (feature.geometry.bsInfo.w || feature.geometry.bsInfo.h) { feature.geometry.bsInfo.w = null; feature.geometry.bsInfo.h = null; feature.geometry.labelWTmp = null; } fea = this.setStyle(feature); //为标签要素指定图层 fea.layer = this.layer; labelFeas.push(fea); } else { return labelFeatures; } } return labelFeas; } /** * @function Label.prototype.setStyle * @description 设置标签要素的 Style。 * @param {FeatureVector} feat - 需要赋予 style 的要素。 */ setStyle(feat) { var feature = feat; feature.style = Util.copyAttributes(feature.style, this.defaultStyle); //将style赋给标签 if (this.style && this.style.fontSize && parseFloat(this.style.fontSize) < 12) { this.style.fontSize = "12px"; } feature.style = Util.copyAttributes(feature.style, this.style); if (this.groupField && this.styleGroups && feature.attributes) { var Sf = this.groupField; var attributes = feature.attributes; var groups = this.styleGroups; var isSfInAttrs = false; //指定的 groupField 是否是geotext的属性字段之一 var attr = null; //属性值 for (var property in attributes) { if (Sf === property) { isSfInAttrs = true; attr = attributes[property]; break; } } //判断属性值是否属于styleGroups的某一个范围,以便对标签分组 if (isSfInAttrs) { for (var i = 0, len = groups.length; i < len; i++) { if ((attr >= groups[i].start) && (attr < groups[i].end)) { var sty1 = groups[i].style; if (sty1 && sty1.fontSize && parseFloat(sty1.fontSize) < 12) { sty1.fontSize = "12px"; } feature.style = Util.copyAttributes(feature.style, sty1); } } } } //将文本内容赋到标签要素的style上 feature.style.label = feature.geometry.text; return feature; } /** * @function Label.prototype.getLabelPxLocation * @description 获取标签要素的像素坐标。 * @param {FeatureVector} feature - 标签要素。 * @returns {Object} 标签位置,例如:{"x":1,"y":1}。 */ getLabelPxLocation(feature) { var geoText = feature.geometry; var styleTmp = feature.style; //将标签的地理位置转为像素位置 var locationTmp = geoText.getCentroid(); var locTmp = this.map.getPixelFromCoordinate([locationTmp.x, locationTmp.y]); var loc = new (external_ol_geom_Point_default())([locTmp[0], locTmp[1]]); //偏移处理 if (styleTmp.labelXOffset || styleTmp.labelYOffset) { var xOffset = isNaN(styleTmp.labelXOffset) ? 0 : styleTmp.labelXOffset; var yOffset = isNaN(styleTmp.labelYOffset) ? 0 : styleTmp.labelYOffset; loc.translate(xOffset, -yOffset); } return { x: loc.getCoordinates()[0], y: loc.getCoordinates()[1] }; } /** * @function Label.prototype.calculateLabelBounds * @description 获得标签要素的最终范围。 * @param {FeatureVector} feature - 需要计算bounds的标签要素数。 * @param {Object} loc - 标签位置,例如:{"x":1,"y":1}。 * @returns {Array.} 四边形节点数组。例如:[{"x":1,"y":1},{"x":3,"y":1},{"x":6,"y":4},{"x":2,"y":10},{"x":1,"y":1}]。 */ calculateLabelBounds(feature, loc) { var geoText = feature.geometry; //标签范围(未旋转前) var labB = null; var labelInfo = null; //获取bounds的方式 if (this.getPxBoundsMode == 0) { labB = geoText.getLabelPxBoundsByText(loc, feature.style); } else if (this.getPxBoundsMode === 1) { //canvas labelInfo = this.getLabelInfo(feature.geometry.getCentroid(), feature.style); labB = geoText.getLabelPxBoundsByLabel(loc, labelInfo.w, labelInfo.h, feature.style); } else { return null; } //旋转Bounds var boundsQuad = []; if ((feature.style.labelRotation % 180) == 0) { boundsQuad = [{ "x": labB.left, "y": labB.top }, { "x": labB.right, "y": labB.top }, { "x": labB.right, "y": labB.bottom }, { "x": labB.left, "y": labB.bottom }, { "x": labB.left, "y": labB.top } ]; } else { boundsQuad = this.rotationBounds(labB, loc, feature.style.labelRotation); } //重置GeoText的bounds geoText.bounds = new Bounds(boundsQuad[1].x, boundsQuad[3].y, boundsQuad[2].x, boundsQuad[4].y); return boundsQuad; } /** * @function Label.prototype.calculateLabelBounds2 * @description 获得标签要素的最终范围的另一种算法(通过记录下的标签宽高),提高计算 bounds 的效率。 * @param {FeatureVector} feature - 需要计算 bounds 的标签要素数。 * @param {Object} loc - 标签位置,例如:{"x":1,"y":1}。 * @returns {Array.} 四边形节点数组。例如:[{"x":1,"y":1},{"x":3,"y":1},{"x":6,"y":4},{"x":2,"y":10},{"x":1,"y":1}]。 */ calculateLabelBounds2(feature, loc) { var labB, left, bottom, top, right; var labelSize = feature.geometry.bsInfo; var style = feature.style; var locationPx = Util.cloneObject(loc); //处理文字对齐 if (style.labelAlign && style.labelAlign !== "cm") { switch (style.labelAlign) { case "lt": locationPx.x += labelSize.w / 2; locationPx.y += labelSize.h / 2; break; case "lm": locationPx.x += labelSize.w / 2; break; case "lb": locationPx.x += labelSize.w / 2; locationPx.y -= labelSize.h / 2; break; case "ct": locationPx.y += labelSize.h / 2; break; case "cb": locationPx.y -= labelSize.h / 2; break; case "rt": locationPx.x -= labelSize.w / 2; locationPx.y += labelSize.h / 2; break; case "rm": locationPx.x -= labelSize.w / 2; break; case "rb": locationPx.x -= labelSize.w / 2; locationPx.y -= labelSize.h / 2; break; default: break; } } left = locationPx.x - labelSize.w / 2; bottom = locationPx.y + labelSize.h / 2; //处理斜体字 if (style.fontStyle && style.fontStyle === "italic") { right = locationPx.x + labelSize.w / 2 + parseInt(parseFloat(style.fontSize) / 2); } else { right = locationPx.x + labelSize.w / 2; } top = locationPx.y - labelSize.h / 2; labB = new Bounds(left, bottom, right, top); //旋转Bounds var boundsQuad = []; if ((style.labelRotation % 180) == 0) { boundsQuad = [{ "x": labB.left, "y": labB.top }, { "x": labB.right, "y": labB.top }, { "x": labB.right, "y": labB.bottom }, { "x": labB.left, "y": labB.bottom }, { "x": labB.left, "y": labB.top } ]; } else { boundsQuad = this.rotationBounds(labB, loc, style.labelRotation); } //重置GeoText的bounds feature.geometry.bounds = new Bounds(boundsQuad[1].x, boundsQuad[3].y, boundsQuad[2].x, boundsQuad[4].y); return boundsQuad; } /** * @function Label.prototype.getLabelInfo * @description 根据当前位置获取绘制后的标签信息,包括标签的宽,高和行数等。 * @returns {Object} 绘制后的标签信息。 */ getLabelInfo(location, style) { var LABEL_ALIGN = { "l": "left", "r": "right", "t": "top", "b": "bottom" }, LABEL_FACTOR = { "l": 0, "r": -1, "t": 0, "b": -1 }; style = Util.extend({ fontColor: "#000000", labelAlign: "cm" }, style); var pt = this.getLocalXY(location); var labelWidth = 0; if (style.labelXOffset || style.labelYOffset) { var xOffset = isNaN(style.labelXOffset) ? 0 : style.labelXOffset; var yOffset = isNaN(style.labelYOffset) ? 0 : style.labelYOffset; pt[0] += xOffset; pt[1] -= yOffset; } var canvas = document.createElement('canvas'); canvas.globalAlpha = 0; canvas.lineWidth = 1; var ctx = canvas.getContext("2d"); ctx.fillStyle = style.fontColor; ctx.globalAlpha = style.fontOpacity || 1.0; var fontStyle = [style.fontStyle ? style.fontStyle : "normal", "normal", style.fontWeight ? style.fontWeight : "normal", style.fontSize ? style.fontSize : "1em", style.fontFamily ? style.fontFamily : "sans-serif" ].join(" "); var labelRows = style.label.split('\n'); var numRows = labelRows.length; var vfactor, lineHeight, labelWidthTmp; if (ctx.fillText) { // HTML5 ctx.font = fontStyle; ctx.textAlign = LABEL_ALIGN[style.labelAlign[0]] || "center"; ctx.textBaseline = LABEL_ALIGN[style.labelAlign[1]] || "middle"; vfactor = LABEL_FACTOR[style.labelAlign[1]]; if (vfactor == null) { vfactor = -.5; } lineHeight = ctx.measureText('Mg').height || ctx.measureText('xx').width; pt[1] += lineHeight * vfactor * (numRows - 1); for (let i = 0; i < numRows; i++) { labelWidthTmp = ctx.measureText(labelRows[i]).width; if (labelWidth < labelWidthTmp) { labelWidth = labelWidthTmp; } } } else if (ctx.mozDrawText) { // Mozilla pre-Gecko1.9.1 (} bounds 旋转后形成的多边形节点数组。是一个四边形,形如:[{"x":1,"y":1},{"x":3,"y":1},{"x":6,"y":4},{"x":2,"y":10},{"x":1,"y":1}]。 */ rotationBounds(bounds, rotationCenterPoi, angle) { var ltPoi = new (external_ol_geom_Point_default())([bounds.left, bounds.top]); var rtPoi = new (external_ol_geom_Point_default())([bounds.right, bounds.top]); var rbPoi = new (external_ol_geom_Point_default())([bounds.right, bounds.bottom]); var lbPoi = new (external_ol_geom_Point_default())([bounds.left, bounds.bottom]); var ver = []; ver.push(this.getRotatedLocation(ltPoi.getCoordinates()[0], ltPoi.getCoordinates()[1], rotationCenterPoi.x, rotationCenterPoi.y, angle)); ver.push(this.getRotatedLocation(rtPoi.getCoordinates()[0], rtPoi.getCoordinates()[1], rotationCenterPoi.x, rotationCenterPoi.y, angle)); ver.push(this.getRotatedLocation(rbPoi.getCoordinates()[0], rbPoi.getCoordinates()[1], rotationCenterPoi.x, rotationCenterPoi.y, angle)); ver.push(this.getRotatedLocation(lbPoi.getCoordinates()[0], lbPoi.getCoordinates()[1], rotationCenterPoi.x, rotationCenterPoi.y, angle)); //bounds旋转后形成的多边形节点数组 var quad = []; for (var i = 0; i < ver.length; i++) { quad.push({ "x": ver[i].x, "y": ver[i].y }); } quad.push({ "x": ver[0].x, "y": ver[0].y }); return quad; } /** * @function Label.prototype.getRotatedLocation * @description 获取一个点绕旋转中心顺时针旋转后的位置。(此方法用于屏幕坐标)。 * @param {number} x - 旋转点横坐标。 * @param {number} y - 旋转点纵坐标。 * @param {number} rx - 旋转中心点横坐标。 * @param {number} ry - 旋转中心点纵坐标。 * @param {number} angle - 旋转角度 * @returns {Object} 旋转后的坐标位置对象,该对象含有属性 x(横坐标),属性 y(纵坐标)。 */ getRotatedLocation(x, y, rx, ry, angle) { var loc = {}, x0, y0; y = -y; ry = -ry; angle = -angle; //顺时针旋转 x0 = (x - rx) * Math.cos((angle / 180) * Math.PI) - (y - ry) * Math.sin((angle / 180) * Math.PI) + rx; y0 = (x - rx) * Math.sin((angle / 180) * Math.PI) + (y - ry) * Math.cos((angle / 180) * Math.PI) + ry; loc.x = x0; loc.y = -y0; return loc; } /** * @function Label.prototype.getAvoidInfo * @description 获取避让的信息。 * @param {Bounds} bounds - 地图像素范围。 * @param {Array.} quadrilateral - 四边形节点数组。例如:[{"x":1,"y":1},{"x":3,"y":1},{"x":6,"y":4},{"x":2,"y":10},{"x":1,"y":1}]。 * @returns {Object} 避让的信息。 */ getAvoidInfo(bounds, quadrilateral) { if (quadrilateral.length !== 5) { return null; } //不是四边形 //将bound序列化为点数组形式 var bounddQuad = [{ "x": bounds.left, "y": bounds.top }, { "x": bounds.right, "y": bounds.top }, { "x": bounds.right, "y": bounds.bottom }, { "x": bounds.left, "y": bounds.bottom }, { "x": bounds.left, "y": bounds.top } ]; var isIntersection = false, bqLen = bounddQuad.length, quadLen = quadrilateral.length; var offsetX = 0, offsetY = 0, aspectH = "", aspectW = ""; for (var i = 0; i < bqLen - 1; i++) { for (var j = 0; j < quadLen - 1; j++) { var isLineIn = Util.lineIntersection(bounddQuad[i], bounddQuad[i + 1], quadrilateral[j], quadrilateral[j + 1]); if (isLineIn.CLASS_NAME === "SuperMap.Geometry.Point") { //设置避让信息 setInfo(quadrilateral[j]); setInfo(quadrilateral[j + 1]); isIntersection = true; } } } if (isIntersection) { //组织避让操作所需的信息 return { "aspectW": aspectW, "aspectH": aspectH, "offsetX": offsetX, "offsetY": offsetY }; } else { return null; } //内部函数:设置避让信息 //参数:vec-{Object} quadrilateral四边形单个节点。如:{"x":1,"y":1}。 function setInfo(vec) { //四边形不在bounds内的节点 if (!bounds.contains(vec.x, vec.y)) { //bounds的Top边 if (vec.y < bounds.top) { let oY = Math.abs(bounds.top - vec.y); if (oY > offsetY) { offsetY = oY; aspectH = "top"; } } //bounds的Bottom边 if (vec.y > bounds.bottom) { let oY = Math.abs(vec.y - bounds.bottom); if (oY > offsetY) { offsetY = oY; aspectH = "bottom"; } } //bounds的left边 if (vec.x < bounds.left) { let oX = Math.abs(bounds.left - vec.x); if (oX > offsetX) { offsetX = oX; aspectW = "left"; } } //bounds的right边 if (vec.x > bounds.right) { let oX = Math.abs(vec.x - bounds.right); if (oX > offsetX) { offsetX = oX; aspectW = "right"; } } } } } /** * @function Label.prototype.isQuadrilateralOverLap * @description 判断两个四边形是否有压盖。 * @param {Array.} quadrilateral - 四边形节点数组。例如:[{"x":1,"y":1},{"x":3,"y":1},{"x":6,"y":4},{"x":2,"y":10},{"x":1,"y":1}]。 * @param {Array.} quadrilateral2 - 第二个四边形节点数组。 * @returns {boolean} 是否压盖,true 表示压盖。 */ isQuadrilateralOverLap(quadrilateral, quadrilateral2) { var quadLen = quadrilateral.length, quad2Len = quadrilateral2.length; if (quadLen !== 5 || quad2Len !== 5) { return null; } //不是四边形 var OverLap = false; //如果两四边形互不包含对方的节点,则两个四边形不相交 for (let i = 0; i < quadLen; i++) { if (this.isPointInPoly(quadrilateral[i], quadrilateral2)) { OverLap = true; break; } } for (let i = 0; i < quad2Len; i++) { if (this.isPointInPoly(quadrilateral2[i], quadrilateral)) { OverLap = true; break; } } //加上两矩形十字相交的情况 for (let i = 0; i < quadLen - 1; i++) { if (OverLap) { break; } for (var j = 0; j < quad2Len - 1; j++) { var isLineIn = Util.lineIntersection(quadrilateral[i], quadrilateral[i + 1], quadrilateral2[j], quadrilateral2[j + 1]); if (isLineIn.CLASS_NAME === "SuperMap.Geometry.Point") { OverLap = true; break; } } } return OverLap; } /** * @function Label.prototype.isPointInPoly * @description 判断一个点是否在多边形里面(射线法)。 * @param {Object} pt - 需要判定的点对象,该对象含有属性 x(横坐标),属性 y(纵坐标)。 * @param {Array.} poly - 多边形节点数组。例如一个四边形:[{"x":1,"y":1},{"x":3,"y":1},{"x":6,"y":4},{"x":2,"y":10},{"x":1,"y":1}]。 * @returns {boolean} 点是否在多边形内。 */ isPointInPoly(pt, poly) { for (var isIn = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) { ((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y)) && (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x) && (isIn = !isIn); } return isIn; } canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars return super.canvasFunctionInternal_.apply(this, arguments); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/mapv/MapvCanvasLayer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MapvCanvasLayer * @classdesc Mapv 渲染器。 * @private * @param {Object} options - 参数。 * @param {number} options.width - 画布宽。 * @param {number} options.height - 画布高。 * @param {string} [options.paneName='mapPane'] - 窗口名。 * @param {string} [options.context='2d'] - 内容。 * @param {number} [options.zIndex=2] - 层级。 * @param {string} [options.mixBlendMode] - 最小混合模式。 */ class MapvCanvasLayer { constructor(options) { this.options = options || {}; this.enableMassClear = this.options.enableMassClear; this._map = options.map; this.paneName = this.options.paneName || 'mapPane'; this.context = this.options.context || '2d'; this.zIndex = this.options.zIndex || 2; this.mixBlendMode = this.options.mixBlendMode || null; this.width = options.width; this.height = options.height; this.initialize(); } initialize() { var canvas = this.canvas = document.createElement("canvas"); canvas.style.cssText = "position:absolute;" + "left:0;" + "top:0;" + "z-index:" + this.zIndex + ";user-select:none;"; canvas.style.mixBlendMode = this.mixBlendMode; canvas.className = "mapvClass"; var global$2 = typeof window === 'undefined' ? {} : window; var devicePixelRatio = this.devicePixelRatio = global$2.devicePixelRatio || 1; canvas.width = parseInt(this.width) * devicePixelRatio; canvas.height = parseInt(this.height) * devicePixelRatio; if (this.context === '2d') { canvas.getContext(this.context).scale(devicePixelRatio, devicePixelRatio); } canvas.style.width = this.width + "px"; canvas.style.height = this.height + "px"; if (this.context === 'webgl') { this.canvas.getContext(this.context).viewport(0, 0, canvas.width, canvas.height) } } /** * @function MapvCanvasLayer.prototype.draw * @description 生成地图。 */ draw() { this.options.update && this.options.update.call(this); } /** * @function MapvCanvasLayer.prototype.resize * @param {number} mapWidth - 地图宽度。 * @param {number} mapHeight - 地图高度。 * @description 调整地图大小。 */ resize(mapWidth, mapHeight) { var global$2 = typeof window === 'undefined' ? {} : window; var devicePixelRatio = this.devicePixelRatio = global$2.devicePixelRatio || 1; this.canvas.width = mapWidth * devicePixelRatio; this.canvas.height = mapHeight * devicePixelRatio; if (this.context === '2d') { this.canvas.getContext('2d').scale(devicePixelRatio, devicePixelRatio); } this.canvas.style.width = mapWidth + "px"; this.canvas.style.height = mapHeight + "px"; if (this.context === 'webgl') { this.canvas.getContext(this.context).viewport(0, 0, this.canvas.width, this.canvas.height) } } /** * @function MapvCanvasLayer.prototype.getContainer * @description 获取容器。 * @returns {HTMLElement} 包含 Mapv 图层的 DOM 对象。 */ getContainer() { return this.canvas; } /** * @function MapvCanvasLayer.prototype.setZIndex * @param {number} zIndex - 层级参数。 * @description 设置图层层级。 */ setZIndex(zIndex) { this.canvas.style.zIndex = zIndex; } /** * @function MapvCanvasLayer.prototype.getZIndex * @description 获取图层层级。 */ getZIndex() { return this.zIndex; } } ;// CONCATENATED MODULE: external "function(){try{return mapv}catch(e){return {}}}()" const external_function_try_return_mapv_catch_e_return_namespaceObject = function(){try{return mapv}catch(e){return {}}}(); ;// CONCATENATED MODULE: external "ol.interaction.Pointer" const external_ol_interaction_Pointer_namespaceObject = ol.interaction.Pointer; var external_ol_interaction_Pointer_default = /*#__PURE__*/__webpack_require__.n(external_ol_interaction_Pointer_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/overlay/mapv/MapvLayer.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ var BaiduMapLayer = external_function_try_return_mapv_catch_e_return_namespaceObject.baiduMapLayer ? external_function_try_return_mapv_catch_e_return_namespaceObject.baiduMapLayer.__proto__ : Function; /** * @class MapvLayer * @classdesc MapV 图层类。 * @private * @param {Object} map - 地图。 * @param {Mapv.DataSet} [dataSet] - 数据集。 * @param {Object} options - 参数。 * @param {number} mapWidth - 地图宽度。 * @param {number} mapHeight - 地图高度。 * @param {Object} source - 资源。 * @param {number} options.width - 画布宽。 * @param {number} options.height - 画布高。 * @param {string} [options.paneName='mapPane'] - 窗口名。 * @param {string} [options.context] - 内容。 * @param {number} [options.zIndex] - 层级。 * @param {string} [options.mixBlendMode] - 最小混合模式。 * @extends {Mapv.BaiduMapLayer} */ class MapvLayer extends BaiduMapLayer { constructor(map, dataSet, options, mapWidth, mapHeight, source) { super(map, dataSet, options); this.dataSet = dataSet; this.mapWidth = mapWidth; this.mapHeight = mapHeight; var self = this; options = options || {}; this.source = source; self.animator = null; self.map = map; self.init(options); self.argCheck(options); this.canvasLayer = new MapvCanvasLayer({ map: map, context: this.context, paneName: options.paneName, mixBlendMode: options.mixBlendMode, enableMassClear: options.enableMassClear, zIndex: options.zIndex, width: mapWidth, height: mapHeight, update: function update() { self._canvasUpdate(); } }); this.clickEvent = this.clickEvent.bind(this); this.mousemoveEvent = this.mousemoveEvent.bind(this); map.on('movestart', this.moveStartEvent.bind(this)); map.on('moveend', this.moveEndEvent.bind(this)); map.getView().on('change:center', this.zoomEvent.bind(this)); map.getView().on('change:size', this.sizeEvent.bind(this)); map.on('pointerdrag', this.dragEvent.bind(this)); this.bindEvent(); } /** * @function MapvLayer.prototype.init * @param {Object} options - 参数。 * @description 初始化参数。 */ init(options) { var self = this; self.options = options; this.initDataRange(options); this.context = self.options.context || '2d'; if (self.options.zIndex) { this.canvasLayer && this.canvasLayer.setZIndex(self.options.zIndex); } this.initAnimator(); } /** * @function MapvLayer.prototype.clickEvent * @param {Object} e - 事件参数。 * @description 点击事件。 */ clickEvent(e) { var pixel = e.pixel; super.clickEvent({ x: pixel[0] + this.offset[0], y: pixel[1] + this.offset[1] }, e); } /** * @function MapvLayer.prototype.mousemoveEvent * @param {Object} e - 事件参数。 * @description 鼠标移动事件。 */ mousemoveEvent(e) { var pixel = e.pixel; super.mousemoveEvent({ x: pixel[0], y: pixel[1] }, e); } /** * @function MapvLayer.prototype.dragEvent * @description 鼠标拖动事件。 */ dragEvent() { this.clear(this.getContext()); } /** * @function MapvLayer.prototype.zoomEvent * @description 缩放事件。 */ zoomEvent() { this.clear(this.getContext()); } /** * @function MapvLayer.prototype.sizeEvent * @description 地图窗口大小发生变化时触发。 */ sizeEvent() { this.canvasLayer.resize(); } /** * @function MapvLayer.prototype.moveStartEvent * @description 开始移动事件。 */ moveStartEvent() { var animationOptions = this.options.animation; if (this.isEnabledTime() && this.animator) { this.steps.step = animationOptions.stepsRange.start; } } /** * @function MapvLayer.prototype.moveEndEvent * @description 结束移动事件。 */ moveEndEvent() { this.canvasLayer.draw(); } /** * @function MapvLayer.prototype.bindEvent * @description 绑定事件。 */ bindEvent() { var me = this; var map = me.map; if (me.options.methods) { if (me.options.methods.click) { map.on('click', me.clickEvent); } if (me.options.methods.mousemove) { me.pointerInteraction = new (external_ol_interaction_Pointer_default())(); me.pointerInteraction.handleMoveEvent_ = function (event) { me.mousemoveEvent(event); }; map.addInteraction(me.pointerInteraction); } } } /** * @function MapvLayer.prototype.unbindEvent * @description 解除绑定事件。 */ unbindEvent() { var map = this.map; if (this.options.methods) { if (this.options.methods.click) { map.un('click', this.clickEvent); } if (this.options.methods.mousemove) { map.removeInteraction(this.pointerInteraction) } } } /** * @function MapvLayer.prototype.addData * @description 添加数据。 * @param {Object} data - 待添加的数据。 * @param {Object} options - 待添加的数据信息。 */ addData(data, options) { var _data = data; if (data && data.get) { _data = data.get(); } this.dataSet.add(_data); this.update({ options: options }); } /** * @function MapvLayer.prototype.update * @description 更新图层。 * @param {Object} opt - 待更新的数据。 * @param {Object} opt.data - mapv 数据集。 */ update(opt) { var update = opt || {}; var _data = update.data; if (_data && _data.get) { _data = _data.get(); } if (_data != undefined) { this.dataSet.set(_data); } super.update({ options: update.options }); } draw() { this.canvasLayer.draw(); } /** * @function MapvLayer.prototype.getData * @description 获取数据。 */ getData() { return this.dataSet; } /** * @function MapvLayer.prototype.removeData * @description 删除符合过滤条件的数据。 * @param {function} filter - 过滤条件。条件参数为数据项,返回值为 true,表示删除该元素;否则表示不删除。 */ removeData(filter) { if (!this.dataSet) { return; } var newData = this.dataSet.get({ filter: function (data) { return (filter != null && typeof filter === "function") ? !filter(data) : true; } }); this.dataSet.set(newData); this.update({ options: null }); } /** * @function MapvLayer.prototype.clearData * @description 清除数据。 */ clearData() { this.dataSet && this.dataSet.clear(); this.update({ options: null }); } _canvasUpdate(time) { if (!this.canvasLayer) { return; } var self = this; var animationOptions = self.options.animation; var map = self.map; var context = self.canvasLayer.canvas.getContext(self.context); if (self.isEnabledTime()) { if (time === undefined) { self.clear(context); return; } if (!self.context || self.context === '2d') { context.save(); context.globalCompositeOperation = 'destination-out'; context.fillStyle = 'rgba(0, 0, 0, .1)'; context.fillRect(0, 0, context.canvas.width, context.canvas.height); context.restore(); } } else { this.clear(context); } if (!self.context || self.context === '2d') { for (var key in self.options) { context[key] = self.options[key]; } } else { context.clear(context.COLOR_BUFFER_BIT); } var ext = map.getView().calculateExtent(); var topLeftPx = map.getPixelFromCoordinate([ext[0], ext[3]]); self._mapCenter = map.getView().getCenter(); self._mapCenterPx = map.getPixelFromCoordinate(self._mapCenter); self._reselutions = map.getView().getResolution(); self._rotation = -map.getView().getRotation(); var zoomUnit = self._reselutions; var scaleRatio = 1; if (this.context != '2d') { var global$2 = typeof window === 'undefined' ? {} : window; var devicePixelRatio = global$2.devicePixelRatio || 1; scaleRatio = devicePixelRatio; } var dataGetOptions = { transferCoordinate: function (coordinate) { var x = (coordinate[0] - self._mapCenter[0]) / self._reselutions, y = (self._mapCenter[1] - coordinate[1]) / self._reselutions; var scaledP = [x + self._mapCenterPx[0], y + self._mapCenterPx[1]]; scaledP = scale(scaledP, self._mapCenterPx, 1); /*//有旋转量的时候处理旋转 if (self._rotation !== 0) { var rotatedP = rotate(scaledP, self._rotation, self._mapCenterPx); return [rotatedP[0] + self.offset[0], rotatedP[1] + self.offset[1]]; } //处理放大或缩小级别*/ return [(scaledP[0] + self.offset[0]) * scaleRatio, (scaledP[1] + self.offset[1]) * scaleRatio]; } }; // //获取某像素坐标点pixelP绕中心center逆时针旋转rotation弧度后的像素点坐标。 // function rotate(pixelP, rotation, center) { // var x = Math.cos(rotation) * (pixelP[0] - center[0]) - Math.sin(rotation) * (pixelP[1] - center[1]) + center[0]; // var y = Math.sin(rotation) * (pixelP[0] - center[0]) + Math.cos(rotation) * (pixelP[1] - center[1]) + center[1]; // return [x, y]; // } //获取某像素坐标点pixelP相对于中心center进行缩放scaleRatio倍后的像素点坐标。 function scale(pixelP, center, scaleRatio) { var x = (pixelP[0] - center[0]) * scaleRatio + center[0]; var y = (pixelP[1] - center[1]) * scaleRatio + center[1]; return [x, y]; } if (time !== undefined) { dataGetOptions.filter = function (item) { var trails = animationOptions.trails || 10; return (time && item.time > (time - trails) && item.time < time); }; } if (self.isEnabledTime() && !self.notFirst) { self.canvasLayer.resize(self.mapWidth, self.mapHeight); self.notFirst = true; } var data = self.dataSet.get(dataGetOptions); self.processData(data); // 兼容unit为'm'的情况 if (self.options.unit === 'm') { if (self.options.size) { self.options._size = self.options.size / zoomUnit; } if (self.options.width) { self.options._width = self.options.width / zoomUnit; } if (self.options.height) { self.options._height = self.options.height / zoomUnit; } } else { self.options._size = self.options.size; self.options._height = self.options.height; self.options._width = self.options.width; } var pixel = map.getPixelFromCoordinate([0, 0]); pixel = [pixel[0] - topLeftPx[0], pixel[1] - topLeftPx[1]]; this.drawContext(context, data, self.options, { x: pixel[0], y: pixel[1] }); if (self.isEnabledTime()) { this.source.changed(); } self.options.updateCallback && self.options.updateCallback(time); } isEnabledTime() { var animationOptions = this.options.animation; return animationOptions && !(animationOptions.enabled === false); } argCheck(options) { if (options.draw === 'heatmap') { if (options.strokeStyle) { console.warn('[heatmap] options.strokeStyle is discard, pleause use options.strength [eg: options.strength = 0.1]'); } } } getContext() { return this.canvasLayer.canvas.getContext(this.context); } clear(context) { context && context.clearRect && context.clearRect(0, 0, context.canvas.width, context.canvas.height); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/Mapv.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Mapv * @browsernamespace ol.source * @category Visualization MapV * @classdesc MapV 图层源。 * @param {Object} opt_options - 参数。 * @param {ol.Map} opt_options.map - 当前 Map 对象。 * @param {Mapv.DataSet} opt_options.dataSet - MapV 的数据集。 * @param {Object} opt_options.mapvOptions - MapV 的配置对象。 * @param {string} [opt_options.logo] - Logo(openLayers 5.0.0 及更高版本不再支持此参数)。 * @param {ol.proj.Projection} [opt_options.projection] - 投影信息。 * @param {number} [opt_options.ratio=1.5] - 视图比,1 表示画布是地图视口的大小,2 表示地图视口的宽度和高度的两倍,依此类推。必须是 1 或更高。 * @param {Array} [opt_options.resolutions] - 分辨率数组。 * @param {ol.source.State} [opt_options.state] - 资源状态。 * @param {(string|Object)} [opt_options.attributions='© 2018 百度 MapV with © SuperMap iClient'] - 版权信息。 * @extends {ol.source.ImageCanvas} * @usage */ class Mapv extends (external_ol_source_ImageCanvas_default()) { constructor(opt_options) { var options = opt_options ? opt_options : {}; super({ attributions: options.attributions || "© 2018 百度 MapV with © SuperMap iClient", canvasFunction: canvasFunctionInternal_, logo: core_Util_Util.getOlVersion() === '4' ? options.logo : null, projection: options.projection, ratio: options.ratio, resolutions: options.resolutions, state: options.state }); this.map = opt_options.map; this.dataSet = opt_options.dataSet; this.mapvOptions = opt_options.mapvOptions; function canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars var mapWidth = size[0] / pixelRatio; var mapHeight = size[1] / pixelRatio; var width = this.map.getSize()[0]; var height = this.map.getSize()[1]; if (!this.layer) { this.layer = new MapvLayer(this.map, this.dataSet, this.mapvOptions, mapWidth, mapHeight, this); } this.layer.pixelRatio = pixelRatio; this.layer.offset = [(mapWidth - width) / 2 , (mapHeight - height) / 2 ]; if (!this.rotate) { this.rotate = this.map.getView().getRotation(); } else { if (this.rotate !== this.map.getView().getRotation()) { this.layer.canvasLayer.resize(mapWidth, mapHeight); this.rotate = this.map.getView().getRotation() } } var canvas = this.layer.canvasLayer.canvas; if (!this.layer.isEnabledTime()) { this.layer.canvasLayer.resize(mapWidth, mapHeight); this.layer.canvasLayer.draw(); } if (!this.context) { this.context = core_Util_Util.createCanvasContext2D(mapWidth, mapHeight); } var canvas2 = this.context.canvas; this.context.clearRect(0, 0, canvas2.width, canvas2.height); canvas2.width = size[0]; canvas2.height = size[1]; canvas2.style.width = size[0] + "px"; canvas2.style.height = size[1] + "px"; this.context.drawImage(canvas, 0, 0); if (this.resolution !== resolution || JSON.stringify(this.extent) !== JSON.stringify(extent)) { this.resolution = resolution; this.extent = extent; } return this.context.canvas; } } /** * @function Mapv.prototype.addData * @description 追加数据。 * @param {Object} data - 要追加的数据。 * @param {Object} options - 要追加的值。 */ addData(data, options) { this.layer.addData(data, options); } /** * @function Mapv.prototype.getData * @description 获取数据。 * @returns {Mapv.DataSet} MapV 数据集。 */ getData() { if (this.layer) { this.dataSet = this.layer.getData(); } return this.dataSet; } /** * @function Mapv.prototype.removeData * @description 删除符合过滤条件的数据。 * @param {function} filter - 过滤条件。条件参数为数据项,返回值为 true,表示删除该元素;否则表示不删除。 * @example * filter=function(data){ * if(data.id=="1"){ * return true * } * return false; * } */ removeData(filter) { this.layer && this.layer.removeData(filter); } /** * @function Mapv.prototype.clearData * @description 清除数据。 */ clearData() { this.layer.clearData(); } /** * @function Mapv.prototype.update * @description 更新数据。 * @param {Object} options - 待更新的数据。 * @param {Object} options.data - mapv 数据集。 */ update(options) { this.layer.update(options); this.changed(); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/Range.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Range * @browsernamespace ol.source * @category Visualization Theme * @classdesc 分段专题图图层源。 * @param {string} name - 名称 * @param {Object} opt_options - 参数。 * @param {ol.Map} opt_options.map - 当前map对象。 * @param {string} opt_options.themeField - 指定创建专题图字段。 * @param {string} [opt_options.id] - 专题图层 ID。默认使用 CommonUtil.createUniqueID("themeLayer_") 创建专题图层 ID。 * @param {number} [opt_options.opacity = 1] - 图层透明度。 * @param {string} [opt_options.logo] - Logo(openLayers 5.0.0 及更高版本不再支持此参数)。 * @param {ol.proj.Projection} [opt_options.projection] - 投影信息。 * @param {number} [opt_options.ratio=1.5] - 视图比,1 表示画布是地图视口的大小,2 表示地图视口的宽度和高度的两倍,依此类推。必须是 1 或更高。 * @param {Array} [opt_options.resolutions] - 分辨率数组。 * @param {ol.source.State} [opt_options.state] - 资源状态。 * @param {Object} [opt_options.style] - 专题图样式。 * @param {Object} [opt_options.styleGroups] - 各专题类型样式组。 * @param {boolean} [opt_options.isHoverAble = false] - 是否开启 hover 事件。 * @param {Object} [opt_options.highlightStyle] - 开启 hover 事件后,触发的样式风格。 * @param {(string|Object)} [opt_options.attributions='Map Data © SuperMap iServer with © SuperMap iClient'] - 版权信息。 * @extends {GeoFeature} * @usage */ class Range extends GeoFeature { constructor(name, opt_options) { super(name, opt_options); this.style = opt_options.style; this.isHoverAble = opt_options.isHoverAble; this.highlightStyle = opt_options.highlightStyle; this.themeField = opt_options.themeField; this.styleGroups = opt_options.styleGroups; } /** * @function Range.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.style = null; this.themeField = null; this.styleGroups = null; GeoFeature.prototype.destroy.apply(this, arguments); } /** * @private * @function Range.prototype.createThematicFeature * @description 创建专题图要素。 * @param {Object} feature - 要创建的专题图形要素。 */ createThematicFeature(feature) { //赋 style var style = this.getStyleByData(feature); //创建专题要素时的可选参数 var options = {}; options.nodesClipPixel = this.nodesClipPixel; options.isHoverAble = this.isHoverAble; options.isMultiHover = this.isMultiHover; options.isClickAble = this.isClickAble; options.highlightStyle = ShapeFactory.transformStyle(this.highlightStyle); //将数据转为专题要素(ThemeVector) var thematicFeature = new ThemeVector(feature, this, ShapeFactory.transformStyle(style), options); //直接添加图形到渲染器 for (var m = 0; m < thematicFeature.shapes.length; m++) { this.renderer.addShape(thematicFeature.shapes[m]); } return thematicFeature; } /** * @private * @function Range.prototype.getStyleByData * @description 通过数据获取 style。 * @param {Object} fea - 要素数据。 */ getStyleByData(fea) { var style = {}; var feature = fea; style = Util.copyAttributesWithClip(style, this.style); if (this.themeField && this.styleGroups && this.styleGroups.length > 0 && feature.attributes) { var Sf = this.themeField; var Attrs = feature.attributes; var Gro = this.styleGroups; var isSfInAttrs = false; //指定的 themeField 是否是 feature 的属性字段之一 var attr = null; //属性值 for (var property in Attrs) { if (Sf === property) { isSfInAttrs = true; attr = Attrs[property]; break; } } //判断属性值是否属于styleGroups的某一个范围,以便对获取分组 style if (isSfInAttrs) { for (var i = 0, len = Gro.length; i < len; i++) { if ((attr >= Gro[i].start) && (attr < Gro[i].end)) { //feature.style = Util.copyAttributes(feature.style, this.defaultStyle); var sty1 = Gro[i].style; style = Util.copyAttributesWithClip(style, sty1); } } } } if (feature.style && this.isAllowFeatureStyle === true) { style = Util.copyAttributesWithClip(feature.style); } return style; } canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars return GeoFeature.prototype.canvasFunctionInternal_.apply(this, arguments); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/RankSymbol.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class RankSymbol * @browsernamespace ol.source * @category Visualization Theme * @classdesc 等级符号专题图图层源。 * @param {string} name - 专题图层名。 * @param {string} symbolType - 标志类型。 * @param {Object} opt_options - 参数。 * @param {ol.Map} opt_options.map - 当前 Map 对象。 * @param {string} opt_options.themeFields - 指定创建专题图字段。 * @param {Object} opt_options.symbolSetting - 符号 Circle 配置对象 symbolSetting(<{@link SuperMap.Layer.RankSymbol}>)。 * @param {Array.} opt_options.symbolSetting.codomain - 图表允许展示的数据值域,长度为 2 的一维数组,第一个元素表示值域下限,第二个元素表示值域上限。 * @param {number} [opt_options.symbolSetting.maxR] - 圆形的最大半径。 * @param {number} [opt_options.symbolSetting.minR] - 圆形的最小半径。 * @param {string} [opt_options.symbolSetting.fillColor] - 圆形的填充色,如:fillColor: "#FFB980"。 * @param {Object} [opt_options.symbolSetting.circleStyle] - 圆形的基础 style,此参数控制圆形基础样式,优先级低于 circleStyleByFields 和 circleStyleByCodomain。 * @param {number} [opt_options.symbolSetting.decimalNumber] - 数据值数组 dataValues 元素值小数位数,数据的小数位处理参数,取值范围:[0, 16]。如果不设置此参数,在取数据值时不对数据做小数位处理。 * @param {Object} [opt_options.symbolSetting.circleHoverStyle] - 圆形 hover 状态时的样式,circleHoverAble 为 true 时有效。 * @param {boolean} [opt_options.symbolSetting.circleHoverAble=true] - 是否允许圆形使用 hover 状态。同时设置 circleHoverAble 和 circleClickAble 为 false,可以直接屏蔽图形对专题图层事件的响应。 * @param {boolean} [opt_options.symbolSetting.circleClickAble=true] - 是否允许圆形被点击。同时设置 circleHoverAble 和 circleClickAble 为 false,可以直接屏蔽图形对专题图层事件的响应。 * @param {string} [opt_options.id] - 专题图层 ID。默认使用 CommonUtil.createUniqueID("themeLayer_") 创建专题图层 ID。 * @param {number} [opt_options.opacity=1] - 图层透明度。 * @param {string} [opt_options.logo] - Logo(openLayers 5.0.0 及更高版本不再支持此参数)。 * @param {ol.proj.Projection} [opt_options.projection] - 投影信息。 * @param {number} [opt_options.ratio=1.5] - 视图比,1 表示画布是地图视口的大小,2 表示地图视口的宽度和高度的两倍,依此类推。必须是 1 或更高。 * @param {Array} [opt_options.resolutions] - 分辨率数组。 * @param {ol.source.State} [opt_options.state] - 资源状态。 * @param {boolean} [opt_options.isOverLay=true] - 是否进行压盖处理,如果设为 true,图表绘制过程中将隐藏对已在图层中绘制的图表产生压盖的图表。 * @param {(string|Object)} [opt_options.attributions='Map Data © SuperMap iServer with © SuperMap iClient'] - 版权信息。 * @extends {Graph} * @usage */ class RankSymbol_RankSymbol extends Graph_Graph { constructor(name, symbolType, opt_options) { super(name, symbolType, opt_options); this.symbolType = symbolType; this.symbolSetting = opt_options.symbolSetting; this.themeField = opt_options.themeField; } /** * @function RankSymbol.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.symbolType = null; this.symbolSetting = null; this.themeField = null; Graph_Graph.prototype.destroy.apply(this, arguments); } /** * @function RankSymbol.prototype.setSymbolType * @description 设置标志符号。 * @param {string} symbolType - 符号类型。 */ setSymbolType(symbolType) { this.symbolType = symbolType; this.redraw(); } /** * @private * @function RankSymbol.prototype.createThematicFeature * @description 创建专题图形要素。 * @param {Object} feature - 要创建的专题图形要素。 */ createThematicFeature(feature) { var thematicFeature; // 检查图形创建条件并创建图形 if (Theme_Theme[this.symbolType] && this.themeField && this.symbolSetting) { thematicFeature = new Theme_Theme[this.symbolType](feature, this, [this.themeField], this.symbolSetting); } // thematicFeature 是否创建成功 if (!thematicFeature) { return false; } // 对专题要素执行图形装载 thematicFeature.assembleShapes(); return thematicFeature; } canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars return Graph_Graph.prototype.canvasFunctionInternal_.apply(this, arguments); } } ;// CONCATENATED MODULE: external "function(){try{return turf}catch(e){return {}}}()" const external_function_try_return_turf_catch_e_return_namespaceObject = function(){try{return turf}catch(e){return {}}}(); ;// CONCATENATED MODULE: ./src/openlayers/overlay/Turf.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Turf * @browsernamespace ol.source * @category Visualization Turf * @classdesc Turf.js 图层源。 * @param {Object} opt_options - 参数。 * @extends {ol.source.Vector} * @usage */ class Turf extends (external_ol_source_Vector_default()) { constructor(opt_options) { var options = opt_options ? opt_options : {}; super({ attributions: options.attributions || "© turfjs with © SuperMap iClient", features: options.features, format: options.format, extent: options.extent, logo: core_Util_Util.getOlVersion() === '4' ? options.logo : null, projection: options.projection, wrapX: options.wrapX }); this.turfMap = { "Measurement.along": ["line", "distance", "units"], "Measurement.area": ["geojson"], "Measurement.bbox": ["geojson"], "Measurement.bboxPolygon": ["bbox"], "Measurement.bearing": ["start", "end", "final"], "Measurement.center": ["geojson", "properties"], "Measurement.centerOfMass": ["geojson", "properties"], "Measurement.centroid": ["geojson", "properties"], "Measurement.destination": ["origin", "distance", "bearing", "units"], "Measurement.distance": ["from", "to", "units"], "Measurement.envelope": ["geojson"], "Measurement.length": ["geojson", "units"], "Measurement.midpoint": ["point1", "point2"], "Measurement.pointOnFeature": ["geojson"], "Measurement.polygonTangents": ["point", "polygon"], "Measurement.rhumbBearing": ["start", "end", "final"], "Measurement.rhumbDestination": ["origin", "distance", "bearing", "units"], "Measurement.rhumbDistance": ["from", "to", "units"], "Measurement.square": ["bbox"], "Measurement.greatCircle": ["start", "end", "properties", "npoints", "offset"], "CoordinateMutation.cleanCoords":["geojson","mutate"], "CoordinateMutation.flip": ["geojson", "mutate"], "CoordinateMutation.rewind": ["geojson", "reverse", "mutate"], "CoordinateMutation.round": ["num", "precision"], "CoordinateMutation.truncate": ["geojson", "precision", "coordinates", "mutate"], "Transformation.bboxClip": ["feature", "bbox"], "Transformation.bezierSpline": ["line", "resolution", "sharpness"], "Transformation.buffer": ["geojson", "radius", "units", "steps"], "Transformation.circle": ["center", "radius", "steps", "units", "properties"], "Transformation.clone": ["geojson"], "Transformation.concave": ["points", "maxEdge", "units"], "Transformation.convex": ["geojson","concavity"], "Transformation.difference": ["polygon1", "polygon2"], "Transformation.dissolve": ["featureCollection", "propertyName"], "Transformation.intersect": ["poly1", "poly2"], "Transformation.lineOffset": ["geojson", "distance", "units"], "Transformation.simplify": ["feature", "tolerance", "highQuality"], "Transformation.tesselate": ["poly"], "Transformation.transformRotate": ["geojson", "angle", "pivot", "mutate"], "Transformation.transformTranslate": ["geojson", "distance", "direction", "units", "zTranslation", "mutate"], "Transformation.transformScale": ["geojson", "factor", "origin", "mutate"], "Transformation.union": ["A"], "Transformation.voronoi": ["points","bbox"], "featureConversion.combine": ["fc"], "featureConversion.explode": ["geojson"], "featureConversion.flatten": ["geojson"], "featureConversion.lineStringToPolygon": ["lines", "properties", "autoComplete", "orderCoords"], "featureConversion.polygonize": ["geojson"], "featureConversion.polygonToLineString": ["polygon", "properties"], "Misc.kinks": ["featureIn"], "Misc.lineArc": ["center", "radius", "bearing1", "bearing2", "steps", "units"], "Misc.lineChunk": ["geojson", "segmentLength", "units", "reverse"], "Misc.lineIntersect": ["line1", "line2"], "Misc.lineOverlap": ["line1", "line2"], "Misc.lineSegment": ["geojson"], "Misc.lineSlice": ["startPt", "stopPt", "line"], "Misc.lineSliceAlong": ["line", "startDist", "stopDist", "units"], "Misc.lineSplit": ["line", "splitter"], "Misc.mask": ["polygon", "mask"], "Misc.pointOnLine": ["lines", "pt", "units"], "Misc.sector": ["center", "radius", "bearing1", "bearing2", "steps", "units"], "Misc.shortestPath": ["start", "end", "obstacles", "units","resolution"], "Misc.unkinkPolygon": ["geojson"], "Helper.featureCollection": ["features","bbox","id"], "Helper.feature": ["geometry", "properties","bbox","id"], "Helper.geometryCollection": ["geometries", "properties","bbox","id"], "Helper.lineString": ["coordinates", "properties","bbox","id"], "Helper.multiLineString": ["coordinates", "properties","bbox","id"], "Helper.multiPoint": ["coordinates", "properties","bbox","id"], "Helper.multiPolygon": ["coordinates", "properties","bbox","id"], "Helper.point": ["coordinates", "properties","bbox","id"], "Helper.polygon": ["coordinates", "properties","bbox","id"], "Data.sample": ["featurecollection", "num"], "Interpolation.interpolate": ["points", "cellSize", "gridType", "property", "units", "weight"], "Interpolation.isobands": ["pointGrid", "breaks", "zProperty", "commonProperties","breaksProperties"], "Interpolation.isolines": ["pointGrid", "breaks", "zProperty", "commonProperties", "breaksProperties"], "Interpolation.planepoint": ["point", "triangle"], "Interpolation.tin": ["points", "z"], "Joins.pointsWithinPolygon": ["points", "polygons"], "Joins.tag": ["points", "polygons", "field", "outField","mask","properties"], "Grids.hexGrid": ["bbox", "cellSide", "units", "triangles"], "Grids.pointGrid": ["bbox", "cellSide", "units", "mask","properties"], "Grids.squareGrid": ["bbox", "cellSide", "units", "mask","properties"], "Grids.triangleGrid": ["bbox", "cellSide", "units", "mask","properties"], "Classification.nearestPoint": ["targetPoint", "points"], "Aggregation.collect": ["polygons", "points", "inProperty", "outProperty"], "Aggregation.clustersDbscan": ["points", "maxDistance", "units", "minPoints","mutate"], "Aggregation.clustersKmeans": ["points", "numberOfClusters", "mutate"], "Meta.coordAll": ["geojson"], "Meta.coordEach": ["geojson", "callback", "excludeWrapCoord"], "Meta.coordReduce": ["geojson", "callback", "initialValue", "excludeWrapCoord"], "Meta.featureEach": ["geojson", "callback"], "Meta.featureReduce": ["geojson", "callback", "initialValue"], "Meta.flattenEach": ["geojson", "callback"], "Meta.flattenReduce": ["geojson", "callback", "initialValue"], "Meta.getCoord": ["coord"], "Meta.getCoords": ["coords"], "Meta.getGeom": ["geojson"], "Meta.getGeomType": ["geojson","name"], "Meta.geomEach": ["geojson", "callback"], "Meta.geomReduce": ["geojson", "callback", "initialValue"], "Meta.propEach": ["geojson", "callback"], "Meta.propReduce": ["geojson", "callback", "initialValue"], "Meta.segmentEach": ["geojson", "callback"], "Meta.segmentReduce": ["geojson", "callback", "initialValue"], "Meta.getCluster": ["geojson", "filter"], "Meta.clusterEach": ["geojson", "property", "callback"], "Meta.clusterReduce": ["geojson", "property", "callback", "initialValue"], "Assertions.collectionOf": ["featureCollection", "type", "name"], "Assertions.containsNumber": ["coordinates"], "Assertions.geojsonType": ["value", "type", "name"], "Assertions.featureOf": ["feature", "type", "name"], "Booleans.booleanClockwise": ["line"], "Booleans.booleanContains": ["feature1", "feature2"], "Booleans.booleanCrosses": ["feature1", "feature2"], "Booleans.booleanDisjoint": ["feature1", "feature2"], "Booleans.booleanEqual": ["feature1", "feature2"], "Booleans.booleanOverlap": ["feature1", "feature2"], "Booleans.booleanParallel": ["feature1", "feature2"], "Booleans.booleanPointInPolygon": ["point", "polygon", "ignoreBoundary"], "Booleans.booleanPointOnLine": ["point", "linestring", "ignoreEndVertices"], "UnitConversion.bearingToAngle": ["bearing"], "UnitConversion.convertArea": ["area", "originalUnit", "finalUnit"], "UnitConversion.convertLength": ["length", "originalUnit", "finalUnit"], "UnitConversion.degreesToradians": ["degrees"], "UnitConversion.lengthToRadians": ["distance", "units"], "UnitConversion.lengthToDegrees": ["distance", "units"], "UnitConversion.radiansToLength": ["radians", "units"], "UnitConversion.radiansToDegrees": ["radians"], "UnitConversion.toMercator": ["geojson","mutate"], "UnitConversion.toWgs84": ["geojson","mutate"] }; // 5.0.0 及以上版本参数配置 this.turfOptionMap={ "Measurement.along": ["line", "distance", {units:""}], "Measurement.bboxPolygon": ["bbox",{properties:"",id:""}], "Measurement.bearing": ["start", "end", {final:""}], "Measurement.center": ["geojson", {properties:""}], "Measurement.destination": ["origin", "distance", "bearing", {units:"",properties:""}], "Measurement.distance": ["from", "to", {units:""}], "Measurement.length": ["geojson", {units:""}], "Measurement.rhumbBearing": ["start", "end", {final:""}], "Measurement.rhumbDestination": ["origin", "distance", "bearing", {units:"",properties:""}], "Measurement.rhumbDistance": ["from", "to", {units:""}], "Measurement.greatCircle": ["start", "end", {properties:"", npoints:"", offset:""}], "CoordinateMutation.cleanCoords":["geojson",{mutate:""}], "CoordinateMutation.flip": ["geojson", {mutate:""}], "CoordinateMutation.rewind": ["geojson",{mutate:"",reverse:""}], "CoordinateMutation.truncate": ["geojson", {precision:"", coordinates:"", mutate:""}], "Transformation.bezierSpline": ["line", {resolution:"", sharpness:""}], "Transformation.buffer": ["geojson", "radius", {units:"", steps:""}], "Transformation.circle": ["center", "radius", {units:"", steps:"",properties:""}], "Transformation.concave": ["points", {maxEdge:"", units:""}], "Transformation.convex": ["geojson",{concavity:""}], "Transformation.dissolve": ["featureCollection", {propertyName:""}], "Transformation.lineOffset": ["geojson", "distance", {units:""}], "Transformation.simplify": ["geojson", {tolerance:"", highQuality:""}], "Transformation.transformRotate": ["geojson", "angle", {pivot:"", mutate:""}], "Transformation.transformTranslate": ["geojson", "distance", "direction", {units:"", zTranslation:"", mutate:""}], "Transformation.transformScale": ["geojson", "factor", {origin:"", mutate:""}], "Transformation.voronoi": ["points",{bbox:""}], "featureConversion.lineStringToPolygon": ["lines",{properties:"", autoComplete:"", orderCoords:""}], "featureConversion.polygonToLineString": ["polygon", {properties:""}], "Misc.lineArc": ["center", "radius", "bearing1", "bearing2", {steps:"", units:""}], "Misc.lineChunk": ["geojson", "segmentLength", {units:"", reverse:""}], "Misc.lineOverlap": ["line1", "line2",{tolerance:""}], "Misc.lineSliceAlong": ["line", "startDist", "stopDist", {units:""}], "Misc.pointOnLine": ["lines", "pt", {units:""}], "Misc.sector": ["center", "radius", "bearing1", "bearing2", {units:"",steps:"",properties:""}], "Misc.shortestPath": ["start", "end", {obstacles:"", units:"",resolution:""}], "Helper.feature": ["geometry", "properties",{bbox:"",id:""}], "Helper.geometryCollection": ["geometries", "properties",{bbox:"",id:""}], "Helper.lineString": ["coordinates", "properties",{bbox:"",id:""}], "Helper.multiLineString": ["coordinates", "properties",{bbox:"",id:""}], "Helper.multiPoint": ["coordinates", "properties",{bbox:"",id:""}], "Helper.multiPolygon": ["coordinates", "properties",{bbox:"",id:""}], "Helper.point": ["coordinates", "properties",{bbox:"",id:""}], "Helper.polygon": ["coordinates", "properties",{bbox:"",id:""}], "Interpolation.interpolate": ["points", "cellSize", {gridType:"", property:"", units:"", weight:""}], "Interpolation.isobands": ["pointGrid", "breaks", {zProperty:"", commonProperties:"",breaksProperties:""}], "Interpolation.isolines": ["pointGrid", "breaks", {zProperty:"", commonProperties:"", breaksProperties:""}], "Grids.hexGrid": ["bbox", "cellSide", {units:"", triangles:"",properties:"",mask:""}], "Grids.pointGrid": ["bbox", "cellSide", {units:"", mask:"",properties:""}], "Grids.squareGrid": ["bbox", "cellSide", {units:"", mask:"",properties:""}], "Grids.triangleGrid": ["bbox", "cellSide", {units:"", mask:"",properties:""}], "Aggregation.clustersDbscan": ["points", "maxDistance", {units:"", minPoints:"",mutate:""}], "Aggregation.clustersKmeans": ["points", {numberOfClusters:"", mutate:""}], "Booleans.booleanPointInPolygon": ["point", "polygon", {ignoreBoundary:""}], "Booleans.booleanPointOnLine": ["point", "linestring", {ignoreEndVertices:""}], "UnitConversion.toMercator": ["geojson",{mutate:""}], "UnitConversion.toWgs84": ["geojson",{mutate:""}] } } /** * @function Turf.prototype.process * @description 执行 Turf.js 提供的相关空间分析方法。 * @param {string} type - Turf.js 提供的空间分析方法名。 * @param {Object} args - Turf.js 提供的空间分析方法对应的参数对象。 * @param {function} callback - 空间分析完成执行的回调函数,返回执行的结果。 * @param {boolean} addFeaturesToMap - 是否添加到 Map。 */ process(type, args, callback, addFeaturesToMap) { var result; // 兼容版本4到5 try{ result = external_function_try_return_turf_catch_e_return_namespaceObject[type.split('.')[1]].apply(this, this.parse(type, args)); }catch(e){ result = external_function_try_return_turf_catch_e_return_namespaceObject[type.split('.')[1]].apply(this, this.parseOption(type, args)); } var features = null; try { features = (new (external_ol_format_GeoJSON_default())()).readFeatures(result); } catch (e) { if (callback) { callback(result); } return; } addFeaturesToMap = addFeaturesToMap == null ? true : addFeaturesToMap; if (addFeaturesToMap) { this.addFeatures(features); } if (callback) { callback(result); } } parse(type, args) { if (type === 'Transformation.union') { return args['A']; } var result = []; var tempArgs = this.turfMap[type]; if (tempArgs) { tempArgs.map(function (key) { result.push(args[key]); return args[key]; }); } return result; } parseOption(type,args){ var result = []; var tempArgs = this.turfOptionMap[type]; tempArgs.map(function(key){ if(key instanceof Object){ var options = key; Object.keys(options).forEach(function(k){ options[k]=args[k] }) result.push(options); }else{ result.push(args[key]) } return args; }) return result; } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/Unique.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class Unique * @browsernamespace ol.source * @category Visualization Theme * @classdesc 单值专题图图层源。 * @param {string} name - 图层名称。 * @param {Object} opt_options - 参数。 * @param {ol.Map} opt_options.map - 当前 Map 对象。 * @param {string} [opt_options.id] - 专题图层 ID。默认使用 CommonUtil.createUniqueID("themeLayer_") 创建专题图层ID。 * @param {number} [opt_options.opacity=1] - 图层透明度。 * @param {string} [opt_options.logo] - Logo(openLayers 5.0.0 及更高版本不再支持此参数)。 * @param {ol.proj.Projection} [opt_options.projection] - 投影信息。 * @param {number} [opt_options.ratio=1.5] - 视图比,1 表示画布是地图视口的大小,2 表示地图视口的宽度和高度的两倍,依此类推。必须是1 或更高。 * @param {Array} [opt_options.resolutions] - 分辨率数组。 * @param {ol.source.State} [opt_options.state] - 资源状态。 * @param {string} [opt_options.themeField] - 指定创建专题图字段。 * @param {Object} [opt_options.style] - 专题图样式。 * @param {Object} [opt_options.styleGroups] - 各专题类型样式组。 * @param {boolean} [opt_options.isHoverAble=false] - 是否开启 hover 事件。 * @param {Object} [opt_options.highlightStyle] - 开启 hover 事件后,触发的样式风格。 * @param {(string|Object)} [opt_options.attributions='Map Data © SuperMap iServer with © SuperMap iClient'] - 版权信息。 * @extends {GeoFeature} * @usage */ class Unique extends GeoFeature { constructor(name, opt_options) { super(name, opt_options); this.themeField = opt_options.themeField; this.style = opt_options.style; this.styleGroups = opt_options.styleGroups; this.isHoverAble = opt_options.isHoverAble; this.highlightStyle = opt_options.highlightStyle; } /** * @function Unique.prototype.destroy * @description 释放资源,将引用资源的属性置空。 */ destroy() { this.style = null; this.themeField = null; this.styleGroups = null; GeoFeature.prototype.destroy.apply(this, arguments); } /** * @private * @function Unique.prototype.createThematicFeature * @description 创建专题要素。 * @param {Object} feature - 要素。 */ createThematicFeature(feature) { var style = this.getStyleByData(feature); //创建专题要素时的可选参数 var options = {}; options.nodesClipPixel = this.nodesClipPixel; options.isHoverAble = this.isHoverAble; options.isMultiHover = this.isMultiHover; options.isClickAble = this.isClickAble; options.highlightStyle = ShapeFactory.transformStyle(this.highlightStyle); //将数据转为专题要素(ThemeVector) var thematicFeature = new ThemeVector(feature, this, ShapeFactory.transformStyle(style), options); //直接添加图形到渲染器 for (var m = 0; m < thematicFeature.shapes.length; m++) { this.renderer.addShape(thematicFeature.shapes[m]); } return thematicFeature; } /** * @private * @function Unique.prototype.getStyleByData * @description 根据用户数据(feature)设置专题要素的 Style。 * @param {Object} fea - 用户要素数据。 */ getStyleByData(fea) { var style = {}; var feature = fea; style = Util.copyAttributesWithClip(style, this.style); if (this.themeField && this.styleGroups && this.styleGroups.length > 0 && feature.attributes) { var tf = this.themeField; var Attrs = feature.attributes; var Gro = this.styleGroups; var isSfInAttrs = false; //指定的 themeField 是否是 feature 的属性字段之一 var attr = null; //属性值 for (var property in Attrs) { if (tf === property) { isSfInAttrs = true; attr = Attrs[property]; break; } } //判断属性值是否属于styleGroups的某一个范围,以便对获取分组 style if (isSfInAttrs) { for (var i = 0, len = Gro.length; i < len; i++) { if ((attr).toString() === ( Gro[i].value).toString()) { //feature.style = CommonUtil.copyAttributes(feature.style, this.defaultStyle); var sty1 = Gro[i].style; style = Util.copyAttributesWithClip(style, sty1); } } } } if (feature.style && this.isAllowFeatureStyle === true) { style = Util.copyAttributesWithClip(feature.style); } return style; } canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars return GeoFeature.prototype.canvasFunctionInternal_.apply(this, arguments); } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/vectortile/VectorTileStyles.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class VectorTileStyles * @classdesc 矢量瓦片风格。 * @category Visualization VectorTile * @param {Object} options - 交互时所需可选参数。 * @extends {ol.Observable} * @usage */ class VectorTileStyles extends (external_ol_Observable_default()) { constructor(options) { super(); if (!options) { return; } var donotNeedServerCartoCss = false; if (options.donotNeedServerCartoCss !== undefined) { donotNeedServerCartoCss = options.donotNeedServerCartoCss } VectorTileStyles.setDonotNeedServerCartoCss(donotNeedServerCartoCss); if (options.view) { VectorTileStyles.setView(options.view); } if (options.url) { VectorTileStyles.setUrl(options.url); } if (options.cartoCss) { VectorTileStyles.setCartoCss(options.cartoCss); } var selectedPointStyle = getDefaultSelectedPointStyle(); if (options.selectedPointStyle) { selectedPointStyle = options.selectedPointStyle; } VectorTileStyles.setSelectedPointStyle(selectedPointStyle); var selectedLineStyle = getDefaultSelectedLineStyle(); if (options.selectedLineStyle) { selectedLineStyle = options.selectedLineStyle; } VectorTileStyles.setSelectedLineStyle(selectedLineStyle); var selectedRegionStyle = getDefaultSelectedRegionStyle(); if (options.selectedRegionStyle) { selectedRegionStyle = options.selectedRegionStyle; } VectorTileStyles.setSelectedRegionStyle(selectedRegionStyle); var selectedTextStyle = getDefaultSelectedTextStyle(); if (options.selectedTextStyle) { selectedTextStyle = options.selectedTextStyle; } VectorTileStyles.setSelectedTextStyle(selectedTextStyle); var layersXHR = new XMLHttpRequest(); layersXHR.onreadystatechange = function () { if (layersXHR.readyState == 4) { var result = JSON.parse(layersXHR.responseText); var layersInfo = {}; for (var i = 0, len = result.length; i < len; i++) { var layers = result[i].subLayers.layers; for (var j = 0, len1 = layers.length; j < len1; j++) { layers[j].layerIndex = len1 - j; layersInfo[layers[j].name] = layers[j]; } } VectorTileStyles.setLayersInfo(layersInfo); if (!VectorTileStyles.getDonotNeedServerCartoCss()) { var vectorStylesXHR = new XMLHttpRequest(); vectorStylesXHR.open("GET", Util.urlPathAppend(VectorTileStyles.getUrl(), "tileFeature/vectorstyles.json"), false); vectorStylesXHR.onreadystatechange = function () { if (vectorStylesXHR.readyState == 4) { var vectorStyles = new JSONFormat().read(vectorStylesXHR.responseText); var cartoCss; if (vectorStyles.style && vectorStyles.type === 'cartoCSS') { cartoCss = vectorStyles.style; cartoCss = cartoCss.replace(/[@]/gi, "___"); cartoCss = cartoCss.replace(/\\#/gi, "___"); //替换一些关键符号 var cachedLayer = {}; layersInfo && Object.keys(layersInfo).sort().forEach(function (attr) { var newAttr = attr.replace(/[@#\s]/gi, "___"); var to = attr; var keys = Object.keys(cachedLayer); for (let index = keys.length; index > -1; index--) { if (attr.indexOf(keys[index]) > -1) { to = attr.replace(keys[index], cachedLayer[keys[index]]); break; } } to = to.replace(/[#]/gi, "\#"); cachedLayer[attr] = newAttr; cartoCss = cartoCss.replace(new RegExp(to, "g"), newAttr); }) cartoCss = cartoCss.replace(/[#]/gi, "\n#"); //将zoom转化为scale,以免引起混淆 cartoCss = cartoCss.replace(/\[zoom/gi, "[scale"); } var cartoShadersArray = new CartoCSS(cartoCss).getShaders(); var cartoShaders = {}; cartoShadersArray.forEach(function (cartoShader) { cartoShaders[cartoShader.elements[0].clean] = cartoShaders[cartoShader.elements[0].clean] || {}; cartoShaders[cartoShader.elements[0].clean][cartoShader.attachment] = cartoShaders[cartoShader.elements[0].clean][cartoShader.attachment] || []; cartoShaders[cartoShader.elements[0].clean][cartoShader.attachment].push(cartoShader); return cartoShader; }); VectorTileStyles.setCartoShaders(cartoShaders); } }; vectorStylesXHR.send(null); } if (VectorTileStyles.getCartoCss()) { var clientCartoShadersArray = new CartoCSS(VectorTileStyles.getCartoCss()).getShaders(); var clientCartoShaders = {}; clientCartoShadersArray.forEach(function (cartoShader) { clientCartoShaders[cartoShader.elements[0].clean] = clientCartoShaders[cartoShader.elements[0].clean] || {}; clientCartoShaders[cartoShader.elements[0].clean][cartoShader.attachment] = clientCartoShaders[cartoShader.elements[0].clean][cartoShader.attachment] || []; clientCartoShaders[cartoShader.elements[0].clean][cartoShader.attachment].push(cartoShader); return cartoShader; }); VectorTileStyles.setClientCartoShaders(clientCartoShaders); } } }; layersXHR.open("GET", Util.urlPathAppend(VectorTileStyles.getUrl(), "layers.json"), false); layersXHR.send(null); this.on('featureSelected', function (e) { VectorTileStyles.setSelectedId(e.selectedId); VectorTileStyles.setLayerName(e.layerName); }); /** * @function VectorTileStyles.prototype.getDefaultSelectedPointStyle * @description 设置默认选择后的点样式。 */ function getDefaultSelectedPointStyle() { return new (external_ol_style_Style_default())({ image: new (external_ol_style_Circle_default())({ radius: 5, fill: new (external_ol_style_Fill_default())({ color: 'blue' }) }) }) } /** * @function VectorTileStyles.prototype.getDefaultSelectedLineStyle * @description 设置默认选择后的线样式。 */ function getDefaultSelectedLineStyle() { return new (external_ol_style_Style_default())({ stroke: new (external_ol_style_Stroke_default())({ color: 'blue', width: 3 }) }) } /** * @function VectorTileStyles.prototype.getDefaultSelectedRegionStyle * @description 设置默认选择后的面样式。 */ function getDefaultSelectedRegionStyle() { return new (external_ol_style_Style_default())({ fill: new (external_ol_style_Fill_default())({ color: [0, 0, 255, 0.5] }), stroke: new (external_ol_style_Stroke_default())({ color: 'blue', width: 3 }) }) } /** * @function VectorTileStyles.prototype.getDefaultSelectedTextStyle * @description 设置默认选择后的文本样式。 */ function getDefaultSelectedTextStyle() { return new (external_ol_style_Style_default())({ text: new (external_ol_style_Text_default())({ font: '15px Microsoft YaHei', fill: new (external_ol_style_Fill_default())({ color: 'blue' }), stroke: new (external_ol_style_Stroke_default())({ color: 'white', width: 1 }) }) }); } } /** * @function VectorTileStyles.setCartoShaders * @description 设置服务端 Carto 的阴影。 * @param {Array} cartoShaders - 服务端 Carto 阴影。 */ static setCartoShaders(cartoShaders) { this.cartoShaders = cartoShaders; } /** * @function VectorTileStyles.getCartoShaders * @description 获取服务端 Carto 的阴影。 */ static getCartoShaders() { return this.cartoShaders; } /** * @function VectorTileStyles.setClientCartoShaders * @description 设置客户端 Carto 的阴影。 * @param {Array} clientCartoShaders - 客户端 Carto 阴影。 */ static setClientCartoShaders(clientCartoShaders) { this.clientCartoShaders = clientCartoShaders; } /** * @function VectorTileStyles.getClientCartoShaders * @description 获取客户端 Carto 的阴影。 */ static getClientCartoShaders() { return this.clientCartoShaders; } /** * @function VectorTileStyles.setCartoCss * @description 设置 CartoCSS 的样式。 * @param {Object} cartoCss - CartoCSS 的样式。 */ static setCartoCss(cartoCss) { this.cartoCss = cartoCss; } /** * @function VectorTileStyles.getCartoCss * @description 获取 CartoCSS 的样式。 */ static getCartoCss() { return this.cartoCss; } /** * @function VectorTileStyles.setDonotNeedServerCartoCss * @description 设置是否需要 CartoCss 服务。 * @param {Object} donotNeedServerCartoCss - 是否需要 CartoCss 服务。 */ static setDonotNeedServerCartoCss(donotNeedServerCartoCss) { this.donotNeedServerCartoCss = donotNeedServerCartoCss; } /** * @function VectorTileStyles.getDonotNeedServerCartoCss * @description 获取是否需要 CartoCss 服务。 */ static getDonotNeedServerCartoCss() { return this.donotNeedServerCartoCss; } /** * @function VectorTileStyles.setLayersInfo * @description 设置图层信息服务。 * @param {Object} layersInfo - 图层信息。 */ static setLayersInfo(layersInfo) { this.layersInfo = layersInfo; } /** * @function VectorTileStyles.getLayersInfo * @description 获取图层信息服务。 */ static getLayersInfo() { return this.layersInfo; } /** * @function VectorTileStyles.setUrl * @description 设置地址。 * @param {string} url - 地址。 */ static setUrl(url) { this.url = url; } /** * @function VectorTileStyles.getUrl * @description 获取地址。 */ static getUrl() { return this.url; } /** * @function VectorTileStyles.setView * @description 设置视图。 * @param {Object} view - 视图。 */ static setView(view) { this.view = view; } /** * @function VectorTileStyles.getView * @description 获取视图。 */ static getView() { return this.view; } /** * @function VectorTileStyles.setSelectedId * @description 设置选择序号。 * @param {number} selectedId - 选择序号。 */ static setSelectedId(selectedId) { this.selectedId = selectedId; } /** * @function VectorTileStyles.getSelectedId * @description 获取选择序号。 */ static getSelectedId() { return this.selectedId; } /** * @function VectorTileStyles.setLayerName * @description 设置图层名称。 * @param {string} layerName - 图层名称。 */ static setLayerName(layerName) { this.layerName = layerName; } /** * @function VectorTileStyles.getLayerName * @description 获取图层名称。 */ static getLayerName() { return this.layerName; } /** * @function VectorTileStyles.setSelectedPointStyle * @description 设置选择后点样式。 * @param {Object} selectedPointStyle - 选择后点样式。 */ static setSelectedPointStyle(selectedPointStyle) { this.selectedPointStyle = selectedPointStyle; } /** * @function VectorTileStyles.setSelectedLineStyle * @description 设置选择后线样式。 * @param {Object} selectedLineStyle - 选择后线样式。 */ static setSelectedLineStyle(selectedLineStyle) { this.selectedLineStyle = selectedLineStyle; } /** * @function VectorTileStyles.setSelectedRegionStyle * @description 设置选择后面样式。 * @param {Object} selectedRegionStyle - 选择后面样式。 */ static setSelectedRegionStyle(selectedRegionStyle) { this.selectedRegionStyle = selectedRegionStyle; } /** * @function VectorTileStyles.setSelectedTextStyle * @description 设置选择后文本样式。 * @param {Object} selectedTextStyle - 选择后文本样式。 */ static setSelectedTextStyle(selectedTextStyle) { this.selectedTextStyle = selectedTextStyle; } /** * @function VectorTileStyles.getSelectedStyle * @description 设置选择后的样式。 * @param {string} type - 选择后的样式。 */ static getSelectedStyle(type) { if (type === 'POINT' || type === 'MULTIPOINT') { return this.selectedPointStyle; } if (type === 'LINESTRING' || type === 'MULTILINESTRING') { return this.selectedLineStyle; } if (type === 'POLYGON' || type === 'MULTIPOLYGON') { return this.selectedRegionStyle; } if (type === 'TEXT') { return this.selectedTextStyle; } } /** * @function VectorTileStyles.getLayerInfo * @description 获取图层的信息。 * @param {string} layerName - 图层名。 */ static getLayerInfo(layerName) { var layersInfo = VectorTileStyles.getLayersInfo(); if (layersInfo === undefined) { return null; } var layerInfo = layersInfo[layerName]; if (!layerInfo) { return null; } var layerInfo_simple = {layerIndex: layerInfo.layerIndex, ugcLayerType: layerInfo.ugcLayerType}; switch (layerInfo.ugcLayerType) { case "VECTOR": layerInfo_simple.layerStyle = layerInfo.style ? layerInfo.style : null; break; case "THEME": var theme = layerInfo.theme; layerInfo_simple.layerStyle = theme ? theme.defaultStyle : null; if (theme && theme.type === "LABEL") { layerInfo_simple.type = theme.type; layerInfo_simple.textField = theme.labelExpression; } break; default : //SVTile发布出来的地图没有ugcLayerType属性 if (layerInfo.style) { layerInfo_simple.layerStyle = layerInfo.style; } break; } return layerInfo_simple; } /** * @function VectorTileStyles.getStyle * @description 获取样式。 * @param {string} originalLayerName - 原始图层信息。 * @param {Object} feature - 要素对象。 */ static getStyle(originalLayerName, feature) { var url = VectorTileStyles.getUrl(), view = VectorTileStyles.getView(), zoom = view.getZoom(), dpi = 96, scale = core_Util_Util.resolutionToScale(view.getResolution(), dpi, Unit.METER), layerName = originalLayerName.replace(/(@)/gi, '___').replace(/(#)/gi, '___'); // feature对象样式的配置遵循以下优先级: // 客户端CartoCSS > 服务器端CartoCSS > 服务器端layer样式 > 客户端默认样式。 if (VectorTileStyles.getCartoCss() && VectorTileStyles.getClientCartoShaders()[layerName]) { return getStyleArray(VectorTileStyles.getClientCartoShaders()[layerName]); } var layerInfo = VectorTileStyles.getLayerInfo(originalLayerName); if (!VectorTileStyles.getDonotNeedServerCartoCss() && VectorTileStyles.getCartoShaders()[layerName]) { //如果是文本,这里特殊处理。 if (feature.getProperties().textStyle || feature.getProperties().TEXT_FEATURE_CONTENT || layerInfo.type == 'LABEL' && layerInfo.textField) { var featureStyle = StyleUtils.getValidStyleFromLayerInfo(layerInfo, feature, url); if (feature.getGeometry().getType().toUpperCase() === "POINT") { featureStyle = mergeTextFeatureStyle(layerInfo, feature, url); } return featureStyle; } return getStyleArray(VectorTileStyles.getCartoShaders()[layerName]); } if (layerInfo) { return StyleUtils.getValidStyleFromLayerInfo(layerInfo, feature, url); } function getStyleArray(shaderAttachment) { var styleArray = []; for (var j in shaderAttachment) { shaderAttachment[j].map(function (shader) { styleArray.push(StyleUtils.getStyleFromCarto(zoom, scale, shader, feature, true, url)) return shader; }) } return styleArray; } /** * @function VectorTileStyles.prototype.mergeTextFeatureStyle * @description 合并文本要素样式。 * @param {string} layerInfo - 图层信息。 * @param {Object} feature - 获取的要素。 * @param {string} url - 服务地址。 */ function mergeTextFeatureStyle(layerInfo, feature, url) { var textFeatureStyle = StyleUtils.getValidStyleFromLayerInfo(layerInfo, feature, url); if (layerInfo.type == 'LABEL') { feature.setProperties({type: "TEXT"}); var cartoTextStyles = getStyleArray(VectorTileStyles.getCartoShaders()[layerName]); var textStyle = textFeatureStyle.getText(); for (var i = 0; i < cartoTextStyles.length; i++) { if (!textStyle) { textStyle = cartoTextStyles[i].getText(); } else { textStyle.setText(cartoTextStyles[i].getText().getText()); } } textFeatureStyle.setText(textStyle); return textFeatureStyle; } return textFeatureStyle; } } /** * @function VectorTileStyles.prototype.getFeatureStyle * @description 获取要素样式。 * @param {Object} feature - 要素。 */ getFeatureStyle(feature) { var selectedStyle; var layerName = feature.getProperties().layerName || feature.getProperties().layer; var id = feature.getProperties().id || parseInt(feature.getProperties().SmID); if (feature.getProperties().type && feature.getProperties().type.toUpperCase() === 'TEXT') { selectedStyle = VectorTileStyles.getSelectedStyle(feature.getProperties().type.toUpperCase()); if (feature.getProperties().texts) { selectedStyle.getText().text_ = feature.getProperties().texts[0]; } else { selectedStyle.getText().text_ = ""; } } else { selectedStyle = VectorTileStyles.getSelectedStyle(feature.getGeometry().getType().toUpperCase()); } if (selectedStyle) { var selectedLayerName = VectorTileStyles.getLayerName(); var selectedId = VectorTileStyles.getSelectedId(); if (selectedLayerName === layerName && id === selectedId) { return selectedStyle; } } return VectorTileStyles.getStyle(layerName, feature); } } ;// CONCATENATED MODULE: external "ol.source.VectorTile" const external_ol_source_VectorTile_namespaceObject = ol.source.VectorTile; var external_ol_source_VectorTile_default = /*#__PURE__*/__webpack_require__.n(external_ol_source_VectorTile_namespaceObject); ;// CONCATENATED MODULE: external "ol.format.MVT" const external_ol_format_MVT_namespaceObject = ol.format.MVT; var external_ol_format_MVT_default = /*#__PURE__*/__webpack_require__.n(external_ol_format_MVT_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/overlay/VectorTileSuperMapRest.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class VectorTileSuperMapRest * @browsernamespace ol.source * @category Visualization VectorTile * @classdesc 矢量瓦片图层源。 * @param {Object} options - 参数。 * @param {(string|undefined)} options.url - 服务地址。 * @param {(string|Object|undefined)} options.style - Mapbox Style JSON 对象或获取 Mapbox Style JSON 对象的 URL。当 `options.format` 为 {@link ol.format.MVT} 且 `options.source` 不为空时有效,优先级高于 `options.url`。 * @param {(string|undefined)} options.source - Mapbox Style JSON 对象中的source名称。当 `options.style` 设置时有效。当不配置时,默认为 Mapbox Style JSON 的 `sources` 对象中的第一个。 * @param {(string|Object)} [options.attributions='Tile Data © SuperMap iServer with © SuperMap iClient'] - 版权信息。 * @param {Object} [options.format] - 瓦片的要素格式化。 * @param {boolean} [options.withCredentials] - 请求是否携带 cookie。 * @extends {ol.source.VectorTile} * @usage */ class VectorTileSuperMapRest extends (external_ol_source_VectorTile_default()) { constructor(options) { if (options.url === undefined && options.style === undefined) { console.error("one of 'options.style' or 'options.style' is required"); } var zRegEx = /\{z\}/g; var xRegEx = /\{x\}/g; var yRegEx = /\{y\}/g; var dashYRegEx = /\{-y\}/g; options.attributions = options.attributions || "Tile Data © SuperMap iServer with © SuperMap iClient"; if (['4', '5'].indexOf(core_Util_Util.getOlVersion()) < 0) { options.tileSize = options.format instanceof (external_ol_format_MVT_default()) && options.style ? 512 : 256; } super({ attributions: options.attributions, cacheSize: options.cacheSize, format: options.format || new (external_ol_format_GeoJSON_default())(), logo: core_Util_Util.getOlVersion() === '4' ? options.logo : null, overlaps: options.overlaps, projection: options.projection, state: options.format instanceof (external_ol_format_MVT_default()) && options.style && Object.prototype.toString.call(options.style) == '[object String]' ? 'loading' : options.state, tileClass: options.tileClass, tileGrid: options.tileGrid, tilePixelRatio: options.tilePixelRatio, tileUrlFunction: options.tileUrlFunction || (options.format instanceof (external_ol_format_MVT_default()) && options.style ? zxyTileUrlFunction : tileUrlFunction), tileLoadFunction: options.tileLoadFunction || (options.format instanceof (external_ol_format_MVT_default()) ? mvtTileLoadFunction : tileLoadFunction), wrapX: options.wrapX !== undefined ? options.wrapX : false, tileSize: options.tileSize || null, zDirection: ['4', '5'].indexOf(core_Util_Util.getOlVersion()) > -1 ? null : 0 }); var me = this; me.withCredentials = options.withCredentials; me._tileType = options.tileType || 'ScaleXY'; this.vectorTileStyles = new VectorTileStyles(); if (options.format instanceof (external_ol_format_MVT_default()) && options.style) { if (Object.prototype.toString.call(options.style) == '[object String]') { var url = SecurityManager.appendCredential(options.style); FetchRequest.get(url, null, { withCredentials: options.withCredentials }) .then((response) => response.json()) .then((mbStyle) => { this._fillByStyleJSON(mbStyle, options.source); this.setState('ready'); }); } else { this._fillByStyleJSON(options.style, options.source); } } else { this._fillByRestMapOptions(options.url, options); } function tileUrlFunction(tileCoord, pixelRatio, projection) { if (!me.tileGrid) { me.tileGrid = me.getTileGridForProjection(projection); } var z = tileCoord[0]; var x = tileCoord[1]; var y = ['4', '5'].indexOf(core_Util_Util.getOlVersion()) > -1 ? -tileCoord[2] - 1 : tileCoord[2]; var tileSize = external_ol_size_namespaceObject.toSize(me.tileGrid.getTileSize(z, me.tmpSize)); var params = ''; if (me.tileType === 'ZXY') { params = '&width=' + tileSize[0] + '&height=' + tileSize[1] + '&x=' + x + '&y=' + y + '&z=' + z; } else if (me.tileType === 'ViewBounds') { var tileExtent = me.tileGrid.getTileCoordExtent(tileCoord); params = '&width=' + tileSize[0] + '&height=' + tileSize[1] + '&viewBounds=' + tileExtent[0] + ',' + tileExtent[1] + ',' + tileExtent[2] + ',' + tileExtent[3]; } else { var origin = me.tileGrid.getOrigin(z); var resolution = me.tileGrid.getResolution(z); var dpi = 96; var unit = projection.getUnits() || 'degrees'; if (unit === 'degrees') { unit = Unit.DEGREE; } if (unit === 'm') { unit = Unit.METER; } var scale = core_Util_Util.resolutionToScale(resolution, dpi, unit); params = '&x=' + x + '&y=' + y + '&width=' + tileSize[0] + '&height=' + tileSize[1] + '&scale=' + scale + "&origin={'x':" + origin[0] + ",'y':" + origin[1] + '}'; } return me._tileUrl + encodeURI(params); } function zxyTileUrlFunction(tileCoord) { if (!tileCoord) { return undefined; } else { return me._tileUrl .replace(zRegEx, tileCoord[0].toString()) .replace(xRegEx, tileCoord[1].toString()) .replace(yRegEx, function () { var y = ['4', '5'].indexOf(core_Util_Util.getOlVersion()) > -1 ? -tileCoord[2] - 1 : tileCoord[2]; return y.toString(); }) .replace(dashYRegEx, function () { var z = tileCoord[0]; var range = me.tileGrid.getFullTileRange(z); var y = range.getHeight() + tileCoord[2]; return y.toString(); }); } } /** * @private * @function VectorTileSuperMapRest.prototype.tileLoadFunction * @description 加载瓦片。 * @param {Object} tile -瓦片类。 * @param {string} tileUrl - 瓦片地址。 */ function tileLoadFunction(tile, tileUrl) { var regWidth = new RegExp('(^|\\?|&)' + 'width' + '=([^&]*)(\\s|&|$)'); var regHeight = new RegExp('(^|\\?|&)' + 'height' + '=([^&]*)(\\s|&|$)'); var width = Number(tileUrl.match(regWidth)[2]); var height = Number(tileUrl.match(regHeight)[2]); tile.setLoader(function (extent, resolution, projection) { FetchRequest.get(tileUrl) .then(function (response) { if (tile.getFormat() instanceof (external_ol_format_GeoJSON_default())) { return response.json(); } }) .then(function (tileFeatureJson) { var features = []; if (tile.getFormat() instanceof (external_ol_format_GeoJSON_default())) { tileFeatureJson.recordsets.map(function (recordset) { recordset.features.map(function (feature) { var points = []; var startIndex = 0; for (var i = 0; i < feature.geometry.parts.length; i++) { var partPointsLength = feature.geometry.parts[i] * 2; for (var j = 0, index = startIndex; j < partPointsLength; j += 2, index += 2) { points.push( new Point( feature.geometry.points[index], feature.geometry.points[index + 1] ) ); } startIndex += partPointsLength; } feature.geometry.points = points; return feature; }); return recordset; }); tileFeatureJson.recordsets.map(function (recordset) { recordset.features.map(function (feature) { feature.layerName = recordset.layerName; feature.type = feature.geometry.type; features.push(feature); return feature; }); return recordset; }); let dataProjection = new (external_ol_proj_Projection_default())({ extent: [0, 0, 256, 256], code: 'TILE_PIXELS', units: 'tile-pixels' }); if (['4', '5'].indexOf(core_Util_Util.getOlVersion()) > -1) { tile.setExtent([0, 0, width, height]); tile.setProjection(dataProjection); features = tile.getFormat().readFeatures(core_Util_Util.toGeoJSON(features)); } else { features = tile.getFormat().readFeatures(core_Util_Util.toGeoJSON(features), { extent, dataProjection, featureProjection: projection }); } tile.setFeatures(features); } }); }); } /** * @private * @function VectorTileSuperMapRest.prototype.tileLoadFunction * @description 加载瓦片。 * @param {Object} tile -瓦片类。 * @param {string} tileUrl - 瓦片地址。 */ function mvtTileLoadFunction(tile, tileUrl) { const format = tile.getFormat(); const success = tile.onLoad.bind(tile); const failure = tile.onError.bind(tile); tile.setLoader(function (extent, resolution, projection) { const xhr = new XMLHttpRequest(); xhr.open( 'GET', typeof tileUrl === 'function' ? tileUrl(extent, resolution, projection) : tileUrl, true ); if (format.getType() == 'arraybuffer') { xhr.responseType = 'arraybuffer'; } xhr.withCredentials = me.withCredentials; xhr.onload = function () { if (!xhr.status || (xhr.status >= 200 && xhr.status < 300)) { const type = format.getType(); let source = void 0; if (type === 'json' || type === 'text') { source = xhr.responseText; } else if (type === 'xml') { source = xhr.responseXML; if (!source) { source = new DOMParser().parseFromString(xhr.responseText, 'application/xml'); } } else if (type === 'arraybuffer') { source = xhr.response; } if (source) { if (['4', '5'].indexOf(core_Util_Util.getOlVersion()) > -1) { success.call( this, format.readFeatures(source, { featureProjection: projection }), format.readProjection(source), format.getLastExtent() ); } else { success.call( this, format.readFeatures(source, { extent: extent, featureProjection: projection }), format.readProjection(source) ); } } else { failure.call(this); } } else { failure.call(this); } }.bind(this); xhr.onerror = function () { failure.call(this); }.bind(this); xhr.send(); }); } } _fillByStyleJSON(style, source) { if (!source) { source = Object.keys(style.sources)[0]; } if (style.sources && style.sources[source]) { //ToDo 支持多个tiles地址 this._tileUrl = SecurityManager.appendCredential(style.sources[source].tiles[0]); } if (style.metadata && style.metadata.indexbounds) { const indexbounds = style.metadata.indexbounds; var max = Math.max(indexbounds[2] - indexbounds[0], indexbounds[3] - indexbounds[1]); const defaultResolutions = []; for (let index = 0; index < 30; index++) { defaultResolutions.push(max / 512 / Math.pow(2, index)); } this.tileGrid = new (external_ol_tilegrid_TileGrid_default())({ extent: style.metadata.indexbounds, resolutions: defaultResolutions, tileSize: [512, 512] }); } } _fillByRestMapOptions(url, options) { this._tileUrl = Util.urlPathAppend(options.url, 'tileFeature.json'); if (options.format instanceof (external_ol_format_MVT_default())) { this._tileUrl = Util.urlPathAppend(options.url, 'tileFeature.mvt'); } //为url添加安全认证信息片段 this._tileUrl = SecurityManager.appendCredential(this._tileUrl); var returnAttributes = true; if (options.returnAttributes !== undefined) { returnAttributes = options.returnAttributes; } var params = {}; params['returnAttributes'] = returnAttributes; if (options._cache !== undefined) { params['_cache'] = options._cache; } if (options.layersID !== undefined) { params['layersID'] = options.layersID; } if (options.layerNames !== undefined) { params['layerNames'] = options.layerNames; } if (options.expands !== undefined) { params['expands'] = options.expands; } if (options.compressTolerance !== undefined) { params['compressTolerance'] = options.compressTolerance; } if (options.coordinateType !== undefined) { params['coordinateType'] = options.coordinateType; } if (options.returnCutEdges !== undefined) { params['returnCutEdges'] = options.returnCutEdges; } this._tileUrl = Util.urlAppend(this._tileUrl, Util.getParameterString(params)); } /** * @function VectorTileSuperMapRest.optionsFromMapJSON * @param {string} url - 地址。 * @param {Object} mapJSONObj - 地图 JSON。 * @description 获取地图 JSON 信息。 */ static optionsFromMapJSON(url, mapJSONObj) { var options = {}; options.url = url; options.crossOrigin = 'anonymous'; var extent = [mapJSONObj.bounds.left, mapJSONObj.bounds.bottom, mapJSONObj.bounds.right, mapJSONObj.bounds.top]; var resolutions = getResolutions(); function getResolutions() { var level = 17; var dpi = 96; var width = extent[2] - extent[0]; var height = extent[3] - extent[1]; var tileSize = width >= height ? width : height; var maxReolution; if (tileSize === width) { maxReolution = tileSize / mapJSONObj.viewer.width; } else { maxReolution = tileSize / mapJSONObj.viewer.height; } var resolutions = []; var unit = Unit.METER; if (mapJSONObj.coordUnit === Unit.DEGREE) { unit = Unit.DEGREE; } if (mapJSONObj.visibleScales.length > 0) { var scales = initScales(mapJSONObj); for (let i = 0; i < scales.length; i++) { resolutions.push(core_Util_Util.scaleToResolution(scales[i], dpi, unit)); } } else { for (let i = 0; i < level; i++) { resolutions.push(maxReolution / Math.pow(2, i)); } } return resolutions; } function initScales(mapJSONObj) { var scales = mapJSONObj.visibleScales; if (!scales) { return null; } var viewBounds = mapJSONObj.viewBounds, coordUnit = mapJSONObj.coordUnit, viewer = mapJSONObj.viewer, scale = mapJSONObj.scale, datumAxis = mapJSONObj.datumAxis; //将jsonObject转化为SuperMap.Bounds,用于计算dpi。 viewBounds = new Bounds(viewBounds.left, viewBounds.bottom, viewBounds.right, viewBounds.top); viewer = new Size(viewer.rightBottom.x, viewer.rightBottom.y); coordUnit = coordUnit.toLowerCase(); datumAxis = datumAxis || 6378137; var units = coordUnit; var dpi = Util.calculateDpi(viewBounds, viewer, scale, units, datumAxis); var resolutions = _resolutionsFromScales(scales); var len = resolutions.length; scales = [len]; for (var i = 0; i < len; i++) { scales[i] = Util.getScaleFromResolutionDpi(resolutions[i], dpi, units, datumAxis); } function _resolutionsFromScales(scales) { if (scales === null) { return; } var resolutions, len; len = scales.length; resolutions = [len]; for (var i = 0; i < len; i++) { resolutions[i] = Util.getResolutionFromScaleDpi(scales[i], dpi, units, datumAxis); } return resolutions; } return scales; } options.tileGrid = new (external_ol_tilegrid_TileGrid_default())({ extent: extent, resolutions: resolutions }); //options.projection = 'EPSG:' + mapJSONObj.prjCoordSys.epsgCode; return options; } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/HeatMap.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class HeatMap * @browsernamespace ol.source * @classdesc 热力图层类。 * @category Visualization HeatMap * @param {string} name - 图层名称。 * @param {Object} options - 参数。 * @param {ol.Map} options.map - openlayers 的 map 对象。 * @param {string} [options.id] - 专题图层 ID,默认使用 CommonUtil.createUniqueID("HeatMapSource_") 创建专题图层 ID。 * @param {string} [options.featureWeight] - 对应 feature 属性中的热点权重字段名称,权重值类型为 number。 * @param {number} [options.radius=50] - 热点渲染的最大半径(热点像素半径),单位为 px,当 useGeoUnit 参数 为 true 时,单位使用当前图层地理坐标单位。热点显示的时候以精确点为中心点开始往四周辐射衰减,其衰减半径和权重值成比列。 * @param {number} [options.opacity=1] - 图层透明度。 * @param {Array.} [options.colors=['blue','cyan','lime','yellow','red']] - 颜色线性渐变数组,颜色值必须为 canvas 所支持的。 * @param {boolean} [options.useGeoUnit=false] - 使用地理单位,false 表示默认热点半径默认使用像素单位。当设置为 true 时,热点半径和图层地理坐标保持一致。 * @extends {ol.source.ImageCanvas} * @usage */ class HeatMap extends (external_ol_source_ImageCanvas_default()) { constructor(name, opt_options) { var options = opt_options ? opt_options : {}; super({ attributions: options.attributions || "Map Data © SuperMap iServer with © SuperMap iClient", canvasFunction: canvasFunctionInternal_, logo: core_Util_Util.getOlVersion() === '4' ? options.logo : null, projection: options.projection, ratio: options.ratio, resolutions: options.resolutions, state: options.state }); function canvasFunctionInternal_(extent, resolution, pixelRatio, size, projection) { // eslint-disable-line no-unused-vars var mapWidth = size[0] * pixelRatio; var mapHeight = size[1] * pixelRatio; this.rootCanvas.width = this.maxWidth = mapWidth; this.rootCanvas.height = this.maxHeight = mapHeight; if (!this.features) { return this.rootCanvas; } this.pixelRatio = pixelRatio; //记录偏移量 var width = this.map.getSize()[0] * pixelRatio; var height = this.map.getSize()[1] * pixelRatio; this.offset = [(mapWidth - width) / 2 / pixelRatio, (mapHeight - height) / 2 / pixelRatio]; this.updateHeatPoints(resolution); return this.rootCanvas; } //初始化成员变量 this.canvasFunctionInternal_ = canvasFunctionInternal_; this.features = []; this.name = name; if (!options.map) { throw new Error('options.map is not found.'); } this.map = options.map; // this.TFEvents = options.TFEvents || []; this.id = options.id ? options.id : Util.createUniqueID("HeatMapSource_"); this.opacity = options.opacity ? options.opacity : 1; this.colors = options.colors ? options.colors : ['blue', 'cyan', 'lime', 'yellow', 'red']; this.useGeoUnit = options.useGeoUnit ? options.useGeoUnit : false; this.radius = options.radius ? options.radius : 50; this.featureWeight = options.featureWeight ? options.featureWeight : null; this.maxWeight = null; this.minWeight = null; this.maxWidth = null; this.maxHeight = null; //创建热力图绘制面板 this.rootCanvas = document.createElement("canvas"); var mapSize = this.map.getSize(); this.rootCanvas.width = this.maxWidth = parseInt(mapSize[0]); this.rootCanvas.height = this.maxHeight = parseInt(mapSize[1]); Util.modifyDOMElement(this.rootCanvas, null, null, null, null, null, null, this.opacity); this.canvasContext = this.rootCanvas.getContext('2d'); } /** * @function HeatMap.prototype.addFeatures * @description 添加热点信息。 * @param {(GeoJSONObject|Array.)} features - 待添加的要素数组。 * @example * var geojson = { * "type": "FeatureCollection", * "features": [ * { * "type": "feature", * "geometry": { * "type": "Point", //只支持point类型 * "coordinates": [0, 0] * }, * "properties": { * "height": Math.random()*9, * } * } * ] * }; * var heatMapSource = new HeatMap("heatMap",{"map": map}); * heatMapSource.addFeatures(geojson); * map.addLayer(new ol.layer.Image({ * source: heatMapSource * })); */ addFeatures(features) { this.features = this.toiClientFeature(features); //支持更新features,刷新底图 this.changed(); } /** * @function HeatMap.prototype.setOpacity * @description 设置图层的不透明度,取值 [0-1] 之间。 * @param {number} opacity - 不透明度。 */ setOpacity(opacity) { if (opacity !== this.opacity) { this.opacity = opacity; var element = this.rootCanvas; Util.modifyDOMElement(element, null, null, null, null, null, null, opacity); if (this.map !== null) { // this.dispatchEvent({type: 'changelayer', value: {layer: this, property: "opacity"}}); this.changed(); } } } /** * @function HeatMap.prototype.updateHeatPoints * @description 刷新热点图显示。 * @param {ol.LngLatBounds} resolution - 当前显示范围。 * @private */ updateHeatPoints(resolution) { if (this.features && this.features.length > 0) { this.convertFastToPixelPoints(resolution); } else { this.canvasContext.clearRect(0, 0, this.maxWidth, this.maxWidth); } } /** * @function HeatMap.prototype.convertFastToPixelPoints * @description 过滤位于当前显示范围内的热点,并转换其为当前分辨率下的像素坐标。 * @param {number} resolution - 当前分辨率。 * @private */ convertFastToPixelPoints(resolution) { var data = [], x, y, k, maxTemp, minTemp, maxWeightTemp; //热点半径 this.useRadius = this.useGeoUnit ? parseInt(this.radius / resolution) : this.radius; for (var i = 0; i < this.features.length; i++) { var feature = this.features[i]; var point = feature.geometry; //过滤,只显示当前范围 // if (mapBounds.contains(point.x, point.y)) { var pixelPoint = this.getLocalXY(new LonLat(point.x, point.y)); if (this.featureWeight) { pixelPoint.weight = feature.attributes[this.featureWeight];//point.value; if (!this.maxWeight) { //找出最大最小权重值 maxTemp = maxTemp ? maxTemp : pixelPoint.weight; minTemp = minTemp ? minTemp : pixelPoint.weight; maxTemp = Math.max(maxTemp, pixelPoint.weight); minTemp = Math.min(minTemp, pixelPoint.weight); } } else { pixelPoint.weight = 1; } x = Math.floor(pixelPoint[0]); y = Math.floor(pixelPoint[1]); k = pixelPoint.weight; data.push([x, y, k]); // } } //无最大权重设置 if (!this.maxWeight) { if (maxTemp && minTemp) { maxWeightTemp = (maxTemp + minTemp) / 2; } else { maxWeightTemp = 1; } this.draw(data, maxWeightTemp); } else { this.draw(data, this.maxWeight); } } /** * @function HeatMap.prototype.draw * @description 绘制热点图。 * @param {Array} data - convertToPixelPoints 方法计算出的点。 * @param {number} maxWeight -最大权重。 * @private */ draw(data, maxWeight) { if (this.maxHeight > 0 && this.maxWidth > 0) { //清空 var ctx = this.canvasContext; this.canvasContext.clearRect(0, 0, this.maxWidth, this.maxHeight); this.drawCircle(this.useRadius); this.createGradient(); for (var i = 0; i < data.length; i++) { var p = data[i]; this.canvasContext.globalAlpha = Math.max(p[2] / maxWeight, 0.05); this.canvasContext.drawImage(this.circle, p[0] - this.useRadius, p[1] - this.useRadius); } var colored = ctx.getImageData(0, 0, this.maxWidth, this.maxHeight); this.colorize(colored.data, this.grad); ctx.putImageData(colored, 0, 0); } else { return false; } } /** * @function HeatMap.prototype.colorize * @description 根据渐变色重置热点图 rgb 值。 * @param {Object} pixels - 像素 rgba 值。 * @param {Array} gradient - 渐变 canvas.getImageData.data。 * @private */ colorize(pixels, gradient) { for (var i = 0, j; i < pixels.length; i += 4) { j = pixels[i + 3] * 4; if (j) { pixels[i] = gradient[j]; pixels[i + 1] = gradient[j + 1]; pixels[i + 2] = gradient[j + 2]; } } } /** * @function HeatMap.drawCircle * @description 绘制热点半径圆。 * @param {number} r - 热点半径。 * @private */ drawCircle(r) { var blur = r / 2; var circle = this.circle = document.createElement('canvas'), ctx = circle.getContext("2d"); circle.height = 2 * r; circle.width = 2 * r; ctx.shadowOffsetX = ctx.shadowOffsetY = 2 * r; ctx.shadowBlur = blur; ctx.shadowColor = "#000000"; ctx.beginPath(); ctx.arc(-r, -r, r / 2, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); } /** * @function HeatMap.createGradient * @description 根据 this.canvasColors 设置渐变并 getImageData。 * @private */ createGradient() { var colors = this.colors; var canvas = document.createElement('canvas'), ctx = canvas.getContext("2d"), gradient = ctx.createLinearGradient(0, 0, 0, 256); canvas.height = 256; canvas.width = 1; var index = 1; for (var i = 0, len = colors.length; i < len; i++) { gradient.addColorStop(index / len, colors[i]); index++; } ctx.fillStyle = gradient; ctx.fillRect(0, 0, 1, 256); this.grad = ctx.getImageData(0, 0, 1, 256).data; } /** * @function HeatMap.prototype.getLocalXY * @description 获取坐标系统。 * @param {Object} coordinate - 坐标位置。 */ getLocalXY(coordinate) { var pixelP, map = this.map; if (coordinate instanceof Point || coordinate instanceof GeoText) { pixelP = map.getPixelFromCoordinate([coordinate.x, coordinate.y]); } if (coordinate instanceof LonLat) { pixelP = map.getPixelFromCoordinate([coordinate.lon, coordinate.lat]); } var rotation = -map.getView().getRotation(); var center = map.getPixelFromCoordinate(map.getView().getCenter()); var rotatedP = pixelP; if (this.pixelRatio) { rotatedP = this.scale(pixelP, center, this.pixelRatio); } if (pixelP && center) { rotatedP = this.rotate(rotatedP, rotation, center); } if (this.offset && rotatedP) { return [rotatedP[0] + this.offset[0], rotatedP[1] + this.offset[1]]; } return rotatedP; } /** * @function HeatMap.prototype.rotate * @description 获取某像素坐标点 pixelP 绕中心 center 逆时针旋转 rotation 弧度后的像素点坐标。 * @param {number} pixelP - 像素坐标点位置。 * @param {number} rotation - 旋转角度。 * @param {number} center - 中心位置。 */ rotate(pixelP, rotation, center) { var x = Math.cos(rotation) * (pixelP[0] - center[0]) - Math.sin(rotation) * (pixelP[1] - center[1]) + center[0]; var y = Math.sin(rotation) * (pixelP[0] - center[0]) + Math.cos(rotation) * (pixelP[1] - center[1]) + center[1]; return [x, y]; } /** * @function HeatMap.prototype.scale * @description 获取某像素坐标点 pixelP 相对于中心 center 进行缩放 scaleRatio 倍后的像素点坐标。 * @param {Object} pixelP - 像素点。 * @param {Object} center - 中心点。 * @param {number} scaleRatio - 缩放倍数。 * @returns {Array.} 返回数组型比例。 */ scale(pixelP, center, scaleRatio) { var x = (pixelP[0] - center[0]) * scaleRatio + center[0]; var y = (pixelP[1] - center[1]) * scaleRatio + center[1]; return [x, y]; } /** * @function HeatMap.prototype.removeFeatures * @description 移除指定的热点信息。 * @param {Array.|FeatureVector} features - 热点信息数组。 */ removeFeatures(features) { if (!features || features.length === 0 || !this.features || this.features.length === 0) { return; } if (features === this.features) { return this.removeAllFeatures(); } if (!(Util.isArray(features))) { features = [features]; } var heatPoint, index, heatPointsFailedRemoved = []; for (var i = 0, len = features.length; i < len; i++) { heatPoint = features[i]; index = Util.indexOf(this.features, heatPoint); //找不到视为删除失败 if (index === -1) { heatPointsFailedRemoved.push(heatPoint); continue; } //删除热点 this.features.splice(index, 1); } var succeed = heatPointsFailedRemoved.length == 0 ? true : false; //派发删除features成功的事件 this.dispatchEvent({type: 'featuresremoved', value: {features: heatPointsFailedRemoved, succeed: succeed}}); this.changed(); } /** * @function HeatMap.prototype.removeAllFeatures * @description 移除全部的热点信息。 */ removeAllFeatures() { this.features = []; this.changed(); } /** * @function HeatMap.prototype.toiClientFeature * @description 转为 iClient 要素。 * @param {GeoJSONObject|Array.} features - 待添加的要素数组。 * @returns {FeatureVector} 转换后的 iClient 要素。 */ toiClientFeature(features) { if (!core_Util_Util.isArray(features)) { features = [features]; } let featuresTemp = [], geometry, attributes; for (let i = 0, len = features.length; i < len; i++) { if (features[i] instanceof (external_ol_Feature_default())) { //热点图支支持传入点对象要素 if (features[i].getGeometry() instanceof (external_ol_geom_Point_default())) { geometry = new Point(features[i].getGeometry().getCoordinates()[0], features[i].getGeometry().getCoordinates()[1]); //固定属性字段为 "Properties" attributes = features[i].getProperties()["Properties"] ? features[i].getProperties()["Properties"] : {}; featuresTemp.push(new Vector(geometry, attributes)); } } else if (["FeatureCollection", "Feature", "Geometry"].indexOf(features[i].type) != -1) { let format = new GeoJSON(); featuresTemp = featuresTemp.concat(format.read(features[i])); } else if (features[i].geometry && features[i].geometry.parts) { //iServer服务器返回数据格式 featuresTemp.push(ServerFeature.fromJson(features[i]).toFeature()); } else { throw new Error(`Features[${i}]'s type does not match, please check.`); } } return featuresTemp; } } ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/flat-geobuf/geometry-type.js var geometry_type_GeometryType; (function (GeometryType) { GeometryType[GeometryType["Unknown"] = 0] = "Unknown"; GeometryType[GeometryType["Point"] = 1] = "Point"; GeometryType[GeometryType["LineString"] = 2] = "LineString"; GeometryType[GeometryType["Polygon"] = 3] = "Polygon"; GeometryType[GeometryType["MultiPoint"] = 4] = "MultiPoint"; GeometryType[GeometryType["MultiLineString"] = 5] = "MultiLineString"; GeometryType[GeometryType["MultiPolygon"] = 6] = "MultiPolygon"; GeometryType[GeometryType["GeometryCollection"] = 7] = "GeometryCollection"; GeometryType[GeometryType["CircularString"] = 8] = "CircularString"; GeometryType[GeometryType["CompoundCurve"] = 9] = "CompoundCurve"; GeometryType[GeometryType["CurvePolygon"] = 10] = "CurvePolygon"; GeometryType[GeometryType["MultiCurve"] = 11] = "MultiCurve"; GeometryType[GeometryType["MultiSurface"] = 12] = "MultiSurface"; GeometryType[GeometryType["Curve"] = 13] = "Curve"; GeometryType[GeometryType["Surface"] = 14] = "Surface"; GeometryType[GeometryType["PolyhedralSurface"] = 15] = "PolyhedralSurface"; GeometryType[GeometryType["TIN"] = 16] = "TIN"; GeometryType[GeometryType["Triangle"] = 17] = "Triangle"; })(geometry_type_GeometryType || (geometry_type_GeometryType = {})); // EXTERNAL MODULE: ./node_modules/flatbuffers/js/flatbuffers.js var js_flatbuffers = __webpack_require__(903); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/flat-geobuf/geometry.js function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var geometry_Geometry = /*#__PURE__*/function () { function Geometry() { _classCallCheck(this, Geometry); this.bb = null; this.bb_pos = 0; } _createClass(Geometry, [{ key: "__init", value: function __init(i, bb) { this.bb_pos = i; this.bb = bb; return this; } }, { key: "ends", value: function ends(index) { var offset = this.bb.__offset(this.bb_pos, 4); return offset ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0; } }, { key: "endsLength", value: function endsLength() { var offset = this.bb.__offset(this.bb_pos, 4); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "endsArray", value: function endsArray() { var offset = this.bb.__offset(this.bb_pos, 4); return offset ? new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; } }, { key: "xy", value: function xy(index) { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; } }, { key: "xyLength", value: function xyLength() { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "xyArray", value: function xyArray() { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; } }, { key: "z", value: function z(index) { var offset = this.bb.__offset(this.bb_pos, 8); return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; } }, { key: "zLength", value: function zLength() { var offset = this.bb.__offset(this.bb_pos, 8); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "zArray", value: function zArray() { var offset = this.bb.__offset(this.bb_pos, 8); return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; } }, { key: "m", value: function m(index) { var offset = this.bb.__offset(this.bb_pos, 10); return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; } }, { key: "mLength", value: function mLength() { var offset = this.bb.__offset(this.bb_pos, 10); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "mArray", value: function mArray() { var offset = this.bb.__offset(this.bb_pos, 10); return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; } }, { key: "t", value: function t(index) { var offset = this.bb.__offset(this.bb_pos, 12); return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; } }, { key: "tLength", value: function tLength() { var offset = this.bb.__offset(this.bb_pos, 12); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "tArray", value: function tArray() { var offset = this.bb.__offset(this.bb_pos, 12); return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; } }, { key: "tm", value: function tm(index) { var offset = this.bb.__offset(this.bb_pos, 14); return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); } }, { key: "tmLength", value: function tmLength() { var offset = this.bb.__offset(this.bb_pos, 14); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "type", value: function type() { var offset = this.bb.__offset(this.bb_pos, 16); return offset ? this.bb.readUint8(this.bb_pos + offset) : geometry_type_GeometryType.Unknown; } }, { key: "parts", value: function parts(index, obj) { var offset = this.bb.__offset(this.bb_pos, 18); return offset ? (obj || new Geometry()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; } }, { key: "partsLength", value: function partsLength() { var offset = this.bb.__offset(this.bb_pos, 18); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }], [{ key: "getRootAsGeometry", value: function getRootAsGeometry(bb, obj) { return (obj || new Geometry()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "getSizePrefixedRootAsGeometry", value: function getSizePrefixedRootAsGeometry(bb, obj) { bb.setPosition(bb.position() + js_flatbuffers/* SIZE_PREFIX_LENGTH */.XU); return (obj || new Geometry()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "startGeometry", value: function startGeometry(builder) { builder.startObject(8); } }, { key: "addEnds", value: function addEnds(builder, endsOffset) { builder.addFieldOffset(0, endsOffset, 0); } }, { key: "createEndsVector", value: function createEndsVector(builder, data) { builder.startVector(4, data.length, 4); for (var i = data.length - 1; i >= 0; i--) { builder.addInt32(data[i]); } return builder.endVector(); } }, { key: "startEndsVector", value: function startEndsVector(builder, numElems) { builder.startVector(4, numElems, 4); } }, { key: "addXy", value: function addXy(builder, xyOffset) { builder.addFieldOffset(1, xyOffset, 0); } }, { key: "createXyVector", value: function createXyVector(builder, data) { builder.startVector(8, data.length, 8); for (var i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]); } return builder.endVector(); } }, { key: "startXyVector", value: function startXyVector(builder, numElems) { builder.startVector(8, numElems, 8); } }, { key: "addZ", value: function addZ(builder, zOffset) { builder.addFieldOffset(2, zOffset, 0); } }, { key: "createZVector", value: function createZVector(builder, data) { builder.startVector(8, data.length, 8); for (var i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]); } return builder.endVector(); } }, { key: "startZVector", value: function startZVector(builder, numElems) { builder.startVector(8, numElems, 8); } }, { key: "addM", value: function addM(builder, mOffset) { builder.addFieldOffset(3, mOffset, 0); } }, { key: "createMVector", value: function createMVector(builder, data) { builder.startVector(8, data.length, 8); for (var i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]); } return builder.endVector(); } }, { key: "startMVector", value: function startMVector(builder, numElems) { builder.startVector(8, numElems, 8); } }, { key: "addT", value: function addT(builder, tOffset) { builder.addFieldOffset(4, tOffset, 0); } }, { key: "createTVector", value: function createTVector(builder, data) { builder.startVector(8, data.length, 8); for (var i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]); } return builder.endVector(); } }, { key: "startTVector", value: function startTVector(builder, numElems) { builder.startVector(8, numElems, 8); } }, { key: "addTm", value: function addTm(builder, tmOffset) { builder.addFieldOffset(5, tmOffset, 0); } }, { key: "createTmVector", value: function createTmVector(builder, data) { builder.startVector(8, data.length, 8); for (var i = data.length - 1; i >= 0; i--) { builder.addInt64(data[i]); } return builder.endVector(); } }, { key: "startTmVector", value: function startTmVector(builder, numElems) { builder.startVector(8, numElems, 8); } }, { key: "addType", value: function addType(builder, type) { builder.addFieldInt8(6, type, geometry_type_GeometryType.Unknown); } }, { key: "addParts", value: function addParts(builder, partsOffset) { builder.addFieldOffset(7, partsOffset, 0); } }, { key: "createPartsVector", value: function createPartsVector(builder, data) { builder.startVector(4, data.length, 4); for (var i = data.length - 1; i >= 0; i--) { builder.addOffset(data[i]); } return builder.endVector(); } }, { key: "startPartsVector", value: function startPartsVector(builder, numElems) { builder.startVector(4, numElems, 4); } }, { key: "endGeometry", value: function endGeometry(builder) { var offset = builder.endObject(); return offset; } }, { key: "createGeometry", value: function createGeometry(builder, endsOffset, xyOffset, zOffset, mOffset, tOffset, tmOffset, type, partsOffset) { Geometry.startGeometry(builder); Geometry.addEnds(builder, endsOffset); Geometry.addXy(builder, xyOffset); Geometry.addZ(builder, zOffset); Geometry.addM(builder, mOffset); Geometry.addT(builder, tOffset); Geometry.addTm(builder, tmOffset); Geometry.addType(builder, type); Geometry.addParts(builder, partsOffset); return Geometry.endGeometry(builder); } }]); return Geometry; }(); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/generic/geometry.js function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function geometry_buildGeometry(builder, parsedGeometry) { var xy = parsedGeometry.xy, z = parsedGeometry.z, ends = parsedGeometry.ends, parts = parsedGeometry.parts, type = parsedGeometry.type; if (parts) { var partOffsets = parts.map(function (part) { return geometry_buildGeometry(builder, part); }); var partsOffset = Geometry.createPartsVector(builder, partOffsets); Geometry.startGeometry(builder); Geometry.addParts(builder, partsOffset); Geometry.addType(builder, type); return Geometry.endGeometry(builder); } var xyOffset = Geometry.createXyVector(builder, xy); var zOffset; if (z) zOffset = Geometry.createZVector(builder, z); var endsOffset; if (ends) endsOffset = Geometry.createEndsVector(builder, ends); Geometry.startGeometry(builder); if (endsOffset) Geometry.addEnds(builder, endsOffset); Geometry.addXy(builder, xyOffset); if (zOffset) Geometry.addZ(builder, zOffset); Geometry.addType(builder, type); return Geometry.endGeometry(builder); } function geometry_flat(a, xy, z) { if (a.length === 0) return; if (Array.isArray(a[0])) { var _iterator = _createForOfIteratorHelper(a), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var sa = _step.value; geometry_flat(sa, xy, z); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { if (a.length === 2) xy.push.apply(xy, _toConsumableArray(a));else { xy.push(a[0], a[1]); z.push(a[2]); } } } function geometry_parseGeometry(geometry, headerGeomType) { var xy; var ends; var parts; var type = headerGeomType; if (type === GeometryType.Unknown) { type = geometry_toGeometryType(geometry.getType()); } if (type === GeometryType.MultiLineString) { if (geometry.getFlatCoordinates) xy = geometry.getFlatCoordinates(); var mlsEnds = geometry.getEnds(); if (mlsEnds.length > 1) ends = mlsEnds.map(function (e) { return e >> 1; }); } else if (type === GeometryType.Polygon) { if (geometry.getFlatCoordinates) xy = geometry.getFlatCoordinates(); var pEnds = geometry.getEnds(); if (pEnds.length > 1) ends = pEnds.map(function (e) { return e >> 1; }); } else if (type === GeometryType.MultiPolygon) { var mp = geometry; parts = mp.getPolygons().map(function (p) { return geometry_parseGeometry(p, GeometryType.Polygon); }); } else { if (geometry.getFlatCoordinates) xy = geometry.getFlatCoordinates(); } return { xy: xy, ends: ends, type: type, parts: parts }; } function pairFlatCoordinates(xy, z) { var newArray = []; for (var i = 0; i < xy.length; i += 2) { var a = [xy[i], xy[i + 1]]; if (z) a.push(z[i >> 1]); newArray.push(a); } return newArray; } function geometry_toGeometryType(name) { if (!name) return GeometryType.Unknown; var type = GeometryType[name]; return type; } ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/geojson/geometry.js function geojson_geometry_parseGeometry(geometry) { var cs = geometry.coordinates; var xy = []; var z = []; var ends; var parts; var type = toGeometryType(geometry.type); var end = 0; switch (geometry.type) { case 'Point': flat(cs, xy, z); break; case 'MultiPoint': case 'LineString': flat(cs, xy, z); break; case 'MultiLineString': case 'Polygon': { var css = cs; flat(css, xy, z); if (css.length > 1) ends = css.map(function (c) { return end += c.length; }); break; } case 'MultiPolygon': { var csss = cs; var geometries = csss.map(function (coordinates) { return { type: 'Polygon', coordinates: coordinates }; }); parts = geometries.map(geojson_geometry_parseGeometry); break; } } return { xy: xy, z: z.length > 0 ? z : undefined, ends: ends, type: type, parts: parts }; } function geometry_parseGC(geometry) { var type = toGeometryType(geometry.type); var parts = []; for (var i = 0; i < geometry.geometries.length; i++) { var g = geometry.geometries[i]; if (g.type === 'GeometryCollection') parts.push(geometry_parseGC(g));else parts.push(geojson_geometry_parseGeometry(g)); } return { type: type, parts: parts }; } function extractParts(xy, z, ends) { if (!ends || ends.length === 0) return [pairFlatCoordinates(xy, z)]; var s = 0; var xySlices = Array.from(ends).map(function (e) { return xy.slice(s, s = e << 1); }); var zSlices; if (z) { s = 0; zSlices = Array.from(ends).map(function (e) { return z.slice(s, s = e); }); } return xySlices.map(function (xy, i) { return pairFlatCoordinates(xy, zSlices ? zSlices[i] : undefined); }); } function toGeoJsonCoordinates(geometry, type) { var xy = geometry.xyArray(); var z = geometry.zArray(); switch (type) { case geometry_type_GeometryType.Point: { var a = Array.from(xy); if (z) a.push(z[0]); return a; } case geometry_type_GeometryType.MultiPoint: case geometry_type_GeometryType.LineString: return pairFlatCoordinates(xy, z); case geometry_type_GeometryType.MultiLineString: return extractParts(xy, z, geometry.endsArray()); case geometry_type_GeometryType.Polygon: return extractParts(xy, z, geometry.endsArray()); } } function fromGeometry(geometry, headerType) { var type = headerType; if (type === geometry_type_GeometryType.Unknown) { type = geometry.type(); } if (type === geometry_type_GeometryType.GeometryCollection) { var geometries = []; for (var i = 0; i < geometry.partsLength(); i++) { var part = geometry.parts(i); var partType = part.type(); geometries.push(fromGeometry(part, partType)); } return { type: geometry_type_GeometryType[type], geometries: geometries }; } else if (type === geometry_type_GeometryType.MultiPolygon) { var _geometries = []; for (var _i2 = 0; _i2 < geometry.partsLength(); _i2++) _geometries.push(fromGeometry(geometry.parts(_i2), geometry_type_GeometryType.Polygon)); return { type: geometry_type_GeometryType[type], coordinates: _geometries.map(function (g) { return g.coordinates; }) }; } var coordinates = toGeoJsonCoordinates(geometry, type); return { type: geometry_type_GeometryType[type], coordinates: coordinates }; } ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/flat-geobuf/column-type.js var column_type_ColumnType; (function (ColumnType) { ColumnType[ColumnType["Byte"] = 0] = "Byte"; ColumnType[ColumnType["UByte"] = 1] = "UByte"; ColumnType[ColumnType["Bool"] = 2] = "Bool"; ColumnType[ColumnType["Short"] = 3] = "Short"; ColumnType[ColumnType["UShort"] = 4] = "UShort"; ColumnType[ColumnType["Int"] = 5] = "Int"; ColumnType[ColumnType["UInt"] = 6] = "UInt"; ColumnType[ColumnType["Long"] = 7] = "Long"; ColumnType[ColumnType["ULong"] = 8] = "ULong"; ColumnType[ColumnType["Float"] = 9] = "Float"; ColumnType[ColumnType["Double"] = 10] = "Double"; ColumnType[ColumnType["String"] = 11] = "String"; ColumnType[ColumnType["Json"] = 12] = "Json"; ColumnType[ColumnType["DateTime"] = 13] = "DateTime"; ColumnType[ColumnType["Binary"] = 14] = "Binary"; })(column_type_ColumnType || (column_type_ColumnType = {})); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/flat-geobuf/column.js function column_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function column_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function column_createClass(Constructor, protoProps, staticProps) { if (protoProps) column_defineProperties(Constructor.prototype, protoProps); if (staticProps) column_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var column_Column = /*#__PURE__*/function () { function Column() { column_classCallCheck(this, Column); this.bb = null; this.bb_pos = 0; } column_createClass(Column, [{ key: "__init", value: function __init(i, bb) { this.bb_pos = i; this.bb = bb; return this; } }, { key: "name", value: function name(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 4); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "type", value: function type() { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? this.bb.readUint8(this.bb_pos + offset) : column_type_ColumnType.Byte; } }, { key: "title", value: function title(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 8); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "description", value: function description(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 10); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "width", value: function width() { var offset = this.bb.__offset(this.bb_pos, 12); return offset ? this.bb.readInt32(this.bb_pos + offset) : -1; } }, { key: "precision", value: function precision() { var offset = this.bb.__offset(this.bb_pos, 14); return offset ? this.bb.readInt32(this.bb_pos + offset) : -1; } }, { key: "scale", value: function scale() { var offset = this.bb.__offset(this.bb_pos, 16); return offset ? this.bb.readInt32(this.bb_pos + offset) : -1; } }, { key: "nullable", value: function nullable() { var offset = this.bb.__offset(this.bb_pos, 18); return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true; } }, { key: "unique", value: function unique() { var offset = this.bb.__offset(this.bb_pos, 20); return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; } }, { key: "primaryKey", value: function primaryKey() { var offset = this.bb.__offset(this.bb_pos, 22); return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; } }, { key: "metadata", value: function metadata(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 24); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }], [{ key: "getRootAsColumn", value: function getRootAsColumn(bb, obj) { return (obj || new Column()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "getSizePrefixedRootAsColumn", value: function getSizePrefixedRootAsColumn(bb, obj) { bb.setPosition(bb.position() + js_flatbuffers/* SIZE_PREFIX_LENGTH */.XU); return (obj || new Column()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "startColumn", value: function startColumn(builder) { builder.startObject(11); } }, { key: "addName", value: function addName(builder, nameOffset) { builder.addFieldOffset(0, nameOffset, 0); } }, { key: "addType", value: function addType(builder, type) { builder.addFieldInt8(1, type, column_type_ColumnType.Byte); } }, { key: "addTitle", value: function addTitle(builder, titleOffset) { builder.addFieldOffset(2, titleOffset, 0); } }, { key: "addDescription", value: function addDescription(builder, descriptionOffset) { builder.addFieldOffset(3, descriptionOffset, 0); } }, { key: "addWidth", value: function addWidth(builder, width) { builder.addFieldInt32(4, width, -1); } }, { key: "addPrecision", value: function addPrecision(builder, precision) { builder.addFieldInt32(5, precision, -1); } }, { key: "addScale", value: function addScale(builder, scale) { builder.addFieldInt32(6, scale, -1); } }, { key: "addNullable", value: function addNullable(builder, nullable) { builder.addFieldInt8(7, +nullable, +true); } }, { key: "addUnique", value: function addUnique(builder, unique) { builder.addFieldInt8(8, +unique, +false); } }, { key: "addPrimaryKey", value: function addPrimaryKey(builder, primaryKey) { builder.addFieldInt8(9, +primaryKey, +false); } }, { key: "addMetadata", value: function addMetadata(builder, metadataOffset) { builder.addFieldOffset(10, metadataOffset, 0); } }, { key: "endColumn", value: function endColumn(builder) { var offset = builder.endObject(); builder.requiredField(offset, 4); return offset; } }, { key: "createColumn", value: function createColumn(builder, nameOffset, type, titleOffset, descriptionOffset, width, precision, scale, nullable, unique, primaryKey, metadataOffset) { Column.startColumn(builder); Column.addName(builder, nameOffset); Column.addType(builder, type); Column.addTitle(builder, titleOffset); Column.addDescription(builder, descriptionOffset); Column.addWidth(builder, width); Column.addPrecision(builder, precision); Column.addScale(builder, scale); Column.addNullable(builder, nullable); Column.addUnique(builder, unique); Column.addPrimaryKey(builder, primaryKey); Column.addMetadata(builder, metadataOffset); return Column.endColumn(builder); } }]); return Column; }(); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/flat-geobuf/feature.js function feature_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function feature_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function feature_createClass(Constructor, protoProps, staticProps) { if (protoProps) feature_defineProperties(Constructor.prototype, protoProps); if (staticProps) feature_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var feature_Feature = /*#__PURE__*/function () { function Feature() { feature_classCallCheck(this, Feature); this.bb = null; this.bb_pos = 0; } feature_createClass(Feature, [{ key: "__init", value: function __init(i, bb) { this.bb_pos = i; this.bb = bb; return this; } }, { key: "geometry", value: function geometry(obj) { var offset = this.bb.__offset(this.bb_pos, 4); return offset ? (obj || new geometry_Geometry()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; } }, { key: "properties", value: function properties(index) { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; } }, { key: "propertiesLength", value: function propertiesLength() { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "propertiesArray", value: function propertiesArray() { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; } }, { key: "columns", value: function columns(index, obj) { var offset = this.bb.__offset(this.bb_pos, 8); return offset ? (obj || new column_Column()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; } }, { key: "columnsLength", value: function columnsLength() { var offset = this.bb.__offset(this.bb_pos, 8); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }], [{ key: "getRootAsFeature", value: function getRootAsFeature(bb, obj) { return (obj || new Feature()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "getSizePrefixedRootAsFeature", value: function getSizePrefixedRootAsFeature(bb, obj) { bb.setPosition(bb.position() + js_flatbuffers/* SIZE_PREFIX_LENGTH */.XU); return (obj || new Feature()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "startFeature", value: function startFeature(builder) { builder.startObject(3); } }, { key: "addGeometry", value: function addGeometry(builder, geometryOffset) { builder.addFieldOffset(0, geometryOffset, 0); } }, { key: "addProperties", value: function addProperties(builder, propertiesOffset) { builder.addFieldOffset(1, propertiesOffset, 0); } }, { key: "createPropertiesVector", value: function createPropertiesVector(builder, data) { builder.startVector(1, data.length, 1); for (var i = data.length - 1; i >= 0; i--) { builder.addInt8(data[i]); } return builder.endVector(); } }, { key: "startPropertiesVector", value: function startPropertiesVector(builder, numElems) { builder.startVector(1, numElems, 1); } }, { key: "addColumns", value: function addColumns(builder, columnsOffset) { builder.addFieldOffset(2, columnsOffset, 0); } }, { key: "createColumnsVector", value: function createColumnsVector(builder, data) { builder.startVector(4, data.length, 4); for (var i = data.length - 1; i >= 0; i--) { builder.addOffset(data[i]); } return builder.endVector(); } }, { key: "startColumnsVector", value: function startColumnsVector(builder, numElems) { builder.startVector(4, numElems, 4); } }, { key: "endFeature", value: function endFeature(builder) { var offset = builder.endObject(); return offset; } }, { key: "finishFeatureBuffer", value: function finishFeatureBuffer(builder, offset) { builder.finish(offset); } }, { key: "finishSizePrefixedFeatureBuffer", value: function finishSizePrefixedFeatureBuffer(builder, offset) { builder.finish(offset, undefined, true); } }, { key: "createFeature", value: function createFeature(builder, geometryOffset, propertiesOffset, columnsOffset) { Feature.startFeature(builder); Feature.addGeometry(builder, geometryOffset); Feature.addProperties(builder, propertiesOffset); Feature.addColumns(builder, columnsOffset); return Feature.endFeature(builder); } }]); return Feature; }(); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/generic/feature.js var textEncoder = new TextEncoder(); var textDecoder = new TextDecoder(); function fromFeature(feature, header, createGeometry, createFeature) { var columns = header.columns; var geometry = feature.geometry(); var simpleGeometry = createGeometry(geometry, header.geometryType); var properties = parseProperties(feature, columns); return createFeature(simpleGeometry, properties); } function feature_buildFeature(geometry, properties, header) { var columns = header.columns; var builder = new flatbuffers.Builder(); var offset = 0; var capacity = 1024; var bytes = new Uint8Array(capacity); var view = new DataView(bytes.buffer); var prep = function prep(size) { if (offset + size < capacity) return; capacity = Math.max(capacity + size, capacity * 2); var newBytes = new Uint8Array(capacity); newBytes.set(bytes); bytes = newBytes; view = new DataView(bytes.buffer); }; if (columns) { for (var i = 0; i < columns.length; i++) { var column = columns[i]; var value = properties[column.name]; if (value === null) continue; prep(2); view.setUint16(offset, i, true); offset += 2; switch (column.type) { case ColumnType.Bool: prep(1); view.setUint8(offset, value); offset += 1; break; case ColumnType.Short: prep(2); view.setInt16(offset, value, true); offset += 2; break; case ColumnType.UShort: prep(2); view.setUint16(offset, value, true); offset += 2; break; case ColumnType.Int: prep(4); view.setInt32(offset, value, true); offset += 4; break; case ColumnType.UInt: prep(4); view.setUint32(offset, value, true); offset += 4; break; case ColumnType.Long: prep(8); view.setBigInt64(offset, BigInt(value), true); offset += 8; break; case ColumnType.Float: prep(4); view.setFloat32(offset, value, true); offset += 4; break; case ColumnType.Double: prep(8); view.setFloat64(offset, value, true); offset += 8; break; case ColumnType.DateTime: case ColumnType.String: { var str = textEncoder.encode(value); prep(4); view.setUint32(offset, str.length, true); offset += 4; prep(str.length); bytes.set(str, offset); offset += str.length; break; } case ColumnType.Json: { var _str = textEncoder.encode(JSON.stringify(value)); prep(4); view.setUint32(offset, _str.length, true); offset += 4; prep(_str.length); bytes.set(_str, offset); offset += _str.length; break; } default: throw new Error('Unknown type ' + column.type); } } } var propertiesOffset = null; if (offset > 0) propertiesOffset = Feature.createPropertiesVector(builder, bytes.slice(0, offset)); var geometryOffset = buildGeometry(builder, geometry); Feature.startFeature(builder); Feature.addGeometry(builder, geometryOffset); if (propertiesOffset) Feature.addProperties(builder, propertiesOffset); var featureOffset = Feature.endFeature(builder); builder.finishSizePrefixed(featureOffset); return builder.asUint8Array(); } function parseProperties(feature, columns) { var properties = {}; if (!columns || columns.length === 0) return properties; var array = feature.propertiesArray(); if (!array) return properties; var view = new DataView(array.buffer, array.byteOffset); var length = feature.propertiesLength(); var offset = 0; while (offset < length) { var i = view.getUint16(offset, true); offset += 2; var column = columns[i]; var name = column.name; switch (column.type) { case column_type_ColumnType.Bool: { properties[name] = !!view.getUint8(offset); offset += 1; break; } case column_type_ColumnType.Byte: { properties[name] = view.getInt8(offset); offset += 1; break; } case column_type_ColumnType.UByte: { properties[name] = view.getUint8(offset); offset += 1; break; } case column_type_ColumnType.Short: { properties[name] = view.getInt16(offset, true); offset += 2; break; } case column_type_ColumnType.UShort: { properties[name] = view.getUint16(offset, true); offset += 2; break; } case column_type_ColumnType.Int: { properties[name] = view.getInt32(offset, true); offset += 4; break; } case column_type_ColumnType.UInt: { properties[name] = view.getUint32(offset, true); offset += 4; break; } case column_type_ColumnType.Long: { properties[name] = Number(view.getBigInt64(offset, true)); offset += 8; break; } case column_type_ColumnType.ULong: { properties[name] = Number(view.getBigUint64(offset, true)); offset += 8; break; } case column_type_ColumnType.Float: { properties[name] = view.getFloat32(offset, true); offset += 4; break; } case column_type_ColumnType.Double: { properties[name] = view.getFloat64(offset, true); offset += 8; break; } case column_type_ColumnType.DateTime: case column_type_ColumnType.String: { var _length = view.getUint32(offset, true); offset += 4; properties[name] = textDecoder.decode(array.subarray(offset, offset + _length)); offset += _length; break; } case column_type_ColumnType.Json: { var _length2 = view.getUint32(offset, true); offset += 4; var str = textDecoder.decode(array.subarray(offset, offset + _length2)); properties[name] = JSON.parse(str); offset += _length2; break; } default: throw new Error('Unknown type ' + column.type); } } return properties; } ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/geojson/feature.js function feature_fromFeature(feature, header) { var columns = header.columns; var geometry = fromGeometry(feature.geometry(), header.geometryType); var geoJsonfeature = { type: 'Feature', geometry: geometry, properties: parseProperties(feature, columns) }; return geoJsonfeature; } // EXTERNAL MODULE: ./node_modules/slice-source/dist/slice-source.js var slice_source = __webpack_require__(901); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/flat-geobuf/crs.js function crs_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function crs_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function crs_createClass(Constructor, protoProps, staticProps) { if (protoProps) crs_defineProperties(Constructor.prototype, protoProps); if (staticProps) crs_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var Crs = /*#__PURE__*/function () { function Crs() { crs_classCallCheck(this, Crs); this.bb = null; this.bb_pos = 0; } crs_createClass(Crs, [{ key: "__init", value: function __init(i, bb) { this.bb_pos = i; this.bb = bb; return this; } }, { key: "org", value: function org(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 4); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "code", value: function code() { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; } }, { key: "name", value: function name(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 8); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "description", value: function description(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 10); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "wkt", value: function wkt(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 12); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "codeString", value: function codeString(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 14); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }], [{ key: "getRootAsCrs", value: function getRootAsCrs(bb, obj) { return (obj || new Crs()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "getSizePrefixedRootAsCrs", value: function getSizePrefixedRootAsCrs(bb, obj) { bb.setPosition(bb.position() + js_flatbuffers/* SIZE_PREFIX_LENGTH */.XU); return (obj || new Crs()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "startCrs", value: function startCrs(builder) { builder.startObject(6); } }, { key: "addOrg", value: function addOrg(builder, orgOffset) { builder.addFieldOffset(0, orgOffset, 0); } }, { key: "addCode", value: function addCode(builder, code) { builder.addFieldInt32(1, code, 0); } }, { key: "addName", value: function addName(builder, nameOffset) { builder.addFieldOffset(2, nameOffset, 0); } }, { key: "addDescription", value: function addDescription(builder, descriptionOffset) { builder.addFieldOffset(3, descriptionOffset, 0); } }, { key: "addWkt", value: function addWkt(builder, wktOffset) { builder.addFieldOffset(4, wktOffset, 0); } }, { key: "addCodeString", value: function addCodeString(builder, codeStringOffset) { builder.addFieldOffset(5, codeStringOffset, 0); } }, { key: "endCrs", value: function endCrs(builder) { var offset = builder.endObject(); return offset; } }, { key: "createCrs", value: function createCrs(builder, orgOffset, code, nameOffset, descriptionOffset, wktOffset, codeStringOffset) { Crs.startCrs(builder); Crs.addOrg(builder, orgOffset); Crs.addCode(builder, code); Crs.addName(builder, nameOffset); Crs.addDescription(builder, descriptionOffset); Crs.addWkt(builder, wktOffset); Crs.addCodeString(builder, codeStringOffset); return Crs.endCrs(builder); } }]); return Crs; }(); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/flat-geobuf/header.js function header_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function header_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function header_createClass(Constructor, protoProps, staticProps) { if (protoProps) header_defineProperties(Constructor.prototype, protoProps); if (staticProps) header_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var header_Header = /*#__PURE__*/function () { function Header() { header_classCallCheck(this, Header); this.bb = null; this.bb_pos = 0; } header_createClass(Header, [{ key: "__init", value: function __init(i, bb) { this.bb_pos = i; this.bb = bb; return this; } }, { key: "name", value: function name(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 4); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "envelope", value: function envelope(index) { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; } }, { key: "envelopeLength", value: function envelopeLength() { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "envelopeArray", value: function envelopeArray() { var offset = this.bb.__offset(this.bb_pos, 6); return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; } }, { key: "geometryType", value: function geometryType() { var offset = this.bb.__offset(this.bb_pos, 8); return offset ? this.bb.readUint8(this.bb_pos + offset) : geometry_type_GeometryType.Unknown; } }, { key: "hasZ", value: function hasZ() { var offset = this.bb.__offset(this.bb_pos, 10); return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; } }, { key: "hasM", value: function hasM() { var offset = this.bb.__offset(this.bb_pos, 12); return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; } }, { key: "hasT", value: function hasT() { var offset = this.bb.__offset(this.bb_pos, 14); return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; } }, { key: "hasTm", value: function hasTm() { var offset = this.bb.__offset(this.bb_pos, 16); return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; } }, { key: "columns", value: function columns(index, obj) { var offset = this.bb.__offset(this.bb_pos, 18); return offset ? (obj || new column_Column()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; } }, { key: "columnsLength", value: function columnsLength() { var offset = this.bb.__offset(this.bb_pos, 18); return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; } }, { key: "featuresCount", value: function featuresCount() { var offset = this.bb.__offset(this.bb_pos, 20); return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); } }, { key: "indexNodeSize", value: function indexNodeSize() { var offset = this.bb.__offset(this.bb_pos, 22); return offset ? this.bb.readUint16(this.bb_pos + offset) : 16; } }, { key: "crs", value: function crs(obj) { var offset = this.bb.__offset(this.bb_pos, 24); return offset ? (obj || new Crs()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; } }, { key: "title", value: function title(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 26); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "description", value: function description(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 28); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }, { key: "metadata", value: function metadata(optionalEncoding) { var offset = this.bb.__offset(this.bb_pos, 30); return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; } }], [{ key: "getRootAsHeader", value: function getRootAsHeader(bb, obj) { return (obj || new Header()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "getSizePrefixedRootAsHeader", value: function getSizePrefixedRootAsHeader(bb, obj) { bb.setPosition(bb.position() + js_flatbuffers/* SIZE_PREFIX_LENGTH */.XU); return (obj || new Header()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } }, { key: "startHeader", value: function startHeader(builder) { builder.startObject(14); } }, { key: "addName", value: function addName(builder, nameOffset) { builder.addFieldOffset(0, nameOffset, 0); } }, { key: "addEnvelope", value: function addEnvelope(builder, envelopeOffset) { builder.addFieldOffset(1, envelopeOffset, 0); } }, { key: "createEnvelopeVector", value: function createEnvelopeVector(builder, data) { builder.startVector(8, data.length, 8); for (var i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]); } return builder.endVector(); } }, { key: "startEnvelopeVector", value: function startEnvelopeVector(builder, numElems) { builder.startVector(8, numElems, 8); } }, { key: "addGeometryType", value: function addGeometryType(builder, geometryType) { builder.addFieldInt8(2, geometryType, geometry_type_GeometryType.Unknown); } }, { key: "addHasZ", value: function addHasZ(builder, hasZ) { builder.addFieldInt8(3, +hasZ, +false); } }, { key: "addHasM", value: function addHasM(builder, hasM) { builder.addFieldInt8(4, +hasM, +false); } }, { key: "addHasT", value: function addHasT(builder, hasT) { builder.addFieldInt8(5, +hasT, +false); } }, { key: "addHasTm", value: function addHasTm(builder, hasTm) { builder.addFieldInt8(6, +hasTm, +false); } }, { key: "addColumns", value: function addColumns(builder, columnsOffset) { builder.addFieldOffset(7, columnsOffset, 0); } }, { key: "createColumnsVector", value: function createColumnsVector(builder, data) { builder.startVector(4, data.length, 4); for (var i = data.length - 1; i >= 0; i--) { builder.addOffset(data[i]); } return builder.endVector(); } }, { key: "startColumnsVector", value: function startColumnsVector(builder, numElems) { builder.startVector(4, numElems, 4); } }, { key: "addFeaturesCount", value: function addFeaturesCount(builder, featuresCount) { builder.addFieldInt64(8, featuresCount, BigInt('0')); } }, { key: "addIndexNodeSize", value: function addIndexNodeSize(builder, indexNodeSize) { builder.addFieldInt16(9, indexNodeSize, 16); } }, { key: "addCrs", value: function addCrs(builder, crsOffset) { builder.addFieldOffset(10, crsOffset, 0); } }, { key: "addTitle", value: function addTitle(builder, titleOffset) { builder.addFieldOffset(11, titleOffset, 0); } }, { key: "addDescription", value: function addDescription(builder, descriptionOffset) { builder.addFieldOffset(12, descriptionOffset, 0); } }, { key: "addMetadata", value: function addMetadata(builder, metadataOffset) { builder.addFieldOffset(13, metadataOffset, 0); } }, { key: "endHeader", value: function endHeader(builder) { var offset = builder.endObject(); return offset; } }, { key: "finishHeaderBuffer", value: function finishHeaderBuffer(builder, offset) { builder.finish(offset); } }, { key: "finishSizePrefixedHeaderBuffer", value: function finishSizePrefixedHeaderBuffer(builder, offset) { builder.finish(offset, undefined, true); } }]); return Header; }(); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/header-meta.js function fromByteBuffer(bb) { var header = header_Header.getRootAsHeader(bb); var featuresCount = header.featuresCount(); var indexNodeSize = header.indexNodeSize(); var columns = []; for (var j = 0; j < header.columnsLength(); j++) { var column = header.columns(j); if (!column) throw new Error('Column unexpectedly missing'); if (!column.name()) throw new Error('Column name unexpectedly missing'); columns.push({ name: column.name(), type: column.type(), title: column.title(), description: column.description(), width: column.width(), precision: column.precision(), scale: column.scale(), nullable: column.nullable(), unique: column.unique(), primary_key: column.primaryKey() }); } var crs = header.crs(); var crsMeta = crs ? { org: crs.org(), code: crs.code(), name: crs.name(), description: crs.description(), wkt: crs.wkt(), code_string: crs.codeString() } : null; var headerMeta = { geometryType: header.geometryType(), columns: columns, envelope: null, featuresCount: Number(featuresCount), indexNodeSize: indexNodeSize, crs: crsMeta, title: header.title(), description: header.description(), metadata: header.metadata() }; return headerMeta; } // EXTERNAL MODULE: ./node_modules/@repeaterjs/repeater/cjs/repeater.js var repeater = __webpack_require__(982); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/config.js function config_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function config_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function config_createClass(Constructor, protoProps, staticProps) { if (protoProps) config_defineProperties(Constructor.prototype, protoProps); if (staticProps) config_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var config_Config = /*#__PURE__*/function () { function Config() { config_classCallCheck(this, Config); this._extraRequestThreshold = 256 * 1024; } config_createClass(Config, [{ key: "extraRequestThreshold", value: function extraRequestThreshold() { return this._extraRequestThreshold; } }, { key: "setExtraRequestThreshold", value: function setExtraRequestThreshold(bytes) { if (bytes < 0) { throw new Error('extraRequestThreshold cannot be negative'); } this._extraRequestThreshold = bytes; } }]); return Config; }(); config_Config.global = new config_Config(); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/logger.js function logger_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function logger_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function logger_createClass(Constructor, protoProps, staticProps) { if (protoProps) logger_defineProperties(Constructor.prototype, protoProps); if (staticProps) logger_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var LogLevel; (function (LogLevel) { LogLevel[LogLevel["Debug"] = 0] = "Debug"; LogLevel[LogLevel["Info"] = 1] = "Info"; LogLevel[LogLevel["Warn"] = 2] = "Warn"; LogLevel[LogLevel["Error"] = 3] = "Error"; })(LogLevel || (LogLevel = {})); var Logger = /*#__PURE__*/function () { function Logger() { logger_classCallCheck(this, Logger); } logger_createClass(Logger, null, [{ key: "debug", value: function debug() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } this.log.apply(this, [LogLevel.Debug].concat(args)); } }, { key: "info", value: function info() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } this.log.apply(this, [LogLevel.Info].concat(args)); } }, { key: "warn", value: function warn() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } this.log.apply(this, [LogLevel.Warn].concat(args)); } }, { key: "error", value: function error() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } this.log.apply(this, [LogLevel.Error].concat(args)); } }, { key: "log", value: function log(level) { if (this.logLevel > level) { return; } for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { args[_key5 - 1] = arguments[_key5]; } switch (level) { case LogLevel.Debug: { var _console; (_console = console).debug.apply(_console, args); break; } case LogLevel.Info: { var _console2; (_console2 = console).info.apply(_console2, args); break; } case LogLevel.Warn: { var _console3; (_console3 = console).warn.apply(_console3, args); break; } case LogLevel.Error: { var _console4; (_console4 = console).error.apply(_console4, args); break; } } } }]); return Logger; }(); Logger.logLevel = LogLevel.Info; ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/packedrtree.js function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || packedrtree_unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function packedrtree_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return packedrtree_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return packedrtree_arrayLikeToArray(o, minLen); } function packedrtree_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function packedrtree_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function packedrtree_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function packedrtree_createClass(Constructor, protoProps, staticProps) { if (protoProps) packedrtree_defineProperties(Constructor.prototype, protoProps); if (staticProps) packedrtree_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _awaitAsyncGenerator(value) { return new _OverloadYield(value, 0); } function _wrapAsyncGenerator(fn) { return function () { return new _AsyncGenerator(fn.apply(this, arguments)); }; } function _AsyncGenerator(gen) { var front, back; function resume(key, arg) { try { var result = gen[key](arg), value = result.value, overloaded = value instanceof _OverloadYield; Promise.resolve(overloaded ? value.v : value).then(function (arg) { if (overloaded) { var nextKey = "return" === key ? "return" : "next"; if (!value.k || arg.done) return resume(nextKey, arg); arg = gen[nextKey](arg).value; } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: !0 }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: !1 }); } (front = front.next) ? resume(front.key, front.arg) : back = null; } this._invoke = function (key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; back ? back = back.next = request : (front = back = request, resume(key, arg)); }); }, "function" != typeof gen["return"] && (this["return"] = void 0); } _AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }, _AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }, _AsyncGenerator.prototype["throw"] = function (arg) { return this._invoke("throw", arg); }, _AsyncGenerator.prototype["return"] = function (arg) { return this._invoke("return", arg); }; function _OverloadYield(value, kind) { this.v = value, this.k = kind; } var NODE_ITEM_LEN = 8 * 4 + 8; var DEFAULT_NODE_SIZE = 16; function calcTreeSize(numItems, nodeSize) { nodeSize = Math.min(Math.max(+nodeSize, 2), 65535); var n = numItems; var numNodes = n; do { n = Math.ceil(n / nodeSize); numNodes += n; } while (n !== 1); return numNodes * NODE_ITEM_LEN; } function generateLevelBounds(numItems, nodeSize) { if (nodeSize < 2) throw new Error('Node size must be at least 2'); if (numItems === 0) throw new Error('Number of items must be greater than 0'); var n = numItems; var numNodes = n; var levelNumNodes = [n]; do { n = Math.ceil(n / nodeSize); numNodes += n; levelNumNodes.push(n); } while (n !== 1); var levelOffsets = []; n = numNodes; for (var _i = 0, _levelNumNodes = levelNumNodes; _i < _levelNumNodes.length; _i++) { var size = _levelNumNodes[_i]; levelOffsets.push(n - size); n -= size; } levelOffsets.reverse(); levelNumNodes.reverse(); var levelBounds = []; for (var i = 0; i < levelNumNodes.length; i++) levelBounds.push([levelOffsets[i], levelOffsets[i] + levelNumNodes[i]]); levelBounds.reverse(); return levelBounds; } function streamSearch(_x, _x2, _x3, _x4) { return _streamSearch.apply(this, arguments); } function _streamSearch() { _streamSearch = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(numItems, nodeSize, rect, readNode) { var NodeRange, minX, minY, maxX, maxY, levelBounds, leafNodesOffset, rootNodeRange, queue, _loop; return _regeneratorRuntime().wrap(function _callee$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: NodeRange = /*#__PURE__*/function () { function NodeRange(nodes, level) { packedrtree_classCallCheck(this, NodeRange); this._level = level; this.nodes = nodes; } packedrtree_createClass(NodeRange, [{ key: "level", value: function level() { return this._level; } }, { key: "startNode", value: function startNode() { return this.nodes[0]; } }, { key: "endNode", value: function endNode() { return this.nodes[1]; } }, { key: "extendEndNodeToNewOffset", value: function extendEndNodeToNewOffset(newOffset) { console.assert(newOffset > this.nodes[1]); this.nodes[1] = newOffset; } }, { key: "toString", value: function toString() { return "[NodeRange level: ".concat(this._level, ", nodes: ").concat(this.nodes[0], "-").concat(this.nodes[1], "]"); } }]); return NodeRange; }(); minX = rect.minX, minY = rect.minY, maxX = rect.maxX, maxY = rect.maxY; Logger.info("tree items: ".concat(numItems, ", nodeSize: ").concat(nodeSize)); levelBounds = generateLevelBounds(numItems, nodeSize); leafNodesOffset = levelBounds[0][0]; rootNodeRange = function () { var range = [0, 1]; var level = levelBounds.length - 1; return new NodeRange(range, level); }(); queue = [rootNodeRange]; Logger.debug("starting stream search with queue: ".concat(queue, ", numItems: ").concat(numItems, ", nodeSize: ").concat(nodeSize, ", levelBounds: ").concat(levelBounds)); _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() { var nodeRange, nodeIndex, isLeafNode, _levelBounds$nodeRang, levelBound, end, length, buffer, float64Array, uint32Array, _loop2, pos, _ret; return _regeneratorRuntime().wrap(function _loop$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: nodeRange = queue.shift(); Logger.debug("popped node: ".concat(nodeRange, ", queueLength: ").concat(queue.length)); nodeIndex = nodeRange.startNode(); isLeafNode = nodeIndex >= leafNodesOffset; _levelBounds$nodeRang = _slicedToArray(levelBounds[nodeRange.level()], 2), levelBound = _levelBounds$nodeRang[1]; end = Math.min(nodeRange.endNode() + nodeSize, levelBound); length = end - nodeIndex; _context2.next = 9; return _awaitAsyncGenerator(readNode(nodeIndex * NODE_ITEM_LEN, length * NODE_ITEM_LEN)); case 9: buffer = _context2.sent; float64Array = new Float64Array(buffer); uint32Array = new Uint32Array(buffer); _loop2 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop2(pos) { var nodePos, low32Offset, high32Offset, offset, featureLength, extraRequestThresholdNodes, nearestNodeRange, newNodeRange; return _regeneratorRuntime().wrap(function _loop2$(_context) { while (1) switch (_context.prev = _context.next) { case 0: nodePos = (pos - nodeIndex) * 5; if (!(maxX < float64Array[nodePos + 0])) { _context.next = 3; break; } return _context.abrupt("return", "continue"); case 3: if (!(maxY < float64Array[nodePos + 1])) { _context.next = 5; break; } return _context.abrupt("return", "continue"); case 5: if (!(minX > float64Array[nodePos + 2])) { _context.next = 7; break; } return _context.abrupt("return", "continue"); case 7: if (!(minY > float64Array[nodePos + 3])) { _context.next = 9; break; } return _context.abrupt("return", "continue"); case 9: low32Offset = uint32Array[(nodePos << 1) + 8]; high32Offset = uint32Array[(nodePos << 1) + 9]; offset = readUint52(high32Offset, low32Offset); if (!isLeafNode) { _context.next = 17; break; } featureLength = function () { if (pos < numItems - 1) { var nextPos = (pos - nodeIndex + 1) * 5; var _low32Offset = uint32Array[(nextPos << 1) + 8]; var _high32Offset = uint32Array[(nextPos << 1) + 9]; var nextOffset = readUint52(_high32Offset, _low32Offset); return nextOffset - offset; } else { return null; } }(); _context.next = 16; return [offset, pos - leafNodesOffset, featureLength]; case 16: return _context.abrupt("return", "continue"); case 17: extraRequestThresholdNodes = config_Config.global.extraRequestThreshold() / NODE_ITEM_LEN; nearestNodeRange = queue[queue.length - 1]; if (!(nearestNodeRange !== undefined && nearestNodeRange.level() == nodeRange.level() - 1 && offset < nearestNodeRange.endNode() + extraRequestThresholdNodes)) { _context.next = 23; break; } Logger.debug("Merging \"nodeRange\" request into existing range: ".concat(nearestNodeRange, ", newOffset: ").concat(nearestNodeRange.endNode(), " -> ").concat(offset)); nearestNodeRange.extendEndNodeToNewOffset(offset); return _context.abrupt("return", "continue"); case 23: newNodeRange = function () { var level = nodeRange.level() - 1; var range = [offset, offset + 1]; return new NodeRange(range, level); }(); if (nearestNodeRange !== undefined && nearestNodeRange.level() == newNodeRange.level()) { Logger.info("Same level, but too far away. Pushing new request at offset: ".concat(offset, " rather than merging with distant ").concat(nearestNodeRange)); } else { Logger.info("Pushing new level for ".concat(newNodeRange, " onto queue with nearestNodeRange: ").concat(nearestNodeRange, " since there's not already a range for this level.")); } queue.push(newNodeRange); case 26: case "end": return _context.stop(); } }, _loop2); }); pos = nodeIndex; case 14: if (!(pos < end)) { _context2.next = 22; break; } return _context2.delegateYield(_loop2(pos), "t0", 16); case 16: _ret = _context2.t0; if (!(_ret === "continue")) { _context2.next = 19; break; } return _context2.abrupt("continue", 19); case 19: pos++; _context2.next = 14; break; case 22: case "end": return _context2.stop(); } }, _loop); }); case 9: if (!(queue.length != 0)) { _context3.next = 13; break; } return _context3.delegateYield(_loop(), "t0", 11); case 11: _context3.next = 9; break; case 13: case "end": return _context3.stop(); } }, _callee); })); return _streamSearch.apply(this, arguments); } function readUint52(high32Bits, low32Bits) { if ((high32Bits & 0xfff00000) != 0) { throw Error('integer is too large to be safely represented'); } var result = low32Bits + high32Bits * Math.pow(2, 32); return result; } ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/constants.js var constants_magicbytes = new Uint8Array([0x66, 0x67, 0x62, 0x03, 0x66, 0x67, 0x62, 0x00]); var SIZE_PREFIX_LEN = 4; ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/http-reader.js function http_reader_typeof(obj) { "@babel/helpers - typeof"; return http_reader_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, http_reader_typeof(obj); } function http_reader_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = http_reader_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function http_reader_slicedToArray(arr, i) { return http_reader_arrayWithHoles(arr) || http_reader_iterableToArrayLimit(arr, i) || http_reader_unsupportedIterableToArray(arr, i) || http_reader_nonIterableRest(); } function http_reader_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function http_reader_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return http_reader_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return http_reader_arrayLikeToArray(o, minLen); } function http_reader_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function http_reader_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function http_reader_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function http_reader_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ http_reader_regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == http_reader_typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function http_reader_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function http_reader_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function http_reader_createClass(Constructor, protoProps, staticProps) { if (protoProps) http_reader_defineProperties(Constructor.prototype, protoProps); if (staticProps) http_reader_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function http_reader_wrapAsyncGenerator(fn) { return function () { return new http_reader_AsyncGenerator(fn.apply(this, arguments)); }; } function http_reader_AsyncGenerator(gen) { var front, back; function resume(key, arg) { try { var result = gen[key](arg), value = result.value, overloaded = value instanceof http_reader_OverloadYield; Promise.resolve(overloaded ? value.v : value).then(function (arg) { if (overloaded) { var nextKey = "return" === key ? "return" : "next"; if (!value.k || arg.done) return resume(nextKey, arg); arg = gen[nextKey](arg).value; } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: !0 }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: !1 }); } (front = front.next) ? resume(front.key, front.arg) : back = null; } this._invoke = function (key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; back ? back = back.next = request : (front = back = request, resume(key, arg)); }); }, "function" != typeof gen["return"] && (this["return"] = void 0); } http_reader_AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }, http_reader_AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }, http_reader_AsyncGenerator.prototype["throw"] = function (arg) { return this._invoke("throw", arg); }, http_reader_AsyncGenerator.prototype["return"] = function (arg) { return this._invoke("return", arg); }; function http_reader_awaitAsyncGenerator(value) { return new http_reader_OverloadYield(value, 0); } function _asyncGeneratorDelegate(inner) { var iter = {}, waiting = !1; function pump(key, value) { return waiting = !0, value = new Promise(function (resolve) { resolve(inner[key](value)); }), { done: !1, value: new http_reader_OverloadYield(value, 1) }; } return iter["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () { return this; }, iter.next = function (value) { return waiting ? (waiting = !1, value) : pump("next", value); }, "function" == typeof inner["throw"] && (iter["throw"] = function (value) { if (waiting) throw waiting = !1, value; return pump("throw", value); }), "function" == typeof inner["return"] && (iter["return"] = function (value) { return waiting ? (waiting = !1, value) : pump("return", value); }), iter; } function http_reader_OverloadYield(value, kind) { this.v = value, this.k = kind; } function _asyncIterator(iterable) { var method, async, sync, retry = 2; for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { if (async && null != (method = iterable[async])) return method.call(iterable); if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); async = "@@asyncIterator", sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); } function AsyncFromSyncIterator(s) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { this.s = s, this.n = s.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, "return": function _return(value) { var ret = this.s["return"]; return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, "throw": function _throw(value) { var thr = this.s["return"]; return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(s); } var HttpReader = /*#__PURE__*/function () { function HttpReader(headerClient, header, headerLength, indexLength) { http_reader_classCallCheck(this, HttpReader); this.headerClient = headerClient; this.header = header; this.headerLength = headerLength; this.indexLength = indexLength; } http_reader_createClass(HttpReader, [{ key: "selectBbox", value: function selectBbox(rect) { var _this = this; return http_reader_wrapAsyncGenerator( /*#__PURE__*/http_reader_regeneratorRuntime().mark(function _callee2() { var lengthBeforeTree, bufferedClient, readNode, batches, currentBatch, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, searchResult, _searchResult2, featureOffset, _searchResult4, featureLength, guessLength, prevFeature, gap, promises; return http_reader_regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: lengthBeforeTree = _this.lengthBeforeTree(); bufferedClient = _this.headerClient; readNode = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/http_reader_regeneratorRuntime().mark(function _callee(offsetIntoTree, size) { var minReqLength; return http_reader_regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: minReqLength = 0; return _context.abrupt("return", bufferedClient.getRange(lengthBeforeTree + offsetIntoTree, size, minReqLength, 'index')); case 2: case "end": return _context.stop(); } }, _callee); })); return function readNode(_x, _x2) { return _ref.apply(this, arguments); }; }(); batches = []; currentBatch = []; _iteratorAbruptCompletion = false; _didIteratorError = false; _context2.prev = 7; _iterator = _asyncIterator(streamSearch(_this.header.featuresCount, _this.header.indexNodeSize, rect, readNode)); case 9: _context2.next = 11; return http_reader_awaitAsyncGenerator(_iterator.next()); case 11: if (!(_iteratorAbruptCompletion = !(_step = _context2.sent).done)) { _context2.next = 26; break; } searchResult = _step.value; _searchResult2 = http_reader_slicedToArray(searchResult, 2), featureOffset = _searchResult2[0]; _searchResult4 = http_reader_slicedToArray(searchResult, 3), featureLength = _searchResult4[2]; if (!featureLength) { Logger.info('final feature'); guessLength = config_Config.global.extraRequestThreshold(); featureLength = guessLength; } if (!(currentBatch.length == 0)) { _context2.next = 19; break; } currentBatch.push([featureOffset, featureLength]); return _context2.abrupt("continue", 23); case 19: prevFeature = currentBatch[currentBatch.length - 1]; gap = featureOffset - (prevFeature[0] + prevFeature[1]); if (gap > config_Config.global.extraRequestThreshold()) { Logger.info("Pushing new feature batch, since gap ".concat(gap, " was too large")); batches.push(currentBatch); currentBatch = []; } currentBatch.push([featureOffset, featureLength]); case 23: _iteratorAbruptCompletion = false; _context2.next = 9; break; case 26: _context2.next = 32; break; case 28: _context2.prev = 28; _context2.t0 = _context2["catch"](7); _didIteratorError = true; _iteratorError = _context2.t0; case 32: _context2.prev = 32; _context2.prev = 33; if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) { _context2.next = 37; break; } _context2.next = 37; return http_reader_awaitAsyncGenerator(_iterator["return"]()); case 37: _context2.prev = 37; if (!_didIteratorError) { _context2.next = 40; break; } throw _iteratorError; case 40: return _context2.finish(37); case 41: return _context2.finish(32); case 42: _this.headerClient.logUsage('header+index'); if (currentBatch.length > 0) { batches.push(currentBatch); } promises = batches.flatMap(function (batch) { return _this.readFeatureBatch(batch); }); return _context2.delegateYield(_asyncGeneratorDelegate(_asyncIterator(repeater/* Repeater.merge */.ZN.merge(promises)), http_reader_awaitAsyncGenerator), "t1", 46); case 46: case "end": return _context2.stop(); } }, _callee2, null, [[7, 28, 32, 42], [33,, 37, 41]]); }))(); } }, { key: "lengthBeforeTree", value: function lengthBeforeTree() { return constants_magicbytes.length + SIZE_PREFIX_LEN + this.headerLength; } }, { key: "lengthBeforeFeatures", value: function lengthBeforeFeatures() { return this.lengthBeforeTree() + this.indexLength; } }, { key: "buildFeatureClient", value: function buildFeatureClient() { return new BufferedHttpRangeClient(this.headerClient.httpClient); } }, { key: "readFeatureBatch", value: function readFeatureBatch(batch) { var _this2 = this; return http_reader_wrapAsyncGenerator( /*#__PURE__*/http_reader_regeneratorRuntime().mark(function _callee3() { var _batch$, firstFeatureOffset, _batch, lastFeatureOffset, lastFeatureLength, batchStart, batchEnd, batchSize, featureClient, _iterator2, _step2, _step2$value2, featureOffset; return http_reader_regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _batch$ = http_reader_slicedToArray(batch[0], 1), firstFeatureOffset = _batch$[0]; _batch = http_reader_slicedToArray(batch[batch.length - 1], 2), lastFeatureOffset = _batch[0], lastFeatureLength = _batch[1]; batchStart = firstFeatureOffset; batchEnd = lastFeatureOffset + lastFeatureLength; batchSize = batchEnd - batchStart; featureClient = _this2.buildFeatureClient(); _iterator2 = http_reader_createForOfIteratorHelper(batch); _context3.prev = 7; _iterator2.s(); case 9: if ((_step2 = _iterator2.n()).done) { _context3.next = 17; break; } _step2$value2 = http_reader_slicedToArray(_step2.value, 1), featureOffset = _step2$value2[0]; _context3.next = 13; return http_reader_awaitAsyncGenerator(_this2.readFeature(featureClient, featureOffset, batchSize)); case 13: _context3.next = 15; return _context3.sent; case 15: _context3.next = 9; break; case 17: _context3.next = 22; break; case 19: _context3.prev = 19; _context3.t0 = _context3["catch"](7); _iterator2.e(_context3.t0); case 22: _context3.prev = 22; _iterator2.f(); return _context3.finish(22); case 25: featureClient.logUsage('feature'); case 26: case "end": return _context3.stop(); } }, _callee3, null, [[7, 19, 22, 25]]); }))(); } }, { key: "readFeature", value: function () { var _readFeature = _asyncToGenerator( /*#__PURE__*/http_reader_regeneratorRuntime().mark(function _callee4(featureClient, featureOffset, minFeatureReqLength) { var offset, featureLength, _bytes, byteBuffer, bytes, bytesAligned, bb; return http_reader_regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: offset = featureOffset + this.lengthBeforeFeatures(); _context4.next = 3; return featureClient.getRange(offset, 4, minFeatureReqLength, 'feature length'); case 3: _bytes = _context4.sent; featureLength = new DataView(_bytes).getUint32(0, true); _context4.next = 7; return featureClient.getRange(offset + 4, featureLength, minFeatureReqLength, 'feature data'); case 7: byteBuffer = _context4.sent; bytes = new Uint8Array(byteBuffer); bytesAligned = new Uint8Array(featureLength + SIZE_PREFIX_LEN); bytesAligned.set(bytes, SIZE_PREFIX_LEN); bb = new js_flatbuffers/* ByteBuffer */.cZ(bytesAligned); bb.setPosition(SIZE_PREFIX_LEN); return _context4.abrupt("return", feature_Feature.getRootAsFeature(bb)); case 14: case "end": return _context4.stop(); } }, _callee4, this); })); function readFeature(_x3, _x4, _x5) { return _readFeature.apply(this, arguments); } return readFeature; }() }], [{ key: "open", value: function () { var _open = _asyncToGenerator( /*#__PURE__*/http_reader_regeneratorRuntime().mark(function _callee5(url) { var assumedHeaderLength, headerClient, assumedIndexLength, minReqLength, _bytes2, headerLength, _bytes3, HEADER_MAX_BUFFER_SIZE, bytes, bb, header, indexLength; return http_reader_regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: assumedHeaderLength = 2024; headerClient = new BufferedHttpRangeClient(url); assumedIndexLength = function () { var assumedBranchingFactor = DEFAULT_NODE_SIZE; var prefetchedLayers = 3; var result = 0; var i; for (i = 0; i < prefetchedLayers; i++) { var layer_width = Math.pow(assumedBranchingFactor, i) * NODE_ITEM_LEN; result += layer_width; } return result; }(); minReqLength = assumedHeaderLength + assumedIndexLength; Logger.debug("fetching header. minReqLength: ".concat(minReqLength, " (assumedHeaderLength: ").concat(assumedHeaderLength, ", assumedIndexLength: ").concat(assumedIndexLength, ")")); _context5.t0 = Uint8Array; _context5.next = 8; return headerClient.getRange(0, 8, minReqLength, 'header'); case 8: _context5.t1 = _context5.sent; _bytes2 = new _context5.t0(_context5.t1); if (_bytes2.subarray(0, 3).every(function (v, i) { return constants_magicbytes[i] === v; })) { _context5.next = 13; break; } Logger.error("bytes: ".concat(_bytes2, " != ").concat(constants_magicbytes)); throw new Error('Not a FlatGeobuf file'); case 13: Logger.debug('magic bytes look good'); _context5.next = 16; return headerClient.getRange(8, 4, minReqLength, 'header'); case 16: _bytes3 = _context5.sent; headerLength = new DataView(_bytes3).getUint32(0, true); HEADER_MAX_BUFFER_SIZE = 1048576 * 10; if (!(headerLength > HEADER_MAX_BUFFER_SIZE || headerLength < 8)) { _context5.next = 21; break; } throw new Error('Invalid header size'); case 21: Logger.debug("headerLength: ".concat(headerLength)); _context5.next = 24; return headerClient.getRange(12, headerLength, minReqLength, 'header'); case 24: bytes = _context5.sent; bb = new js_flatbuffers/* ByteBuffer */.cZ(new Uint8Array(bytes)); header = fromByteBuffer(bb); indexLength = calcTreeSize(header.featuresCount, header.indexNodeSize); Logger.debug('completed: opening http reader'); return _context5.abrupt("return", new HttpReader(headerClient, header, headerLength, indexLength)); case 30: case "end": return _context5.stop(); } }, _callee5); })); function open(_x6) { return _open.apply(this, arguments); } return open; }() }]); return HttpReader; }(); var BufferedHttpRangeClient = /*#__PURE__*/function () { function BufferedHttpRangeClient(source) { http_reader_classCallCheck(this, BufferedHttpRangeClient); this.bytesEverUsed = 0; this.bytesEverFetched = 0; this.buffer = new ArrayBuffer(0); this.head = 0; if (typeof source === 'string') { this.httpClient = new HttpRangeClient(source); } else { this.httpClient = source; } } http_reader_createClass(BufferedHttpRangeClient, [{ key: "getRange", value: function () { var _getRange = _asyncToGenerator( /*#__PURE__*/http_reader_regeneratorRuntime().mark(function _callee6(start, length, minReqLength, purpose) { var start_i, end_i, lengthToFetch; return http_reader_regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: this.bytesEverUsed += length; start_i = start - this.head; end_i = start_i + length; if (!(start_i >= 0 && end_i <= this.buffer.byteLength)) { _context6.next = 5; break; } return _context6.abrupt("return", this.buffer.slice(start_i, end_i)); case 5: lengthToFetch = Math.max(length, minReqLength); this.bytesEverFetched += lengthToFetch; Logger.debug("requesting for new Range: ".concat(start, "-").concat(start + length - 1)); _context6.next = 10; return this.httpClient.getRange(start, lengthToFetch, purpose); case 10: this.buffer = _context6.sent; this.head = start; return _context6.abrupt("return", this.buffer.slice(0, length)); case 13: case "end": return _context6.stop(); } }, _callee6, this); })); function getRange(_x7, _x8, _x9, _x10) { return _getRange.apply(this, arguments); } return getRange; }() }, { key: "logUsage", value: function logUsage(purpose) { var category = purpose.split(' ')[0]; var used = this.bytesEverUsed; var requested = this.bytesEverFetched; var efficiency = (100.0 * used / requested).toFixed(2); Logger.info("".concat(category, " bytes used/requested: ").concat(used, " / ").concat(requested, " = ").concat(efficiency, "%")); } }]); return BufferedHttpRangeClient; }(); var HttpRangeClient = /*#__PURE__*/function () { function HttpRangeClient(url) { http_reader_classCallCheck(this, HttpRangeClient); this.requestsEverMade = 0; this.bytesEverRequested = 0; this.url = url; } http_reader_createClass(HttpRangeClient, [{ key: "getRange", value: function () { var _getRange2 = _asyncToGenerator( /*#__PURE__*/http_reader_regeneratorRuntime().mark(function _callee7(begin, length, purpose) { var range, response; return http_reader_regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: this.requestsEverMade += 1; this.bytesEverRequested += length; range = "bytes=".concat(begin, "-").concat(begin + length - 1); Logger.info("request: #".concat(this.requestsEverMade, ", purpose: ").concat(purpose, "), bytes: (this_request: ").concat(length, ", ever: ").concat(this.bytesEverRequested, "), Range: ").concat(range)); _context7.next = 6; return fetch(this.url, { headers: { Range: range } }); case 6: response = _context7.sent; return _context7.abrupt("return", response.arrayBuffer()); case 8: case "end": return _context7.stop(); } }, _callee7, this); })); function getRange(_x11, _x12, _x13) { return _getRange2.apply(this, arguments); } return getRange; }() }]); return HttpRangeClient; }(); ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/generic/header.js function header_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = header_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function header_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return header_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return header_arrayLikeToArray(o, minLen); } function header_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function featureGeomType(feature) { if (feature.getGeometry) { return toGeometryType(feature.getGeometry().getType()); } else { return toGeometryType(feature.geometry.type); } } function header_inferGeometryType(features) { var geometryType = undefined; var _iterator = header_createForOfIteratorHelper(features), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var f = _step.value; if (geometryType === GeometryType.Unknown) { break; } var gtype = featureGeomType(f); if (geometryType === undefined) { geometryType = gtype; } else if (geometryType !== gtype) { geometryType = GeometryType.Unknown; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (geometryType === undefined) { throw new Error('Could not infer geometry type for collection of features.'); } return geometryType; } ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/generic/featurecollection.js function featurecollection_typeof(obj) { "@babel/helpers - typeof"; return featurecollection_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, featurecollection_typeof(obj); } function featurecollection_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ featurecollection_regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == featurecollection_typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function featurecollection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function featurecollection_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { featurecollection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { featurecollection_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function featurecollection_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = featurecollection_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function featurecollection_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return featurecollection_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return featurecollection_arrayLikeToArray(o, minLen); } function featurecollection_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function featurecollection_asyncIterator(iterable) { var method, async, sync, retry = 2; for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { if (async && null != (method = iterable[async])) return method.call(iterable); if (sync && null != (method = iterable[sync])) return new featurecollection_AsyncFromSyncIterator(method.call(iterable)); async = "@@asyncIterator", sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); } function featurecollection_AsyncFromSyncIterator(s) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return featurecollection_AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { this.s = s, this.n = s.next; }, featurecollection_AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, "return": function _return(value) { var ret = this.s["return"]; return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, "throw": function _throw(value) { var thr = this.s["return"]; return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }, new featurecollection_AsyncFromSyncIterator(s); } function featurecollection_awaitAsyncGenerator(value) { return new featurecollection_OverloadYield(value, 0); } function featurecollection_wrapAsyncGenerator(fn) { return function () { return new featurecollection_AsyncGenerator(fn.apply(this, arguments)); }; } function featurecollection_AsyncGenerator(gen) { var front, back; function resume(key, arg) { try { var result = gen[key](arg), value = result.value, overloaded = value instanceof featurecollection_OverloadYield; Promise.resolve(overloaded ? value.v : value).then(function (arg) { if (overloaded) { var nextKey = "return" === key ? "return" : "next"; if (!value.k || arg.done) return resume(nextKey, arg); arg = gen[nextKey](arg).value; } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: !0 }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: !1 }); } (front = front.next) ? resume(front.key, front.arg) : back = null; } this._invoke = function (key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; back ? back = back.next = request : (front = back = request, resume(key, arg)); }); }, "function" != typeof gen["return"] && (this["return"] = void 0); } featurecollection_AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }, featurecollection_AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }, featurecollection_AsyncGenerator.prototype["throw"] = function (arg) { return this._invoke("throw", arg); }, featurecollection_AsyncGenerator.prototype["return"] = function (arg) { return this._invoke("return", arg); }; function featurecollection_OverloadYield(value, kind) { this.v = value, this.k = kind; } function serialize(features) { var headerMeta = introspectHeaderMeta(features); var header = featurecollection_buildHeader(headerMeta); var featureBuffers = features.map(function (f) { if (!f.getGeometry) throw new Error('Missing getGeometry implementation'); if (!f.getProperties) throw new Error('Missing getProperties implementation'); return buildFeature(parseGeometry(f.getGeometry(), headerMeta.geometryType), f.getProperties(), headerMeta); }); var featuresLength = featureBuffers.map(function (f) { return f.length; }).reduce(function (a, b) { return a + b; }); var uint8 = new Uint8Array(magicbytes.length + header.length + featuresLength); uint8.set(header, magicbytes.length); var offset = magicbytes.length + header.length; var _iterator2 = featurecollection_createForOfIteratorHelper(featureBuffers), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var feature = _step2.value; uint8.set(feature, offset); offset += feature.length; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } uint8.set(magicbytes); return uint8; } function deserialize(bytes, fromFeature, headerMetaFn) { if (!bytes.subarray(0, 3).every(function (v, i) { return constants_magicbytes[i] === v; })) throw new Error('Not a FlatGeobuf file'); var bb = new js_flatbuffers/* ByteBuffer */.cZ(bytes); var headerLength = bb.readUint32(constants_magicbytes.length); bb.setPosition(constants_magicbytes.length + SIZE_PREFIX_LEN); var headerMeta = fromByteBuffer(bb); if (headerMetaFn) headerMetaFn(headerMeta); var offset = constants_magicbytes.length + SIZE_PREFIX_LEN + headerLength; var indexNodeSize = headerMeta.indexNodeSize, featuresCount = headerMeta.featuresCount; if (indexNodeSize > 0) offset += calcTreeSize(featuresCount, indexNodeSize); var features = []; while (offset < bb.capacity()) { var featureLength = bb.readUint32(offset); bb.setPosition(offset + SIZE_PREFIX_LEN); var feature = feature_Feature.getRootAsFeature(bb); features.push(fromFeature(feature, headerMeta)); offset += SIZE_PREFIX_LEN + featureLength; } return features; } function deserializeStream(_x, _x2, _x3) { return _deserializeStream.apply(this, arguments); } function _deserializeStream() { _deserializeStream = featurecollection_wrapAsyncGenerator( /*#__PURE__*/featurecollection_regeneratorRuntime().mark(function _callee2(stream, fromFeature, headerMetaFn) { var reader, read, bytes, bb, headerLength, headerMeta, indexNodeSize, featuresCount, treeSize, feature; return featurecollection_regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: reader = slice_source(stream); read = /*#__PURE__*/function () { var _ref = featurecollection_asyncToGenerator( /*#__PURE__*/featurecollection_regeneratorRuntime().mark(function _callee(size) { return featurecollection_regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: _context.next = 2; return reader.slice(size); case 2: return _context.abrupt("return", _context.sent); case 3: case "end": return _context.stop(); } }, _callee); })); return function read(_x8) { return _ref.apply(this, arguments); }; }(); _context2.t0 = Uint8Array; _context2.next = 5; return featurecollection_awaitAsyncGenerator(read(8, 'magic bytes')); case 5: _context2.t1 = _context2.sent; bytes = new _context2.t0(_context2.t1); if (bytes.subarray(0, 3).every(function (v, i) { return constants_magicbytes[i] === v; })) { _context2.next = 9; break; } throw new Error('Not a FlatGeobuf file'); case 9: _context2.t2 = Uint8Array; _context2.next = 12; return featurecollection_awaitAsyncGenerator(read(4, 'header length')); case 12: _context2.t3 = _context2.sent; bytes = new _context2.t2(_context2.t3); bb = new js_flatbuffers/* ByteBuffer */.cZ(bytes); headerLength = bb.readUint32(0); _context2.t4 = Uint8Array; _context2.next = 19; return featurecollection_awaitAsyncGenerator(read(headerLength, 'header data')); case 19: _context2.t5 = _context2.sent; bytes = new _context2.t4(_context2.t5); bb = new js_flatbuffers/* ByteBuffer */.cZ(bytes); headerMeta = fromByteBuffer(bb); if (headerMetaFn) headerMetaFn(headerMeta); indexNodeSize = headerMeta.indexNodeSize, featuresCount = headerMeta.featuresCount; if (!(indexNodeSize > 0)) { _context2.next = 29; break; } treeSize = calcTreeSize(featuresCount, indexNodeSize); _context2.next = 29; return featurecollection_awaitAsyncGenerator(read(treeSize, 'entire index, w/o rect')); case 29: _context2.next = 31; return featurecollection_awaitAsyncGenerator(readFeature(read, headerMeta, fromFeature)); case 31: if (!(feature = _context2.sent)) { _context2.next = 36; break; } _context2.next = 34; return feature; case 34: _context2.next = 29; break; case 36: case "end": return _context2.stop(); } }, _callee2); })); return _deserializeStream.apply(this, arguments); } function deserializeFiltered(_x4, _x5, _x6, _x7) { return _deserializeFiltered.apply(this, arguments); } function _deserializeFiltered() { _deserializeFiltered = featurecollection_wrapAsyncGenerator( /*#__PURE__*/featurecollection_regeneratorRuntime().mark(function _callee3(url, rect, fromFeature, headerMetaFn) { var reader, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, feature; return featurecollection_regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return featurecollection_awaitAsyncGenerator(HttpReader.open(url)); case 2: reader = _context3.sent; Logger.debug('opened reader'); if (headerMetaFn) headerMetaFn(reader.header); _iteratorAbruptCompletion = false; _didIteratorError = false; _context3.prev = 7; _iterator = featurecollection_asyncIterator(reader.selectBbox(rect)); case 9: _context3.next = 11; return featurecollection_awaitAsyncGenerator(_iterator.next()); case 11: if (!(_iteratorAbruptCompletion = !(_step = _context3.sent).done)) { _context3.next = 18; break; } feature = _step.value; _context3.next = 15; return fromFeature(feature, reader.header); case 15: _iteratorAbruptCompletion = false; _context3.next = 9; break; case 18: _context3.next = 24; break; case 20: _context3.prev = 20; _context3.t0 = _context3["catch"](7); _didIteratorError = true; _iteratorError = _context3.t0; case 24: _context3.prev = 24; _context3.prev = 25; if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) { _context3.next = 29; break; } _context3.next = 29; return featurecollection_awaitAsyncGenerator(_iterator["return"]()); case 29: _context3.prev = 29; if (!_didIteratorError) { _context3.next = 32; break; } throw _iteratorError; case 32: return _context3.finish(29); case 33: return _context3.finish(24); case 34: case "end": return _context3.stop(); } }, _callee3, null, [[7, 20, 24, 34], [25,, 29, 33]]); })); return _deserializeFiltered.apply(this, arguments); } function readFeature(_x9, _x10, _x11) { return _readFeature.apply(this, arguments); } function _readFeature() { _readFeature = featurecollection_asyncToGenerator( /*#__PURE__*/featurecollection_regeneratorRuntime().mark(function _callee4(read, headerMeta, fromFeature) { var bytes, bb, featureLength, bytesAligned, feature; return featurecollection_regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: _context4.t0 = Uint8Array; _context4.next = 3; return read(4, 'feature length'); case 3: _context4.t1 = _context4.sent; bytes = new _context4.t0(_context4.t1); if (!(bytes.byteLength === 0)) { _context4.next = 7; break; } return _context4.abrupt("return"); case 7: bb = new js_flatbuffers/* ByteBuffer */.cZ(bytes); featureLength = bb.readUint32(0); _context4.t2 = Uint8Array; _context4.next = 12; return read(featureLength, 'feature data'); case 12: _context4.t3 = _context4.sent; bytes = new _context4.t2(_context4.t3); bytesAligned = new Uint8Array(featureLength + 4); bytesAligned.set(bytes, 4); bb = new js_flatbuffers/* ByteBuffer */.cZ(bytesAligned); bb.setPosition(SIZE_PREFIX_LEN); feature = feature_Feature.getRootAsFeature(bb); return _context4.abrupt("return", fromFeature(feature, headerMeta)); case 20: case "end": return _context4.stop(); } }, _callee4); })); return _readFeature.apply(this, arguments); } function buildColumn(builder, column) { var nameOffset = builder.createString(column.name); Column.startColumn(builder); Column.addName(builder, nameOffset); Column.addType(builder, column.type); return Column.endColumn(builder); } function featurecollection_buildHeader(header) { var builder = new flatbuffers.Builder(); var columnOffsets = null; if (header.columns) columnOffsets = Header.createColumnsVector(builder, header.columns.map(function (c) { return buildColumn(builder, c); })); var nameOffset = builder.createString('L1'); Header.startHeader(builder); Header.addFeaturesCount(builder, BigInt(header.featuresCount)); Header.addGeometryType(builder, header.geometryType); Header.addIndexNodeSize(builder, 0); if (columnOffsets) Header.addColumns(builder, columnOffsets); Header.addName(builder, nameOffset); var offset = Header.endHeader(builder); builder.finishSizePrefixed(offset); return builder.asUint8Array(); } function valueToType(value) { if (typeof value === 'boolean') return ColumnType.Bool;else if (typeof value === 'number') { if (value % 1 === 0) return ColumnType.Int;else return ColumnType.Double; } else if (typeof value === 'string') return ColumnType.String;else if (value === null) return ColumnType.String;else if (featurecollection_typeof(value) === 'object') return ColumnType.Json;else throw new Error("Unknown type (value '".concat(value, "')")); } function featurecollection_mapColumn(properties, k) { return { name: k, type: valueToType(properties[k]), title: null, description: null, width: -1, precision: -1, scale: -1, nullable: true, unique: false, primary_key: false }; } function introspectHeaderMeta(features) { var sampleFeature = features[0]; var properties = sampleFeature.getProperties ? sampleFeature.getProperties() : {}; var columns = null; if (properties) columns = Object.keys(properties).filter(function (key) { return key !== 'geometry'; }).map(function (k) { return featurecollection_mapColumn(properties, k); }); var geometryType = inferGeometryType(features); var headerMeta = { geometryType: geometryType, columns: columns, envelope: null, featuresCount: features.length, indexNodeSize: 0, crs: null, title: null, description: null, metadata: null }; return headerMeta; } ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/geojson/featurecollection.js function geojson_featurecollection_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = geojson_featurecollection_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function geojson_featurecollection_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return geojson_featurecollection_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return geojson_featurecollection_arrayLikeToArray(o, minLen); } function geojson_featurecollection_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function featurecollection_serialize(featurecollection) { var headerMeta = featurecollection_introspectHeaderMeta(featurecollection); var header = buildHeader(headerMeta); var features = featurecollection.features.map(function (f) { return buildFeature(f.geometry.type === 'GeometryCollection' ? parseGC(f.geometry) : parseGeometry(f.geometry), f.properties, headerMeta); }); var featuresLength = features.map(function (f) { return f.length; }).reduce(function (a, b) { return a + b; }); var uint8 = new Uint8Array(magicbytes.length + header.length + featuresLength); uint8.set(header, magicbytes.length); var offset = magicbytes.length + header.length; var _iterator = geojson_featurecollection_createForOfIteratorHelper(features), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var feature = _step.value; uint8.set(feature, offset); offset += feature.length; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } uint8.set(magicbytes); return uint8; } function featurecollection_deserialize(bytes, headerMetaFn) { var features = deserialize(bytes, feature_fromFeature, headerMetaFn); return { type: 'FeatureCollection', features: features }; } function featurecollection_deserializeStream(stream, headerMetaFn) { return deserializeStream(stream, feature_fromFeature, headerMetaFn); } function featurecollection_deserializeFiltered(url, rect, headerMetaFn) { return deserializeFiltered(url, rect, feature_fromFeature, headerMetaFn); } function featurecollection_introspectHeaderMeta(featurecollection) { var feature = featurecollection.features[0]; var properties = feature.properties; var columns = null; if (properties) columns = Object.keys(properties).map(function (k) { return mapColumn(properties, k); }); var geometryType = inferGeometryType(featurecollection.features); var headerMeta = { geometryType: geometryType, columns: columns, envelope: null, featuresCount: featurecollection.features.length, indexNodeSize: 0, crs: null, title: null, description: null, metadata: null }; return headerMeta; } ;// CONCATENATED MODULE: ./node_modules/flatgeobuf/lib/mjs/geojson.js function geojson_serialize(geojson) { var bytes = fcSerialize(geojson); return bytes; } function geojson_deserialize(input, rect, headerMetaFn) { if (input instanceof Uint8Array) return featurecollection_deserialize(input, headerMetaFn);else if (input instanceof ReadableStream) return featurecollection_deserializeStream(input, headerMetaFn);else return featurecollection_deserializeFiltered(input, rect, headerMetaFn); } ;// CONCATENATED MODULE: external "ol.loadingstrategy" const external_ol_loadingstrategy_namespaceObject = ol.loadingstrategy; ;// CONCATENATED MODULE: ./src/openlayers/overlay/FGB.js function FGB_typeof(obj) { "@babel/helpers - typeof"; return FGB_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, FGB_typeof(obj); } function FGB_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ FGB_regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == FGB_typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function FGB_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function FGB_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { FGB_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { FGB_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function FGB_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function FGB_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function FGB_createClass(Constructor, protoProps, staticProps) { if (protoProps) FGB_defineProperties(Constructor.prototype, protoProps); if (staticProps) FGB_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (FGB_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function FGB_asyncIterator(iterable) { var method, async, sync, retry = 2; for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { if (async && null != (method = iterable[async])) return method.call(iterable); if (sync && null != (method = iterable[sync])) return new FGB_AsyncFromSyncIterator(method.call(iterable)); async = "@@asyncIterator", sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); } function FGB_AsyncFromSyncIterator(s) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return FGB_AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { this.s = s, this.n = s.next; }, FGB_AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, "return": function _return(value) { var ret = this.s["return"]; return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, "throw": function _throw(value) { var thr = this.s["return"]; return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }, new FGB_AsyncFromSyncIterator(s); } /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FGB * @browsernamespace ol.source * @category Visualization FGB * @classdesc FGB 图层源。 * @version 11.1.0 * @param {Object} opt_options - 参数。 * @param {string} opt_options.url - FGB 服务地址,例如:http://localhost:8090/iserver/services/xxx/rest/data/featureResults/newResourceId.fgb。 * @param {GeoJSONObject} [opt_options.strategy='bbox'] - 指定加载策略,可选值为 ol.loadingstrategy.all,ol/loadingstrategy.bbox。all为全部加载, bbox为当前可见范围加载 * @param {Array} [opt_options.extent] - 加载范围, 参数规范为: [minX, minY, maxX, maxY], 传递此参数后, 图层将使用局部加载。 * @param {Function} [opt_options.featureLoader] - 要素加载回调函数 * @param {boolean} [opt_options.overlaps] - 是否优化重叠要素的填充与描边操作 * @param {boolean} [opt_options.useSpatialIndex] - 是否启用要素空间索引 * @param {boolean} [opt_options.wrapX] - 是否平铺地图 * @extends {ol.source.Vector} * @usage */ var FGB = /*#__PURE__*/function (_VectorSource) { _inherits(FGB, _VectorSource); var _super = _createSuper(FGB); function FGB(options) { var _this; FGB_classCallCheck(this, FGB); var baseOptions = Object.assign({ strategy: external_ol_loadingstrategy_namespaceObject.bbox }, options); delete baseOptions.url; delete baseOptions.extent; _this = _super.call(this, baseOptions); _this.options = options || {}; _this.strategy = baseOptions.strategy; _this.url = _this.options.url; _this.extent = _this.options.extent; _this.setLoader( /*#__PURE__*/function () { var _ref = FGB_asyncToGenerator( /*#__PURE__*/FGB_regeneratorRuntime().mark(function _callee(extent) { var intersectExtent, fgbStream; return FGB_regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (this.extent && this.strategy === external_ol_loadingstrategy_namespaceObject.bbox) { intersectExtent = getIntersection(this.extent, extent); extent = intersectExtent && intersectExtent.length ? intersectExtent : this.extent; } if (!this.extent && (this.strategy === external_ol_loadingstrategy_namespaceObject.all || !isFinite(extent[0]))) { extent = []; } if (Object.keys(extent).length) { _context.next = 6; break; } _context.next = 5; return this._getStream(this.url); case 5: fgbStream = _context.sent; case 6: this._handleFeatures(fgbStream && fgbStream.body || this.url, extent); case 7: case "end": return _context.stop(); } }, _callee, this); })); return function (_x) { return _ref.apply(this, arguments); }; }()); return _this; } FGB_createClass(FGB, [{ key: "_handleFeatures", value: function () { var _handleFeatures2 = FGB_asyncToGenerator( /*#__PURE__*/FGB_regeneratorRuntime().mark(function _callee2(url, extent) { var rect, fgb, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, feature; return FGB_regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: rect = {}; if (extent && extent.length) { rect = { minX: extent[0], minY: extent[1], maxX: extent[2], maxY: extent[3] }; } fgb = geojson_deserialize(url, rect); _iteratorAbruptCompletion = false; _didIteratorError = false; _context2.prev = 5; _iterator = FGB_asyncIterator(fgb); case 7: _context2.next = 9; return _iterator.next(); case 9: if (!(_iteratorAbruptCompletion = !(_step = _context2.sent).done)) { _context2.next = 17; break; } feature = _step.value; feature = new (external_ol_format_GeoJSON_default())().readFeature(feature); if (this.options.featureLoader && typeof this.options.featureLoader === 'function') { feature = this.options.featureLoader(feature); } this.addFeature(feature); case 14: _iteratorAbruptCompletion = false; _context2.next = 7; break; case 17: _context2.next = 23; break; case 19: _context2.prev = 19; _context2.t0 = _context2["catch"](5); _didIteratorError = true; _iteratorError = _context2.t0; case 23: _context2.prev = 23; _context2.prev = 24; if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) { _context2.next = 28; break; } _context2.next = 28; return _iterator["return"](); case 28: _context2.prev = 28; if (!_didIteratorError) { _context2.next = 31; break; } throw _iteratorError; case 31: return _context2.finish(28); case 32: return _context2.finish(23); case 33: case "end": return _context2.stop(); } }, _callee2, this, [[5, 19, 23, 33], [24,, 28, 32]]); })); function _handleFeatures(_x2, _x3) { return _handleFeatures2.apply(this, arguments); } return _handleFeatures; }() }, { key: "_getStream", value: function () { var _getStream2 = FGB_asyncToGenerator( /*#__PURE__*/FGB_regeneratorRuntime().mark(function _callee3(url) { return FGB_regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return FetchRequest.get(url, {}, { withoutFormatSuffix: true }).then(function (response) { return response; }); case 2: return _context3.abrupt("return", _context3.sent); case 3: case "end": return _context3.stop(); } }, _callee3); })); function _getStream(_x4) { return _getStream2.apply(this, arguments); } return _getStream; }() }]); return FGB; }((external_ol_source_Vector_default())); ;// CONCATENATED MODULE: ./src/openlayers/overlay/graphic/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/openlayers/overlay/mapv/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/openlayers/overlay/theme/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: external "ol.geom.LineString" const external_ol_geom_LineString_namespaceObject = ol.geom.LineString; var external_ol_geom_LineString_default = /*#__PURE__*/__webpack_require__.n(external_ol_geom_LineString_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/overlay/vectortile/olExtends.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ var olExtends = function(targetMap) { //解决olms.js插件,在使用ol.js时沿线标注不显示的问题,因为ol.geom.LineString.getFlatMidpoint未非公开方法 if (!(external_ol_geom_LineString_default()).prototype.getFlatMidpoint) { (external_ol_geom_LineString_default()).prototype.getFlatMidpoint = function() { return this.getCoordinateAt(0.5); }; } if (core_Util_Util.getOlVersion() === '4' && window && window.ol && window.ol.geom.flat) { // for ol4-debug window.targetMapCache = targetMap; let ol = window.ol; //解决 new ol.format.MVT({featureClass: ol.Feature})时,非3857显示异常的问题。ol即将发布的5.0版本已解决。 // eslint-disable-next-line no-unused-vars ol.format.MVT.prototype.readProjection = function(source) { return new ol.proj.Projection({ code: '', units: ol.proj.Units.TILE_PIXELS }); }; //解决 new ol.format.MVT({featureClass: ol.Feature})时,非3857显示异常的问题。ol即将发布的5.0版本已解决。 // eslint-disable-next-line no-unused-vars ol.format.MVT.prototype.readProjection = function(source) { return new ol.proj.Projection({ code: '', units: ol.proj.Units.TILE_PIXELS }); }; //解决面填充时不能整版填充的问题。ol即将发布的5.0版本已解决。 // eslint-disable-next-line no-unused-vars ol.render.canvas.Replay.prototype.applyFill = function(state, geometry) { var fillStyle = state.fillStyle; var fillInstruction = [ol.render.canvas.Instruction.SET_FILL_STYLE, fillStyle]; if (typeof fillStyle !== 'string') { var viewExtent = window.targetMapCache .getView() .getProjection() .getExtent(); fillInstruction.push([viewExtent[0], viewExtent[3]]); } this.instructions.push(fillInstruction); }; //解决面填充时不能整版填充的问题。ol即将发布的5.0版本已解决。 // eslint-disable-next-line no-unused-vars ol.render.canvas.Replay.prototype.applyFill = function(state, geometry) { var fillStyle = state.fillStyle; var fillInstruction = [ol.render.canvas.Instruction.SET_FILL_STYLE, fillStyle]; if (typeof fillStyle !== 'string') { var viewExtent = window.targetMapCache .getView() .getProjection() .getExtent(); fillInstruction.push([viewExtent[0], viewExtent[3]]); } this.instructions.push(fillInstruction); }; //解决在多面时,第一个面是逆时针时无法显示的问题。该问题由组件修复。 ol.format.MVT.prototype.createFeature_ = function(pbf, rawFeature, opt_options) { var type = rawFeature.type; if (type === 0) { return null; } var feature; var id = rawFeature.id; var values = rawFeature.properties; values[this.layerName_] = rawFeature.layer.name; var flatCoordinates = []; var ends = []; ol.format.MVT.readRawGeometry_(pbf, rawFeature, flatCoordinates, ends); var geometryType = ol.format.MVT.getGeometryType_(type, ends.length); if (this.featureClass_ === ol.render.Feature) { feature = new this.featureClass_(geometryType, flatCoordinates, ends, values, id); } else { var geom; if (geometryType == ol.geom.GeometryType.POLYGON) { var endss = []; var offset = 0; var prevEndIndex = 0; for (var i = 0, ii = ends.length; i < ii; ++i) { var end = ends[i]; if (!ol.geom.flat.orient.linearRingIsClockwise(flatCoordinates, offset, end, 2)) { endss.push(ends.slice(prevEndIndex, i + 1)); prevEndIndex = i + 1; } offset = end; } if (endss.length > 1) { ends = endss; geom = new ol.geom.MultiPolygon(null); } else { geom = new ol.geom.Polygon(null); } } else { geom = geometryType === ol.geom.GeometryType.POINT ? new ol.geom.Point(null) : geometryType === ol.geom.GeometryType.LINE_STRING ? new ol.geom.LineString(null) : geometryType === ol.geom.GeometryType.POLYGON ? new ol.geom.Polygon(null) : geometryType === ol.geom.GeometryType.MULTI_POINT ? new ol.geom.MultiPoint(null) : geometryType === ol.geom.GeometryType.MULTI_LINE_STRING ? new ol.geom.MultiLineString(null) : null; } if (geom) { geom.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates, ends); feature = new this.featureClass_(); if (this.geometryName_) { feature.setGeometryName(this.geometryName_); } var geometry = ol.format.Feature.transformWithOptions(geom, false, this.adaptOptions(opt_options)); feature.setGeometry(geometry); feature.setId(id); feature.setProperties(values); } } return feature; }; //解决中文沿线表述显示不符合中文阅读习惯的问题 ol.geom.flat.textpath.lineString = function( flatCoordinates, offset, end, stride, text, measure, startM, maxAngle ) { var result = []; // Keep text upright var anglereverse = Math.atan2( flatCoordinates[end - stride + 1] - flatCoordinates[offset + 1], flatCoordinates[end - stride] - flatCoordinates[offset] ); var reverse = anglereverse < -0.785 || anglereverse > 2.356; //0.785//2.356 var isRotateUp = (anglereverse < -0.785 && anglereverse > -2.356) || (anglereverse > 0.785 && anglereverse < 2.356); var numChars = text.length; var x1 = flatCoordinates[offset]; var y1 = flatCoordinates[offset + 1]; offset += stride; var x2 = flatCoordinates[offset]; var y2 = flatCoordinates[offset + 1]; var segmentM = 0; var segmentLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); while (offset < end - stride && segmentM + segmentLength < startM) { x1 = x2; y1 = y2; offset += stride; x2 = flatCoordinates[offset]; y2 = flatCoordinates[offset + 1]; segmentM += segmentLength; segmentLength = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); } var interpolate = (startM - segmentM) / segmentLength; var x0 = ol.math.lerp(x1, x2, interpolate); //起始点 var y0 = ol.math.lerp(y1, y2, interpolate); //起始点 var chunk = ''; var chunkLength = 0; var data, index, previousAngle, previousLang; for (var i = 0; i < numChars; ++i) { index = reverse ? numChars - i - 1 : i; var char = text.charAt(index); var charcode = char.charCodeAt(0); var ischinese = charcode >= 19968 && charcode <= 40907; chunk = reverse ? char + chunk : chunk + char; var charLength = measure(chunk) - chunkLength; chunkLength += charLength; //var charM = startM + charLength / 2; while ( offset < end - stride && Math.sqrt(Math.pow(x2 - x0, 2) + Math.pow(y2 - y0, 2)) < charLength / 2 ) { x1 = x2; y1 = y2; offset += stride; x2 = flatCoordinates[offset]; y2 = flatCoordinates[offset + 1]; } var a = Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2); var b = 2 * (x2 - x1) * (x1 - x0) + 2 * (y2 - y1) * (y1 - y0); var c = Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2) - Math.pow(charLength / 2, 2); var scale1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); var scale2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); interpolate = scale1 < 0 || scale1 > 1 ? scale2 : scale2 < 0 || scale2 > 1 ? scale1 : scale1 < scale2 ? scale2 : scale1; var x = ol.math.lerp(x1, x2, interpolate); var y = ol.math.lerp(y1, y2, interpolate); while (offset < end - stride && Math.sqrt(Math.pow(x2 - x, 2) + Math.pow(y2 - y, 2)) < charLength / 2) { x1 = x2; y1 = y2; offset += stride; x2 = flatCoordinates[offset]; y2 = flatCoordinates[offset + 1]; } a = Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2); b = 2 * (x2 - x1) * (x1 - x) + 2 * (y2 - y1) * (y1 - y); c = Math.pow(x1 - x, 2) + Math.pow(y1 - y, 2) - Math.pow(charLength / 2, 2); scale1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); scale2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); interpolate = scale1 < 0 || scale1 > 1 ? scale2 : scale2 < 0 || scale2 > 1 ? scale1 : scale1 < scale2 ? scale2 : scale1; var x3 = ol.math.lerp(x1, x2, interpolate); var y3 = ol.math.lerp(y1, y2, interpolate); var angle = Math.atan2(y3 - y0, x3 - x0); if (reverse) { angle += angle > 0 ? -Math.PI : Math.PI; } if (ischinese && isRotateUp) { angle += angle > 0 ? -Math.PI / 2 : Math.PI / 2; } if (previousAngle !== undefined) { var delta = angle - previousAngle; delta += delta > Math.PI ? -2 * Math.PI : delta < -Math.PI ? 2 * Math.PI : 0; if ( ischinese === previousLang ? Math.abs(delta) > maxAngle : Math.abs(delta) > maxAngle + Math.PI / 2 ) { return null; } } if (previousAngle == angle && !isRotateUp) { if (reverse) { data[0] = x; data[1] = y; data[2] = charLength / 2; } data[4] = chunk; } else { chunk = char; chunkLength = charLength; data = [x, y, charLength / 2, angle, chunk]; if (reverse) { result.unshift(data); } else { result.push(data); } previousAngle = angle; previousLang = ischinese; } x0 = x3; y0 = y3; startM += charLength; } return result; }; //以下两个方法解决在大数据量图斑时,内存疯长的问题。该改法引发新问题:无法点选要素 ol.layer.VectorTile.prototype.setFastRender = function(fastRender) { return (this.fastRender = fastRender); }; ol.renderer.canvas.VectorTileLayer.prototype.postCompose = function(context, frameState, layerState) { var layer = this.getLayer(); var declutterReplays = layer.getDeclutter() ? {} : null; var source = /** @type {ol.source.VectorTile} */ (layer.getSource()); var renderMode = layer.getRenderMode(); var replayTypes = ol.renderer.canvas.VectorTileLayer.VECTOR_REPLAYS[renderMode]; var pixelRatio = frameState.pixelRatio; var rotation = frameState.viewState.rotation; var size = frameState.size; var offsetX, offsetY; if (rotation) { offsetX = Math.round((pixelRatio * size[0]) / 2); offsetY = Math.round((pixelRatio * size[1]) / 2); ol.render.canvas.rotateAtOffset(context, -rotation, offsetX, offsetY); } if (declutterReplays) { this.declutterTree_.clear(); } var tiles = this.renderedTiles; var tileGrid = source.getTileGridForProjection(frameState.viewState.projection); var clips = []; var zs = []; for (var i = tiles.length - 1; i >= 0; --i) { var tile = /** @type {ol.VectorImageTile} */ (tiles[i]); if (tile.getState() == ol.TileState.ABORT) { continue; } var tileCoord = tile.tileCoord; var worldOffset = tileGrid.getTileCoordExtent(tileCoord)[0] - tileGrid.getTileCoordExtent(tile.wrappedTileCoord)[0]; var transform = undefined; for (var t = 0, tt = tile.tileKeys.length; t < tt; ++t) { var sourceTile = tile.getTile(tile.tileKeys[t]); if (sourceTile.getState() == ol.TileState.ERROR) { continue; } var replayGroup = sourceTile.getReplayGroup(layer, tileCoord.toString()); if ( renderMode != ol.layer.VectorTileRenderType.VECTOR && (!replayGroup || !replayGroup.hasReplays(replayTypes)) ) { if (layer.fastRender === true) { sourceTile.replayGroups_ = {}; sourceTile.features_ = []; } continue; } if (!transform) { transform = this.getTransform(frameState, worldOffset); } var currentZ = sourceTile.tileCoord[0]; var currentClip = replayGroup.getClipCoords(transform); context.save(); context.globalAlpha = layerState.opacity; // Create a clip mask for regions in this low resolution tile that are // already filled by a higher resolution tile for (var j = 0, jj = clips.length; j < jj; ++j) { var clip = clips[j]; if (currentZ < zs[j]) { context.beginPath(); // counter-clockwise (outer ring) for current tile context.moveTo(currentClip[0], currentClip[1]); context.lineTo(currentClip[2], currentClip[3]); context.lineTo(currentClip[4], currentClip[5]); context.lineTo(currentClip[6], currentClip[7]); // clockwise (inner ring) for higher resolution tile context.moveTo(clip[6], clip[7]); context.lineTo(clip[4], clip[5]); context.lineTo(clip[2], clip[3]); context.lineTo(clip[0], clip[1]); context.clip(); } } replayGroup.replay(context, transform, rotation, {}, replayTypes, declutterReplays); context.restore(); clips.push(currentClip); zs.push(currentZ); } } if (declutterReplays) { ol.render.canvas.ReplayGroup.replayDeclutter(declutterReplays, context, rotation); } if (rotation) { ol.render.canvas.rotateAtOffset( context, rotation, /** @type {number} */ (offsetX), /** @type {number} */ (offsetY) ); } ol.renderer.canvas.TileLayer.prototype.postCompose.apply(this, arguments); }; } }; window.olExtends = olExtends; // EXTERNAL MODULE: ./node_modules/lodash.remove/index.js var lodash_remove = __webpack_require__(794); var lodash_remove_default = /*#__PURE__*/__webpack_require__.n(lodash_remove); ;// CONCATENATED MODULE: ./src/openlayers/overlay/vectortile/MapboxStyles.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MapboxStyles * @classdesc Mapbox 矢量瓦片风格。 *
*

Notice

*

该功能依赖 ol-mapbox-style 插件,请确认引入该插件。

* `` *
* @category Visualization VectorTile * @param {Object} options - 参数。 * @param {(string|undefined)} [options.url] - SuperMap iServer 地图服务地址,例如'http://localhost:8090/iserver/services/map-mvt-test/rest/maps/test',与options.style互斥,优先级低于options.style。 * @param {(Object|string|undefined)} [options.style] - Mapbox Style JSON 对象或获取 Mapbox Style JSON 对象的 URL。与 options.url 互斥,优先级高于 options.url。 * @param {Array.} [options.resolutions] - 地图分辨率数组,用于映射 zoom 值。通常情況与地图的 {@link ol.View} 的分辨率一致。
* 默认值为:[78271.51696402048,39135.75848201024, 19567.87924100512,9783.93962050256,4891.96981025128,2445.98490512564, 1222.99245256282,611.49622628141,305.748113140705,152.8740565703525, 76.43702828517625,38.21851414258813,19.109257071294063,9.554628535647032, 4.777314267823516,2.388657133911758,1.194328566955879,0.5971642834779395, 0.29858214173896974,0.14929107086948487,0.07464553543474244]。 * @param {(string|Array.|undefined)} [options.source] - Mapbox Style 'source'的 key 值或者 'layer' 的 ID 数组。 * 当配置 'source' 的 key 值时,source 为该值的 layer 会被加载; * 当配置为 'layer' 的 ID 数组时,指定的 layer 会被加载,注意被指定的 layer 需要有相同的 source。 * 当不配置时,默认为 Mapbox Style JSON 的 `sources` 对象中的第一个。 * @param {ol.Map} [options.map] - Openlayers 地图对象,仅用于面填充样式,若没有面填充样式可不填。 * @param {ol.StyleFunction} [options.selectedStyle] -选中样式Function。 * @param {boolean} [options.withCredentials] - 请求是否携带 cookie。 * @example * var mbStyle = new MapboxStyles({ url: url, source: 'California', resolutions: [78271.51696402048,39135.75848201024, 19567.87924100512,9783.93962050256,4891.96981025128,2445.98490512564] }) mbStyle.on('styleLoaded', function () { var vectorLayer = new ol.layer.VectorTile({ //设置避让参数 declutter: true, source: new ol.source.VectorTileSuperMapRest({ url: url, format: new ol.format.MVT({ featureClass: ol.Feature }), tileType: 'ScaleXY' }), style: mbStyle.featureStyleFuntion }); map.addLayer(vectorLayer); }) * @usage */ class MapboxStyles extends (external_ol_Observable_default()) { constructor(options) { super(); options = options || {}; this.spriteRegEx = /^(.*)(\?.*)$/; this.defaultFont = ['DIN Offc Pro Medium', 'Arial Unicode MS Regular']; this.map = options.map; this.source = options.source; this.styleTarget = options.style || Util.urlAppend( Util.urlPathAppend(options.url, 'tileFeature/vectorstyles'), 'type=MapBox_GL&styleonly=true' ); this.resolutions = options.resolutions; this.withCredentials = options.withCredentials; this.selectedObjects = []; this.selectedStyle = options.selectedStyle || function() { return new (external_ol_style_Style_default())({ fill: new (external_ol_style_Fill_default())({ color: 'rgba(255, 0, 0, 1)' }), stroke: new (external_ol_style_Stroke_default())({ color: 'rgba(255, 0, 0, 1)', width: 10 }), text: new (external_ol_style_Text_default())({ font: 'normal 400 11.19px "Microsoft YaHei"', placement: 'point', fill: new (external_ol_style_Fill_default())({ color: 'blue' }) }), image: new (external_ol_style_Circle_default())({ radius: 5, fill: new (external_ol_style_Fill_default())({ color: 'blue' }) }) }); }; this.layersBySourceLayer = {}; olExtends(this.map); this._loadStyle(this.styleTarget); } /** * @function MapboxStyles.prototype.getStyleFunction * @description 获取 ol.StyleFunction。 * @returns {ol.StyleFunction} 返回 ol.StyleFunction */ getStyleFunction() { return this.featureStyleFuntion; } /** * @function MapboxStyles.prototype.getStylesBySourceLayer * @description 根据图层名称获取样式。 * @param {string} sourceLayer - 数据图层名称。 */ getStylesBySourceLayer(sourceLayer) { if (this.layersBySourceLayer[sourceLayer]) { return this.layersBySourceLayer[sourceLayer]; } const layers = []; for (let index = 0; index < this._mbStyle.layers.length; index++) { const layer = this._mbStyle.layers[index]; if (layer['source-layer'] !== sourceLayer) { continue; } layers.push(layer); } this.layersBySourceLayer[sourceLayer] = layers; return layers; } /** * @function MapboxStyles.prototype.setSelectedId * @description 设置选中要素,该要素将会用 `selectedStyle` 样式绘制。调用该方法后需要调用 {@link ol.layer.VectorTile} 的 `changed`,才能生效。 * @param {number} selectedId - 要素ID。 * @param {string} sourceLayer - 要素所在图层名称。 */ setSelectedId(selectedId, sourceLayer) { this.selectedObjects = []; this.selectedObjects.push({ id: selectedId, sourceLayer: sourceLayer }); } /** * @typedef {Object} MapboxStyles.selectedObject * @description 要选择的要素对象。 * @property {number} selectedId - 要素ID。 * @property {string} sourceLayer - 要素所在图层名称。 */ /** * @function MapboxStyles.prototype.setSelectedObjects * @version 10.0.0 * @description 设置选中要素或要素数组,该要素将会用 `selectedStyle` 样式绘制。调用该方法后需要调用 {@link ol.layer.VectorTile} 的 `changed`,才能生效。 * @param {MapboxStyles.selectedObject|Array.} addSelectedObjects - 选择的要素或要素数组。 */ setSelectedObjects(selectedObjects) { if (!Array.isArray(selectedObjects)) { selectedObjects = [selectedObjects]; } this.selectedObjects = []; this.selectedObjects = selectedObjects; } /** * @function MapboxStyles.prototype.addSelectedObjects * @version 10.0.0 * @description 增加选中的要素或要素数组,该要素将会用 `selectedStyle` 样式绘制。调用该方法后需要调用 {@link ol.layer.VectorTile} 的 `changed` 才能生效。 * @param {MapboxStyles.selectedObject|Array.} addSelectedObjects - 选择的要素或要素数组。 */ addSelectedObjects(selectedObjects) { if (!Array.isArray(selectedObjects)) { selectedObjects = [selectedObjects]; } this.selectedObjects.push(...selectedObjects); } /** * @function MapboxStyles.prototype.removeSelectedObjects * @version 10.0.0 * @description 清空选中状态。调用该方法后需要调用 {@link ol.layer.VectorTile} 的 `changed` 才能生效。 */ removeSelectedObjects(selectedObjects) { if (!Array.isArray(selectedObjects)) { selectedObjects = [selectedObjects]; } selectedObjects.forEach(element => { lodash_remove_default()(this.selectedObjects, obj => { return element.id === obj.id && element.sourceLayer === obj.sourceLayer; }); }); } /** * @function MapboxStyles.prototype.clearSelectedObjects * @version 10.0.0 * @description 清空选中状态。调用该方法后需要调用 {@link ol.layer.VectorTile} 的 `changed`,才能生效。 */ clearSelectedObjects() { this.selectedObjects = []; } /** * @function MapboxStyles.prototype.updateStyles * @description 更新图层样式。 * @param {Object} layerStyles - 图层样式或图层样式数组。 */ updateStyles(layerStyles) { if (Object.prototype.toString.call(layerStyles) !== '[object Array]') { layerStyles = [layerStyles]; } const layerObj = {}; layerStyles.forEach(layerStyle => { layerObj[layerStyle.id] = layerStyle; }); let count = 0; for (const key in this._mbStyle.layers) { const oldLayerStyle = this._mbStyle.layers[key]; if (count >= layerStyles.length) { break; } if (!layerObj[oldLayerStyle.id]) { continue; } const newLayerStyle = JSON.parse(JSON.stringify(layerObj[oldLayerStyle.id])); if (newLayerStyle.paint) { newLayerStyle.paint = Object.assign({}, oldLayerStyle.paint, newLayerStyle.paint); } if (newLayerStyle.layout) { newLayerStyle.layout = Object.assign({}, oldLayerStyle.layout, newLayerStyle.layout); } Object.assign(oldLayerStyle, newLayerStyle); count++; } this._createStyleFunction(); } /** * @function MapboxStyles.prototype.setStyle * @version 9.1.1 * @description 设置 Mapbox style 对象。 * @param {Object} style - Mapbox style 对象。 */ setStyle(style) { this.layersBySourceLayer = {}; this._loadStyle(style); } _loadStyle(style) { if (Object.prototype.toString.call(style) == '[object Object]') { this._mbStyle = style; this._resolve(); } else { var url = SecurityManager.appendCredential(style); FetchRequest.get(url, null, { withCredentials: this.withCredentials }) .then(response => response.json()) .then(mbStyle => { this._mbStyle = mbStyle; this._resolve(); }); } } _resolve() { if (!this.source) { this.source = Object.keys(this._mbStyle.sources)[0]; } if (this._mbStyle.sprite) { const spriteScale = window.devicePixelRatio >= 1.5 ? 0.5 : 1; const sizeFactor = spriteScale == 0.5 ? '@2x' : ''; //兼容一下iServer 等iServer修改 this._mbStyle.sprite = this._mbStyle.sprite.replace('@2x', ''); const spriteUrl = this._toSpriteUrl(this._mbStyle.sprite, this.path, sizeFactor + '.json'); FetchRequest.get(SecurityManager.appendCredential(spriteUrl), null, { withCredentials: this.withCredentials }) .then(response => response.json()) .then(spritesJson => { this._spriteData = spritesJson; this._spriteImageUrl = SecurityManager.appendCredential( this._toSpriteUrl(this._mbStyle.sprite, this.path, sizeFactor + '.png') ); this._spriteImage = null; const img = new Image(); img.crossOrigin = this.withCredentials ? 'use-credentials' : 'anonymous'; img.onload = () => { this._spriteImage = img; this._initStyleFunction(); }; img.onerror = () => { this._spriteImage = null; this._initStyleFunction(); }; img.src = this._spriteImageUrl; }); } else { this._initStyleFunction(); } } _initStyleFunction() { if (!this.resolutions && this._mbStyle.metadata && this._mbStyle.metadata.indexbounds) { const indexbounds = this._mbStyle.metadata.indexbounds; var max = Math.max(indexbounds[2] - indexbounds[0], indexbounds[3] - indexbounds[1]); const defaultResolutions = []; for (let index = 0; index < 30; index++) { defaultResolutions.push(max / 512 / Math.pow(2, index)); } this.resolutions = defaultResolutions; } this._createStyleFunction(); /** * @event MapboxStyles#styleloaded * @description 样式加载成功后触发。 */ this.dispatchEvent('styleloaded'); } _createStyleFunction() { if (this.map) { window.olms.applyBackground(this.map, this._mbStyle); } this.featureStyleFuntion = this._getStyleFunction(); } _getStyleFunction() { this.fun = window.olms.stylefunction( { setStyle: function() {}, set: function() {}, changed: function() {} }, this._mbStyle, this.source, this.resolutions, this._spriteData, '', this._spriteImage ); return (feature, resolution) => { const style = this.fun(feature, resolution); if ( this.selectedObjects.length > 0 && this.selectedObjects.find(element => { return element.id === feature.getId() && element.sourceLayer === feature.get('layer'); }) ) { const styleIndex = style && style[0] ? style[0].getZIndex() : 99999; let selectStyles = this.selectedStyle(feature, resolution); if (!Array.isArray(selectStyles)) { selectStyles = [selectStyles]; } for (let index = 0; index < selectStyles.length; index++) { const selectStyle = selectStyles[index]; if (feature.getGeometry().getType() === 'Point' && style[0].getText() && selectStyle.getText()) { selectStyle.setFill(null); selectStyle.setStroke(null); selectStyle.setImage(); selectStyle.getText().setText(style[0].getText().getText()); } selectStyle.setZIndex(styleIndex); } return selectStyles; } return style; }; } _withPath(url, path) { if (path && url.indexOf('http') != 0) { url = path + url; } return url; } _toSpriteUrl(url, path, extension) { url = this._withPath(url, path); const parts = url.match(this.spriteRegEx); return parts ? parts[1] + extension + (parts.length > 2 ? parts[2] : '') : url + extension; } } ;// CONCATENATED MODULE: ./src/openlayers/overlay/vectortile/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/openlayers/overlay/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/openlayers/services/AddressMatchService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class AddressMatchService * @category iServer AddressMatch * @classdesc 地址匹配服务。 * @example * new AddressMatchService(url,options) * .code(function(result){ * //doSomething * }) * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {ServiceBase} * @usage */ class AddressMatchService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function AddressMatchService.prototype.code * @description 获取正向地址匹配结果。 * @param {GeoCodingParameter} params - 正向匹配参数。 * @param {RequestCallback} callback 回调函数。 */ code(params, callback) { var me = this; var addressMatchService = new AddressMatchService_AddressMatchService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); addressMatchService.code(Util.urlPathAppend(me.url, 'geocoding'), params); } /** * @function AddressMatchService.prototype.decode * @description 获取反向地址匹配结果。 * @param {GeoDecodingParameter} params - 反向匹配参数。 * @param {RequestCallback} callback 回调函数。 */ decode(params, callback) { var me = this; var addressMatchService = new AddressMatchService_AddressMatchService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); addressMatchService.decode(Util.urlPathAppend(me.url, 'geodecoding'), params); } } ;// CONCATENATED MODULE: ./src/openlayers/services/ChartService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ChartService * @category iServer Map Chart * @classdesc 海图服务。 * @extends {ServiceBase} * @example * new ChartService(url).queryChart(param,function(result){ * //doSomething * }) * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ChartService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function ChartService.prototype.queryChart * @description 查询海图服务。 * @param {ChartQueryParameters} params - 海图查询所需参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} resultFormat - 返回结果类型。 */ queryChart(params, callback, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var chartQueryService = new ChartQueryService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); chartQueryService.processAsync(param); } /** * @function ChartService.prototype.getChartFeatureInfo * @description 获取海图物标信息服务。 * @param {RequestCallback} callback 回调函数。 */ getChartFeatureInfo(callback) { var me = this; var url = Util.urlPathAppend(me.url, 'chartFeatureInfoSpecs'); var chartFeatureInfoSpecsService = new ChartFeatureInfoSpecsService(url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); chartFeatureInfoSpecsService.processAsync(); } _processParams(params) { if (!params) { return {}; } params.returnContent = (params.returnContent == null) ? true : params.returnContent; if (params.filter) { params.chartQueryFilterParameters = core_Util_Util.isArray(params.filter) ? params.filter : [params.filter]; } if (params.bounds) { params.bounds = new Bounds( params.bounds[0], params.bounds[1], params.bounds[2], params.bounds[3] ); } } _processFormat(resultFormat) { return (resultFormat) ? resultFormat : DataFormat.GEOJSON; } } ;// CONCATENATED MODULE: ./src/openlayers/services/FieldService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class FieldService * @category iServer Data Field * @classdesc 字段服务类。 * @example * new FieldService(url).getFields(function(result){ * //doSomething * }); * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {ServiceBase} * @usage */ class FieldService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function FieldService.prototype.getFields * @description 字段查询服务。 * @param {FieldParameters} params - 字段信息查询参数类。 * @param {RequestCallback} callback - 回调函数。 */ getFields(params, callback) { var me = this; var getFieldsService = new GetFieldsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, datasource: params.datasource, dataset: params.dataset }); getFieldsService.processAsync(); } /** * @function FieldService.prototype.getFieldStatisticsInfo * @description 字段统计服务。 * @param {FieldStatisticsParameters} params - 字段统计信息查询参数类。 * @param {RequestCallback} callback - 回调函数。 */ getFieldStatisticsInfo(params, callback) { var me = this, fieldName = params.fieldName, modes = params.statisticMode; if (modes && !core_Util_Util.isArray(modes)) { modes = [modes]; } me.currentStatisticResult = {fieldName: fieldName}; me._statisticsCallback = callback; //针对每种统计方式分别进行请求 modes.forEach(mode => { me.currentStatisticResult[mode] = null; me._fieldStatisticRequest(params.datasource, params.dataset, fieldName, mode); }) } _fieldStatisticRequest(datasource, dataset, fieldName, statisticMode) { var me = this; var statisticService = new FieldStatisticService(me.url, { eventListeners: { scope: me, processCompleted: me._processCompleted, processFailed: me._statisticsCallback }, crossOrigin: me.options.crossOrigin, headers: me.options.headers, datasource: datasource, dataset: dataset, field: fieldName, statisticMode: statisticMode }); statisticService.processAsync(); } _processCompleted(fieldStatisticResult) { var me = this; var getAll = true, result = fieldStatisticResult.result; if (this.currentStatisticResult) { if (null == me.currentStatisticResult[result.mode]) { this.currentStatisticResult[result.mode] = result.result; } } for (var mode in me.currentStatisticResult) { if (null == me.currentStatisticResult[mode]) { getAll = false; break; } } if (getAll) { me._statisticsCallback({result: me.currentStatisticResult}); } } } ;// CONCATENATED MODULE: ./src/openlayers/services/DatasetService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasetService * @category iServer Data Dataset * @classdesc 数据集服务类。 * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {ServiceBase} * @usage */ class DatasetService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function DatasetService.prototype.getDatasets * @description 数据集查询服务。 * @param {string} datasourceName - 数据源名称。 * @param {RequestCallback} callback - 回调函数。 */ getDatasets(datasourceName, callback) { if (!datasourceName) { return; } const me = this; const datasetService = new DatasetService_DatasetService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); datasetService.getDatasetsService(datasourceName); } /** * @function DatasetService.prototype.getDataset * @description 数据集查询服务。 * @param {string} datasourceName - 数据源名称。 * @param {string} datasetName - 数据集名称。 * @param {RequestCallback} callback - 回调函数。 */ getDataset(datasourceName, datasetName, callback) { if (!datasourceName || !datasetName) { return; } const me = this; const datasetService = new DatasetService_DatasetService(me.url, { proxy: me.proxy, withCredentials: me.withCredentials, crossOrigin: me.crossOrigin, headers: me.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); datasetService.getDatasetService(datasourceName, datasetName); } /** * @function DatasetService.prototype.setDataset * @description 数据集信息设置服务。可实现修改已存在数据集,新增不存在数据集。 * @param {CreateDatasetParameters | UpdateDatasetParameters } params - 数据集创建参数类或数据集信息更改参数类。 * @param {RequestCallback} callback - 回调函数。 */ setDataset(params, callback) { if(!(params instanceof CreateDatasetParameters) && !(params instanceof UpdateDatasetParameters)){ return; }else if (params instanceof CreateDatasetParameters) { var datasetParams = { "datasetType": params.datasetType, "datasetName": params.datasetName } }else if(params instanceof UpdateDatasetParameters){ datasetParams = { "datasetName": params.datasetName, "isFileCache": params.isFileCache, "description": params.description, "prjCoordSys": params.prjCoordSys, "charset": params.charset } } const me = this; const url = Util.urlPathAppend(me.url, `datasources/name/${params.datasourceName}/datasets/name/${params.datasetName}`); const datasetService = new DatasetService_DatasetService(url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback } }); datasetService.setDatasetService(datasetParams); } /** * @function DatasetService.prototype.deleteDataset * @description 指定数据源下的数据集删除服务。 * @param {string} datasourceName - 数据源名称。 * @param {string} datasetName - 数据集名称。 * @param {RequestCallback} callback - 回调函数。 */ deleteDataset(datasourceName, datasetName, callback) { const me = this; const url = Util.urlPathAppend(me.url, `datasources/name/${datasourceName}/datasets/name/${datasetName}`); const datasetService = new DatasetService_DatasetService(url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback } }); datasetService.deleteDatasetService(); } } ;// CONCATENATED MODULE: ./src/openlayers/services/DatasourceService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class DatasourceService * @category iServer Data Datasource * @classdesc 数据源服务类。 * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @extends {ServiceBase} * @usage */ class DatasourceService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function DatasourceService.prototype.getDatasources * @description 数据源集查询服务。 * @param {RequestCallback} callback - 回调函数。 */ getDatasources(callback) { const me = this; const datasourceService = new DatasourceService_DatasourceService(me.url, { proxy: me.proxy, withCredentials: me.withCredentials, crossOrigin: me.crossOrigin, headers: me.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); datasourceService.getDatasourcesService(); } /** * @function DatasourceService.prototype.getDatasource * @description 数据源信息查询服务。 * @param {string} datasourceName - 数据源名称。 * @param {RequestCallback} callback 回调函数。 */ getDatasource(datasourceName, callback) { if (!datasourceName) { return; } const me = this; const datasourceService = new DatasourceService_DatasourceService(me.url, { proxy: me.proxy, withCredentials: me.withCredentials, crossOrigin: me.crossOrigin, headers: me.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); datasourceService.getDatasourceService(datasourceName); } /** * @function DatasourceService.prototype.setDatasource * @description 数据源信息设置服务。可实现更改当前数据源信息。 * @param {SetDatasourceParameters} params - 数据源信息设置参数类。 * @param {RequestCallback} callback - 回调函数。 */ setDatasource(params, callback) { if (!(params instanceof SetDatasourceParameters)) { return; } const datasourceParams = { description: params.description , coordUnit: params.coordUnit, distanceUnit: params.distanceUnit }; const me = this; const url = Util.urlPathAppend(me.url,`datasources/name/${params.datasourceName}`); const datasourceService = new DatasourceService_DatasourceService(url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback } }); datasourceService.setDatasourceService(datasourceParams); } } ;// CONCATENATED MODULE: ./src/openlayers/services/GridCellInfosService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** /** * @class GridCellInfosService * @category iServer Data Grid * @classdesc 数据栅格查询服务。 * @extends {ServiceBase} * @example * new GridCellInfosService(url) * .getGridCellInfos(param,function(result){ * //doSomething * }) * @param {string} url - 服务地址。请求地图服务,URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{地图服务名}/rest/maps/{地图名}/tempLayersSet/{tempLayerID}/Rivers@World@@World。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class GridCellInfosService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function GridCellInfosService.prototype.getGridCellInfos * @param {GetGridCellInfosParameters} params - 数据服务栅格查询参数类。 * @param {RequestCallback} callback - 回调函数。 */ getGridCellInfos(params, callback) { if (!params) { return null; } var me = this; var gridCellQueryService = new GetGridCellInfosService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); gridCellQueryService.processAsync(params); } } ;// CONCATENATED MODULE: ./src/openlayers/services/GeoprocessingService.js /** * @class GeoprocessingService * @classdesc 处理自动化服务接口类。 * @version 10.1.0 * @category iServer ProcessingAutomationService * @extends {ServiceBase} * @example * //为了安全访问受保护的处理自动化服务,必须通过传递iserver令牌(token),才能正确访问相关资源。 * SecurityManager.registerToken(serviceUrl, token); * var geoprocessingService = new geoprocessingService("http://localhost:8090/iserver/services/geoprocessing/restjsr/gp/v2") geoprocessingService.submitJob(identifier,params, environments, function(serverResult) { console.log(serverResult.result); var jobID = serverResult.result.jobID; var options = { interval: 5000, statusCallback: function(state) { console.log("Job Status: ", state); } }; geoprocessingService.waitForJobCompletion(jobID, identifier, options, function(serverResult) { console.log(serverResult); }); }) * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @usage */ class GeoprocessingService extends ServiceBase { constructor(url, options) { super(url, options); this.headers = true; this.crossOrigin = true; this.withCredentials = true; this.proxy = true; } /** * @function GeoprocessingService.prototype.getTools * @description 获取处理自动化工具列表。 * @param {RequestCallback} callback 回调函数。 */ getTools(callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.getTools(); } /** * @function GeoprocessingService.prototype.getTool * @description 获取处理自动化工具的ID、名称、描述、输入参数、环境参数和输出结果等相关参数。 * @param {string} identifier - 处理自动化工具ID。 * @param {RequestCallback} callback 回调函数。 */ getTool(identifier, callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.getTool(identifier); } /** * @function GeoprocessingService.prototype.execute * @description 同步执行处理自动化工具。 * @param {string} identifier - 处理自动化工具ID。 * @param {Object} parameter - 处理自动化工具的输入参数。 * @param {Object} environment - 处理自动化工具的环境参数。 * @param {RequestCallback} callback 回调函数。 */ execute(identifier, parameter, environment, callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.execute(identifier, parameter, environment); } /** * @function GeoprocessingService.prototype.submitJob * @description 异步执行处理自动化工具。 * @param {string} identifier - 处理自动化工具ID。 * @param {Object} parameter - 处理自动化工具的输入参数。 * @param {Object} environment - 处理自动化工具的环境参数。 * @param {RequestCallback} callback 回调函数。 */ submitJob(identifier, parameter, environment, callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.submitJob(identifier, parameter, environment); } /** * @function GeoprocessingService.prototype.waitForJobCompletion * @description 获取处理自动化异步执行状态信息。 * @param {string} jobId - 处理自动化任务ID。 * @param {string} identifier - 处理自动化工具ID。 * @param {Object} options - 状态信息参数。 * @param {number} options.interval - 定时器时间间隔。 * @param {function} options.statusCallback - 回调函数。 * @param {RequestCallback} callback 回调函数。 */ waitForJobCompletion(jobId, identifier, options, callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.waitForJobCompletion(jobId, identifier, options); } /** * @function GeoprocessingService.prototype.getJobInfo * @description 获取处理自动化任务的执行信息。 * @param {string} identifier - 处理自动化工具ID。 * @param {string} jobId - 处理自动化任务ID。 * @param {RequestCallback} callback 回调函数。 */ getJobInfo(identifier, jobId, callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.getJobInfo(identifier, jobId); } /** * @function GeoprocessingService.prototype.cancelJob * @description 取消处理自动化任务的异步执行。 * @param {string} identifier - 处理自动化工具ID。 * @param {string} jobId - 处理自动化任务ID。 * @param {RequestCallback} callback 回调函数。 */ cancelJob(identifier, jobId, callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.cancelJob(identifier, jobId); } /** * @function GeoprocessingService.prototype.getJobs * @description 获取处理自动化服务任务列表。 * @param {string} identifier - 处理自动化工具ID。(可选,传参代表identifier算子的任务列表,不传参代表所有任务的列表) * @param {RequestCallback} callback 回调函数。 */ getJobs(identifier, callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.getJobs(identifier); } /** * @function GeoprocessingService.prototype.getResults * @description 处理自动化工具异步执行的结果,支持结果过滤。 * @param {string} identifier - 处理自动化工具ID。 * @param {string} jobId - 处理自动化任务ID。 * @param {string} filter - 输出异步结果的ID。(可选,传入filter参数时对该处理自动化工具执行的结果进行过滤获取,不填参时显示所有的执行结果) * @param {RequestCallback} callback 回调函数。 */ getResults(identifier, jobId, filter, callback) { const geoprocessingJobsService = new GeoprocessingService_GeoprocessingService(this.url, { proxy: this.options.proxy, withCredentials: this.options.withCredentials, crossOrigin: this.options.crossOrigin, headers: this.options.headers, eventListeners: { scope: this, processCompleted: callback, processFailed: callback } }); geoprocessingJobsService.getResults(identifier, jobId, filter); } } ;// CONCATENATED MODULE: ./src/openlayers/services/LayerInfoService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class LayerInfoService * @category iServer Map Layer * @classdesc 图层信息服务类。 * @extends {ServiceBase} * @example * new LayerInfoService(url).getLayersInfo(function(result){ * //doSomething * }) * @param {string} url - 服务地址。请求地图服务,URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{地图服务名}/rest/maps/{地图名}/tempLayersSet/{tempLayerID}/Rivers@World@@World"。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class LayerInfoService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function LayerInfoService.prototype.getLayersInfo * @description 获取图层信息服务。 * @param {RequestCallback} callback - 回调函数。 */ getLayersInfo(callback) { var me = this; var getLayersInfoService = new GetLayersInfoService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback } }); getLayersInfoService.processAsync(); } /** * @function LayerInfoService.prototype.setLayerInfo * @description 设置图层信息服务。可以实现临时图层中子图层的修改。 * @param {SetLayerInfoParameters} params - 设置图层信息参数类。 * @param {RequestCallback} callback - 回调函数。 */ setLayerInfo(params, callback) { if (!params) { return; } var me = this, resourceID = params.resourceID, tempLayerName = params.tempLayerName, layerInfoParams = params.layerInfo; if (!resourceID || !tempLayerName) { return; } var url = Util.urlPathAppend(me.url, "tempLayersSet/" + resourceID + "/" + tempLayerName); var setLayerInfoService = new SetLayerInfoService(url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback } }); setLayerInfoService.processAsync(layerInfoParams); } /** * @function LayerInfoService.prototype.setLayersInfo * @description 设置图层信息服务。可以创建新的临时图层和修改现有的临时图层。 * @param {SetLayersInfoParameters} params - 设置图层信息参数类。 * @param {RequestCallback} callback - 回调函数。 */ setLayersInfo(params, callback) { if (!params) { return; } var me = this, resourceID = params.resourceID, isTempLayers = params.isTempLayers ? params.isTempLayers : false, layersInfo = params.layersInfo; if ((isTempLayers && !resourceID) || !layersInfo) { return; } var setLayersInfoService = new SetLayersInfoService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback }, resourceID: resourceID, isTempLayers: isTempLayers }); setLayersInfoService.processAsync(layersInfo); } /** * @function LayerInfoService.prototype.setLayerStatus * @description 子图层显示控制服务。负责将子图层显示控制参数传递到服务端,并获取服务端返回的图层显示状态。 * @param {SetLayerStatusParameters} params - 子图层显示控制参数类。 * @param {RequestCallback} callback - 回调函数。 */ setLayerStatus(params, callback) { if (!params) { return; } var me = this; var setLayerStatusService = new SetLayerStatusService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { processCompleted: callback, processFailed: callback } }); setLayerStatusService.processAsync(params); } } ;// CONCATENATED MODULE: ./src/openlayers/services/MeasureService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class MeasureService * @category iServer Map Measure * @classdesc 量算服务。 * @extends {ServiceBase} * @param {string} url - 服务地址。如:http://localhost:8090/iserver/services/map-world/rest/maps/World+Map 。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class MeasureService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function MeasureService.prototype.measureDistance * @description 测距。 * @param {MeasureParameters} params - 量算参数类。 * @param {RequestCallback} callback - 回调函数。 */ measureDistance(params, callback) { this.measure(params, 'DISTANCE', callback); } /** * @function MeasureService.prototype.measureArea * @description 测面积。 * @param {MeasureParameters} params - 量算参数类。 * @param {RequestCallback} callback - 回调函数。 */ measureArea(params, callback) { this.measure(params, 'AREA', callback); } /** * @function MeasureService.prototype.measure * @description 测量。 * @param {MeasureParameters} params - 量算参数类。 * @param {string} type - 类型。 * @param {RequestCallback} callback - 回调函数。 * @returns {MeasureService} 量算服务。 */ measure(params, type, callback) { var me = this; var measureService = new MeasureService_MeasureService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, measureMode: type, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); measureService.processAsync(me._processParam(params)); } _processParam(params) { if (params && params.geometry) { params.geometry = core_Util_Util.toSuperMapGeometry(JSON.parse((new (external_ol_format_GeoJSON_default())()).writeGeometry(params.geometry))); } return params; } } ;// CONCATENATED MODULE: ./src/openlayers/services/NetworkAnalyst3DService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class NetworkAnalyst3DService * @category iServer FacilityAnalyst3D * @classdesc 3D 网络分析服务类。 * @extends {ServiceBase} * @example * new NetworkAnalyst3DService(url).sinksFacilityAnalyst(params,function(result){ * //doSomething * }) * @param {string} url - 网络分析服务地址。请求网络分析服务,URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源}; * 例如:"http://localhost:8090/iserver/services/components-rest/rest/networkanalyst/RoadNet@Changchun"。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class NetworkAnalyst3DService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function NetworkAnalyst3DService.prototype.sinksFacilityAnalyst * @description 汇查找服务 * @param {FacilityAnalystSinks3DParameters} params- 最近设施分析参数类(汇查找资源)。 * @param {RequestCallback} callback - 回调函数。 * @returns {NetworkAnalyst3DService} 3D 网络分析服务。 */ sinksFacilityAnalyst(params, callback) { var me = this; var facilityAnalystSinks3DService = new FacilityAnalystSinks3DService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); facilityAnalystSinks3DService.processAsync(params); } /** * @function NetworkAnalyst3DService.prototype.sourcesFacilityAnalyst * @description 源查找服务。 * @param {FacilityAnalystSources3DParameters} params - 最近设施分析参数类(源查找服务)。 * @param {RequestCallback} callback - 回调函数。 * @returns {NetworkAnalyst3DService} 3D 网络分析服务。 */ sourcesFacilityAnalyst(params, callback) { var me = this; var facilityAnalystSources3DService = new FacilityAnalystSources3DService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); facilityAnalystSources3DService.processAsync(params); } /** * @function NetworkAnalyst3DService.prototype.traceUpFacilityAnalyst * @description 上游追踪资源服务。 * @param {FacilityAnalystTraceup3DParameters} params - 上游追踪资源参数类。 * @param {RequestCallback} callback - 回调函数。 * @returns {NetworkAnalyst3DService} 3D 网络分析服务。 */ traceUpFacilityAnalyst(params, callback) { var me = this; var facilityAnalystTraceup3DService = new FacilityAnalystTraceup3DService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); facilityAnalystTraceup3DService.processAsync(params); } /** * @function NetworkAnalyst3DService.prototype.traceDownFacilityAnalyst * @description 下游追踪资源服务。 * @param {FacilityAnalystTracedown3DParameters} params - 下游追踪资源服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @returns {NetworkAnalyst3DService} 3D 网络分析服务。 */ traceDownFacilityAnalyst(params, callback) { var me = this; var facilityAnalystTracedown3DService = new FacilityAnalystTracedown3DService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); facilityAnalystTracedown3DService.processAsync(params); } /** * @function NetworkAnalyst3DService.prototype.upstreamFacilityAnalyst * @description 上游关键设施查找服务。 * @param {FacilityAnalystUpstream3DParameters} params - 上游关键设施查找服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @returns {NetworkAnalyst3DService} 3D 网络分析服务。 */ upstreamFacilityAnalyst(params, callback) { var me = this; var facilityAnalystUpstream3DService = new FacilityAnalystUpstream3DService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); facilityAnalystUpstream3DService.processAsync(params); } } ;// CONCATENATED MODULE: ./src/openlayers/services/NetworkAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class NetworkAnalystService * @category iServer NetworkAnalyst * @classdesc 网络分析服务类。 * @extends {ServiceBase} * @example * new NetworkAnalystService(url).findPath(params,function(result){ * //doSomething * }) * @param {string} url - 网络分析服务地址。请求网络分析服务,URL 应为: * http://{服务器地址}:{服务端口号}/iserver/services/{网络分析服务名}/rest/networkanalyst/{网络数据集@数据源};
* 例如: "http://localhost:8090/iserver/services/test/rest/networkanalyst/WaterNet@FacilityNet"。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class NetworkAnalystService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function NetworkAnalystService.prototype.burstPipelineAnalyst * @description 爆管分析服务:即将给定弧段或节点作为爆管点来进行分析,返回关键结点 ID 数组,普通结点 ID 数组及其上下游弧段 ID 数组。 * @param {BurstPipelineAnalystParameters} params - 爆管分析服务参数类。 * @param {RequestCallback} callback 回调函数。 */ burstPipelineAnalyst(params, callback) { var me = this; var burstPipelineAnalystService = new BurstPipelineAnalystService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); burstPipelineAnalystService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.computeWeightMatrix * @description 耗费矩阵分析服务:根据交通网络分析参数中的耗费字段返回一个耗费矩阵。该矩阵是一个二维数组,用来存储任意两点间的资源消耗。 * @param {ComputeWeightMatrixParameters} params - 耗费矩阵分析服务参数类。 * @param {RequestCallback} callback - 回调函数。 */ computeWeightMatrix(params, callback) { var me = this; var computeWeightMatrixService = new ComputeWeightMatrixService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); computeWeightMatrixService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.findClosestFacilities * @description 最近设施分析服务:指在网络上给定一个事件点和一组设施点,查找从事件点到设施点(或从设施点到事件点)以最小耗费能到达的最佳路径。 * @param {FindClosestFacilitiesParameters} params - 最近设施分析服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ findClosestFacilities(params, callback, resultFormat) { var me = this; var findClosestFacilitiesService = new FindClosestFacilitiesService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); findClosestFacilitiesService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.streamFacilityAnalyst * @description 上游/下游 关键设施查找资源服务:查找给定弧段或节点的上游/下游中的关键设施结点,返回关键结点 ID 数组及其下游弧段 ID 数组。 * @param {FacilityAnalystStreamParameters} params - 上游/下游 关键设施查找资源服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ streamFacilityAnalyst(params, callback, resultFormat) { var me = this; var facilityAnalystStreamService = new FacilityAnalystStreamService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); facilityAnalystStreamService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.findLocation * @description 选址分区分析服务:确定一个或多个待建设施的最佳或最优位置。 * @param {FindLocationParameters} params - 选址分区分析服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ findLocation(params, callback, resultFormat) { var me = this; var findLocationService = new FindLocationService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); findLocationService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.findPath * @description 最佳路径分析服务:在网络数据集中指定一些节点,按照节点的选择顺序,顺序访问这些节点从而求解起止点之间阻抗最小的路经。 * @param {FindPathParameters} params - 最佳路径分析服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ findPath(params, callback, resultFormat) { var me = this; var findPathService = new FindPathService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); findPathService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.findTSPPaths * @description 旅行商分析服务:路径分析的一种,它从起点开始(默认为用户指定的第一点)查找能够遍历所有途经点且花费最小的路径。 * @param {FindTSPPathsParameters} params - 旅行商分析服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ findTSPPaths(params, callback, resultFormat) { var me = this; var findTSPPathsService = new FindTSPPathsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); findTSPPathsService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.findMTSPPaths * @description 多旅行商分析服务:也称为物流配送,是指在网络数据集中,给定 M 个配送中心点和 N 个配送目的地(M,N 为大于零的整数)。查找经济有效的配送路径,并给出相应的行走路线。 * @param {FindMTSPPathsParameters} params - 多旅行商分析服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ findMTSPPaths(params, callback, resultFormat) { var me = this; var findMTSPPathsService = new FindMTSPPathsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); findMTSPPathsService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.findServiceAreas * @description 服务区分析服务:以指定服务站点为中心,在一定服务范围内查找网络上服务站点能够提供服务的区域范围。 * @param {FindServiceAreasParameters} params - 服务区分析服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ findServiceAreas(params, callback, resultFormat) { var me = this; var findServiceAreasService = new FindServiceAreasService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); findServiceAreasService.processAsync(me._processParams(params)); } /** * @function NetworkAnalystService.prototype.updateEdgeWeight * @description 更新边的耗费权重服务。 * @param {UpdateEdgeWeightParameters} params - 更新边的耗费权重服务参数类。 * @param {RequestCallback} callback 回调函数。 */ updateEdgeWeight(params, callback) { var me = this; var updateEdgeWeightService = new UpdateEdgeWeightService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); updateEdgeWeightService.processAsync(params); } /** * @function NetworkAnalystService.prototype.updateTurnNodeWeight * @description 转向耗费权重更新服务。 * @param {UpdateTurnNodeWeightParameters} params - 转向耗费权重更新服务参数类。 * @param {RequestCallback} callback - 回调函数。 */ updateTurnNodeWeight(params, callback) { var me = this; var updateTurnNodeWeightService = new UpdateTurnNodeWeightService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); updateTurnNodeWeightService.processAsync(params); } _processParams(params) { if (!params) { return {}; } if (params.centers && core_Util_Util.isArray(params.centers)) { params.centers.map(function (point, key) { params.centers[key] = (point instanceof (external_ol_geom_Point_default())) ? { x: point.getCoordinates()[0], y: point.getCoordinates()[1] } : point; return params.centers[key]; }); } if (params.nodes && core_Util_Util.isArray(params.nodes)) { params.nodes.map(function (point, key) { params.nodes[key] = (point instanceof (external_ol_geom_Point_default())) ? { x: point.getCoordinates()[0], y: point.getCoordinates()[1] } : point; return params.nodes[key]; }); } if (params.event && params.event instanceof (external_ol_geom_Point_default())) { params.event = {x: params.event.getCoordinates()[0], y: params.event.getCoordinates()[1]}; } if (params.facilities && core_Util_Util.isArray(params.facilities)) { params.facilities.map(function (point, key) { params.facilities[key] = (point instanceof (external_ol_geom_Point_default())) ? { x: point.getCoordinates()[0], y: point.getCoordinates()[1] } : point; return params.facilities[key]; }); } if (params.parameter && params.parameter.barrierPoints) { var barrierPoints = params.parameter.barrierPoints; if (core_Util_Util.isArray(barrierPoints)) { barrierPoints.map(function (point, key) { params.parameter.barrierPoints[key] = (point instanceof (external_ol_geom_Point_default())) ? { x: point.getCoordinates()[0], y: point.getCoordinates()[1] } : point; return params.parameter.barrierPoints[key]; }); } else { params.parameter.barrierPoints = [(barrierPoints instanceof (external_ol_geom_Point_default())) ? { x: barrierPoints.getCoordinates()[0], y: barrierPoints.getCoordinates()[1] } : barrierPoints]; } } return params; } _processFormat(resultFormat) { return (resultFormat) ? resultFormat : DataFormat.GEOJSON; } } ;// CONCATENATED MODULE: ./src/openlayers/services/ProcessingService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ProcessingService * @category iServer ProcessingService * @classdesc 分布式分析相关服务类。 * @extends {ServiceBase} * @example * new ProcessingService(url,options).getKernelDensityJobs(function(result){ * //doSomething * }) * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ProcessingService extends ServiceBase { constructor(url, options) { super(url, options); this.kernelDensityJobs = {}; this.summaryMeshJobs = {}; this.queryJobs = {}; this.summaryRegionJobs = {}; this.vectorClipJobs = {}; this.overlayGeoJobs = {}; this.buffersJobs = {}; this.topologyValidatorJobs = {}; this.summaryAttributesJobs = {}; } /** * @function ProcessingService.prototype.getKernelDensityJobs * @description 获取密度分析的列表。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getKernelDensityJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var kernelDensityJobsService = new KernelDensityJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); kernelDensityJobsService.getKernelDensityJobs(); } /** * @function ProcessingService.prototype.getKernelDensityJob * @description 获取密度分析。 * @param {string} id - 空间分析的 ID。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getKernelDensityJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var kernelDensityJobsService = new KernelDensityJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); kernelDensityJobsService.getKernelDensityJob(id); } /** * @function ProcessingService.prototype.addKernelDensityJob * @description 密度分析。 * @param {KernelDensityJobParameter} params - 核密度分析服务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addKernelDensityJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var kernelDensityJobsService = new KernelDensityJobsService(me.url, { proxy: me.proxy, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.kernelDensityJobs[job.id] = job.state; } }, format: format }); kernelDensityJobsService.addKernelDensityJob(param, seconds); } /** * @function ProcessingService.prototype.getKernelDensityJobState * @description 获取密度分析的状态。 * @param {string} id - 密度分析的 ID。 * @returns {Object} 密度分析的状态 */ getKernelDensityJobState(id) { return this.kernelDensityJobs[id]; } /** * @function ProcessingService.prototype.getSummaryMeshJobs * @description 获取点聚合分析的列表。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getSummaryMeshJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var summaryMeshJobsService = new SummaryMeshJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); summaryMeshJobsService.getSummaryMeshJobs(); } /** * @function ProcessingService.prototype.getSummaryMeshJob * @description 获取点聚合分析。 * @param {string} id - 空间分析的 ID。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getSummaryMeshJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var summaryMeshJobsService = new SummaryMeshJobsService(me.url, { proxy: me.options.proxy, crossOrigin: me.options.crossOrigin, headers: me.options.headers, withCredentials: me.options.withCredentials, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); summaryMeshJobsService.getSummaryMeshJob(id); } /** * @function ProcessingService.prototype.addSummaryMeshJob * @description 点聚合分析。 * @param {SummaryMeshJobParameter} params - 点聚合分析任务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addSummaryMeshJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var summaryMeshJobsService = new SummaryMeshJobsService(me.url, { proxy: me.proxy, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.summaryMeshJobs[job.id] = job.state; } }, format: format }); summaryMeshJobsService.addSummaryMeshJob(param, seconds); } /** * @function ProcessingService.prototype.getSummaryMeshJobState * @description 获取点聚合分析的状态。 * @param {string} id - 点聚合分析的 ID。 * @returns {Object} 点聚合分析的状态。 */ getSummaryMeshJobState(id) { return this.summaryMeshJobs[id]; } /** * @function ProcessingService.prototype.getQueryJobs * @description 获取单对象查询分析的列表。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getQueryJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var singleObjectQueryJobsService = new SingleObjectQueryJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); singleObjectQueryJobsService.getQueryJobs(); } /** * @function ProcessingService.prototype.getQueryJob * @description 获取单对象查询分析。 * @param {string} id - 空间分析的 ID。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getQueryJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var singleObjectQueryJobsService = new SingleObjectQueryJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); singleObjectQueryJobsService.getQueryJob(id); } /** * @function ProcessingService.prototype.addQueryJob * @description 单对象查询分析。 * @param {SingleObjectQueryJobsParameter} params - 单对象空间查询分析任务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addQueryJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var singleObjectQueryJobsService = new SingleObjectQueryJobsService(me.url, { proxy: me.proxy, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.queryJobs[job.id] = job.state; } }, format: format }); singleObjectQueryJobsService.addQueryJob(param, seconds); } /** * @function ProcessingService.prototype.getQueryJobState * @description 获取单对象查询分析的状态。 * @param {string} id - 单对象查询分析的 ID。 * @returns {Object} 单对象查询分析的状态。 */ getQueryJobState(id) { return this.queryJobs[id]; } /** * @function ProcessingService.prototype.getSummaryRegionJobs * @description 获取区域汇总分析的列表。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getSummaryRegionJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var summaryRegionJobsService = new SummaryRegionJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); summaryRegionJobsService.getSummaryRegionJobs(); } /** * @function ProcessingService.prototype.getSummaryRegionJob * @description 获取区域汇总分析。 * @param {string} id - 区域汇总分析的 ID。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getSummaryRegionJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var summaryRegionJobsService = new SummaryRegionJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); summaryRegionJobsService.getSummaryRegionJob(id); } /** * @function ProcessingService.prototype.addSummaryRegionJob * @description 区域汇总分析。 * @param {SummaryRegionJobParameter} params - 区域汇总分析任务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addSummaryRegionJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var summaryRegionJobsService = new SummaryRegionJobsService(me.url, { proxy: me.proxy, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.summaryRegionJobs[job.id] = job.state; } }, format: format }); summaryRegionJobsService.addSummaryRegionJob(param, seconds); } /** * @function ProcessingService.prototype.getSummaryRegionJobState * @description 获取区域汇总分析的状态。 * @param {string} id - 生成区域汇总分析的 ID。 * @returns {Object} 区域汇总分析的状态。 */ getSummaryRegionJobState(id) { return this.summaryRegionJobs[id]; } /** * @function ProcessingService.prototype.getVectorClipJobs * @description 获取矢量裁剪分析的列表。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getVectorClipJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var vectorClipJobsService = new VectorClipJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); vectorClipJobsService.getVectorClipJobs(); } /** * @function ProcessingService.prototype.getVectorClipJob * @description 获取矢量裁剪分析。 * @param {string} id - 空间分析的 ID。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getVectorClipJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var vectorClipJobsService = new VectorClipJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); vectorClipJobsService.getVectorClipJob(id); } /** * @function ProcessingService.prototype.addVectorClipJob * @description 矢量裁剪分析。 * @param {VectorClipJobsParameter} params - 矢量裁剪分析任务参数类。 * @param {RequestCallback} callback 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addVectorClipJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var vectorClipJobsService = new VectorClipJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.vectorClipJobs[job.id] = job.state; } }, format: format }); vectorClipJobsService.addVectorClipJob(param, seconds); } /** * @function ProcessingService.prototype.getVectorClipJobState * @description 获取矢量裁剪分析的状态。 * @param {number} id - 矢量裁剪分析的 ID。 * @returns {Object} 矢量裁剪分析的状态。 */ getVectorClipJobState(id) { return this.vectorClipJobs[id]; } /** * @function ProcessingService.prototype.getOverlayGeoJobs * @description 获取叠加分析的列表。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getOverlayGeoJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var overlayGeoJobsService = new OverlayGeoJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); overlayGeoJobsService.getOverlayGeoJobs(); } /** * @function ProcessingService.prototype.getOverlayGeoJob * @description 获取叠加分析。 * @param {string} id - 空间分析的 ID。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getOverlayGeoJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var overlayGeoJobsService = new OverlayGeoJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); overlayGeoJobsService.getOverlayGeoJob(id); } /** * @function ProcessingService.prototype.addOverlayGeoJob * @description 叠加分析。 * @param {OverlayGeoJobParameter} params - 叠加分析任务参数类。 * @param {RequestCallback} callback 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addOverlayGeoJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var overlayGeoJobsService = new OverlayGeoJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.overlayGeoJobs[job.id] = job.state; } }, format: format }); overlayGeoJobsService.addOverlayGeoJob(param, seconds); } /** * @function ProcessingService.prototype.getoverlayGeoJobState * @description 获取叠加分析的状态。 * @param {string} id - 叠加分析的 ID。 * @returns {Object} 叠加分析的状态。 */ getoverlayGeoJobState(id) { return this.overlayGeoJobs[id]; } /** * @function ProcessingService.prototype.getBuffersJobs * @description 获取缓冲区分析的列表。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getBuffersJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var buffersAnalystJobsService = new BuffersAnalystJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); buffersAnalystJobsService.getBuffersJobs(); } /** * @function ProcessingService.prototype.getBuffersJob * @description 获取缓冲区分析。 * @param {string} id - 空间分析的 ID。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getBuffersJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var buffersAnalystJobsService = new BuffersAnalystJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); buffersAnalystJobsService.getBuffersJob(id); } /** * @function ProcessingService.prototype.addBuffersJob * @description 缓冲区分析。 * @param {BuffersAnalystJobsParameter} params - 缓冲区分析任务参数类。 * @param {RequestCallback} callback 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addBuffersJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var buffersAnalystJobsService = new BuffersAnalystJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.buffersJobs[job.id] = job.state; } }, format: format }); buffersAnalystJobsService.addBuffersJob(param, seconds); } /** * @function ProcessingService.prototype.getBuffersJobState * @description 获取缓冲区分析的状态。 * @param {string} id - 缓冲区分析的 ID。 * @returns {Object} 缓冲区分析的状态。 */ getBuffersJobState(id) { return this.buffersJobs[id]; } /** * @function ProcessingService.prototype.getTopologyValidatorJobs * @description 获取拓扑检查分析的列表。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getTopologyValidatorJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var topologyValidatorJobsService = new TopologyValidatorJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); topologyValidatorJobsService.getTopologyValidatorJobs(); } /** * @function ProcessingService.prototype.getTopologyValidatorJob * @description 获取拓扑检查分析。 * @param {string} id - 空间分析的 ID。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getTopologyValidatorJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var topologyValidatorJobsService = new TopologyValidatorJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); topologyValidatorJobsService.getTopologyValidatorJob(id); } /** * @function ProcessingService.prototype.addTopologyValidatorJob * @description 拓扑检查分析。 * @param {TopologyValidatorJobsParameter} params - 拓扑检查分析任务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addTopologyValidatorJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var topologyValidatorJobsService = new TopologyValidatorJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.topologyValidatorJobs[job.id] = job.state; } }, format: format }); topologyValidatorJobsService.addTopologyValidatorJob(param, seconds); } /** * @function ProcessingService.prototype.getTopologyValidatorJobState * @description 获取拓扑检查分析的状态。 * @param {string} id - 拓扑检查分析的 ID。 * @returns {Object} 拓扑检查分析的状态。 */ getTopologyValidatorJobState(id) { return this.topologyValidatorJobs[id]; } /** * @function ProcessingService.prototype.getSummaryAttributesJobs * @description 获取拓扑检查属性汇总分析的列表。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getSummaryAttributesJobs(callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var summaryAttributesJobsService = new SummaryAttributesJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); summaryAttributesJobsService.getSummaryAttributesJobs(); } /** * @function ProcessingService.prototype.getSummaryAttributesJob * @description 获取属性汇总分析。 * @param {string} id - 空间分析的 ID。 * @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ getSummaryAttributesJob(id, callback, resultFormat) { var me = this, format = me._processFormat(resultFormat); var summaryAttributesJobsService = new SummaryAttributesJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: format }); summaryAttributesJobsService.getSummaryAttributesJob(id); } /** * @function ProcessingService.prototype.addSummaryAttributesJob * @description 属性汇总分析。 * @param {SummaryAttributesJobsParameter} params - 属性汇总分析任务参数类。 * @param {RequestCallback} callback - 回调函数。 * @param {number} [seconds=1000] - 获取创建成功结果的时间间隔。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回结果类型。 */ addSummaryAttributesJob(params, callback, seconds, resultFormat) { var me = this, param = me._processParams(params), format = me._processFormat(resultFormat); var summaryAttributesJobsService = new SummaryAttributesJobsService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback, processRunning: function (job) { me.summaryAttributesJobs[job.id] = job.state; } }, format: format }); summaryAttributesJobsService.addSummaryAttributesJob(param, seconds); } /** * @function ProcessingService.prototype.getSummaryAttributesJobState * @description 获取属性汇总分析的状态。 * @param {string} id - 属性汇总分析的 ID。 * @returns {Object} 属性汇总分析的状态。 */ getSummaryAttributesJobState(id) { return this.summaryAttributesJobs[id]; } _processFormat(resultFormat) { return (resultFormat) ? resultFormat : DataFormat.GEOJSON; } _processParams(params) { if (!params) { return {}; } if (params.bounds) { params.bounds = core_Util_Util.toSuperMapBounds(params.bounds); } if (params.query) { params.query = core_Util_Util.toSuperMapBounds(params.query); } if (params.geometryQuery) { params.geometryQuery = core_Util_Util.toProcessingParam(params.geometryQuery); } if (params.geometryClip) { params.geometryClip = core_Util_Util.toProcessingParam(params.geometryClip); } return params; } } ;// CONCATENATED MODULE: ./src/openlayers/services/SpatialAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class SpatialAnalystService * @extends {ServiceBase} * @category iServer SpatialAnalyst * @classdesc 空间分析服务类。提供:地区太阳辐射、缓冲区分析、点密度分析、动态分段分析、空间关系分析、插值分析、栅格代数运算、叠加分析、路由定位、路由测量计算、表面分析、地形曲率计算、泰森多边形分析。 * @example * new SpatialAnalystService(url).bufferAnalysis(params,function(result){ * //doSomething * }) * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class SpatialAnalystService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function SpatialAnalystService.prototype.getAreaSolarRadiationResult * @description 地区太阳辐射。 * @param {AreaSolarRadiationParameters} params - 地区太阳辐射参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ getAreaSolarRadiationResult(params, callback, resultFormat) { var me = this; var areaSolarRadiationService = new AreaSolarRadiationService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); areaSolarRadiationService.processAsync(params); } /** * @function SpatialAnalystService.prototype.bufferAnalysis * @description 缓冲区分析。 * @param {DatasetBufferAnalystParameters} params - 数据集缓冲区分析参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ bufferAnalysis(params, callback, resultFormat) { var me = this; var bufferAnalystService = new BufferAnalystService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); bufferAnalystService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.densityAnalysis * @description 点密度分析。 * @param {DensityKernelAnalystParameters} params - 核密度分析参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ densityAnalysis(params, callback, resultFormat) { var me = this; var densityAnalystService = new DensityAnalystService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); densityAnalystService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.generateSpatialData * @description 动态分段分析。 * @param {GenerateSpatialDataParameters} params - 动态分段操作参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ generateSpatialData(params, callback, resultFormat) { var me = this; var generateSpatialDataService = new GenerateSpatialDataService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); generateSpatialDataService.processAsync(params); } /** * @function SpatialAnalystService.prototype.geoRelationAnalysis * @description 空间关系分析。 * @param {GeoRelationAnalystParameters} params - 空间关系分析服务参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ geoRelationAnalysis(params, callback, resultFormat) { var me = this; var geoRelationAnalystService = new GeoRelationAnalystService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); geoRelationAnalystService.processAsync(params); } /** * @function SpatialAnalystService.prototype.interpolationAnalysis * @description 插值分析。 * @param {InterpolationRBFAnalystParameters|InterpolationDensityAnalystParameters|InterpolationIDWAnalystParameters|InterpolationKrigingAnalystParameters} params - 样条插值分析参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ interpolationAnalysis(params, callback, resultFormat) { var me = this; var interpolationAnalystService = new InterpolationAnalystService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); interpolationAnalystService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.mathExpressionAnalysis * @description 栅格代数运算。 * @param {MathExpressionAnalysisParameters} params - 栅格代数运算参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ mathExpressionAnalysis(params, callback, resultFormat) { var me = this; var mathExpressionAnalysisService = new MathExpressionAnalysisService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); mathExpressionAnalysisService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.overlayAnalysis * @description 叠加分析。 * @param {DatasetOverlayAnalystParameters|GeometryOverlayAnalystParameters} params - 数据集叠加分析参数类或几何对象叠加分析参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ overlayAnalysis(params, callback, resultFormat) { var me = this; var overlayAnalystService = new OverlayAnalystService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); overlayAnalystService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.routeCalculateMeasure * @description 路由测量计算。 * @param {RouteCalculateMeasureParameters} params - 基于路由对象计算指定点 M 值操作的参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ routeCalculateMeasure(params, callback, resultFormat) { var me = this; var routeCalculateMeasureService = new RouteCalculateMeasureService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); routeCalculateMeasureService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.routeLocate * @description 路由定位。 * @param {RouteLocatorParameters} params - 路由对象定位空间对象的参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ routeLocate(params, callback, resultFormat) { var me = this; var routeLocatorService = new RouteLocatorService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); routeLocatorService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.surfaceAnalysis * @description 表面分析。 * @param {SurfaceAnalystParameters} params - 表面分析提取操作参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ surfaceAnalysis(params, callback, resultFormat) { var me = this; var surfaceAnalystService = new SurfaceAnalystService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); surfaceAnalystService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.terrainCurvatureCalculate * @description 地形曲率计算。 * @param {TerrainCurvatureCalculationParameters} params - 地形曲率计算参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ terrainCurvatureCalculate(params, callback, resultFormat) { var me = this; var terrainCurvatureCalculationService = new TerrainCurvatureCalculationService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); terrainCurvatureCalculationService.processAsync(params); } /** * @function SpatialAnalystService.prototype.thiessenAnalysis * @description 泰森多边形分析。 * @param {DatasetThiessenAnalystParameters|GeometryThiessenAnalystParameters} params - 数据集泰森多边形分析参数类。 * @param {RequestCallback} callback 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ thiessenAnalysis(params, callback, resultFormat) { var me = this; var thiessenAnalystService = new ThiessenAnalystService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); thiessenAnalystService.processAsync(me._processParams(params)); } /** * @function SpatialAnalystService.prototype.geometrybatchAnalysis * @description 批量空间分析。 * @param {Array.} params - 批量分析参数对象数组。 * @param {Array.} params.analystName - 空间分析方法的名称。包括:
* "buffer","overlay","interpolationDensity","interpolationidw","interpolationRBF","interpolationKriging","isoregion","isoline"。 * @param {Object} params.param - 空间分析类型对应的请求参数,包括:
* {@link GeometryBufferAnalystParameters} 缓冲区分析参数类。
* {@link GeometryOverlayAnalystParameters} 叠加分析参数类。
* {@link InterpolationAnalystParameters} 插值分析参数类。
* {@link SurfaceAnalystParameters} 表面分析参数类。
* @param {RequestCallback} callback - 回调函数。 * @param {DataFormat} [resultFormat=DataFormat.GEOJSON] - 返回的结果类型。 */ geometrybatchAnalysis(params, callback, resultFormat) { var me = this; var geometryBatchAnalystService = new GeometryBatchAnalystService(me.url, { eventListeners: { scope: me, processCompleted: callback, processFailed: callback }, format: me._processFormat(resultFormat) }); //处理批量分析中各个分类类型的参数: var analystParameters = []; for (var i = 0; i < params.length; i++) { var tempParameter = params[i]; analystParameters.push({ analystName: tempParameter.analystName, param: me._processParams(tempParameter.param) }) } geometryBatchAnalystService.processAsync(analystParameters); } _processParams(params) { if (!params) { return {}; } if (params.bounds) { params.bounds = core_Util_Util.toSuperMapBounds(params.bounds); } if (params.inputPoints) { for (let i = 0; i < params.inputPoints.length; i++) { var inputPoint = params.inputPoints[i]; if (core_Util_Util.isArray(inputPoint)) { params.inputPoints[i] = {x: inputPoint[0], y: inputPoint[1], tag: inputPoint[2]}; } else { params.inputPoints[i] = { x: inputPoint.getCoordinates()[0], y: inputPoint.getCoordinates()[1], tag: inputPoint.tag }; } } } if (params.points) { for (let i = 0; i < params.points.length; i++) { let point = params.points[i]; if (core_Util_Util.isArray(point)) { point.setCoordinates(point); } params.points[i] = new Point(point.getCoordinates()[0], point.getCoordinates()[1]); } } if (params.point) { let point = params.point; if (core_Util_Util.isArray(point)) { point.setCoordinates(point); } params.point = new Point(point.getCoordinates()[0], point.getCoordinates()[1]); } if (params.extractRegion) { params.extractRegion = this.convertGeometry(params.extractRegion); } if (params.extractParameter && params.extractParameter.clipRegion) { params.extractParameter.clipRegion = this.convertGeometry(params.extractParameter.clipRegion); } if (params.clipParam && params.clipParam.clipRegion) { params.clipParam.clipRegion = this.convertGeometry(params.clipParam.clipRegion); } //支持格式:Vector Layers; GeoJson if (params.sourceGeometry) { var SRID = null; if (params.sourceGeometrySRID) { SRID = params.sourceGeometrySRID; } params.sourceGeometry = this.convertGeometry(params.sourceGeometry); if (SRID) { params.sourceGeometry.SRID = SRID; } delete params.sourceGeometry.sourceGeometrySRID; } if (params.operateGeometry) { params.operateGeometry = this.convertGeometry(params.operateGeometry); } //支持传入多个几何要素进行叠加分析: if (params.sourceGeometries) { var sourceGeometries = []; for (var k = 0; k < params.sourceGeometries.length; k++) { sourceGeometries.push(this.convertGeometry(params.sourceGeometries[k])); } params.sourceGeometries = sourceGeometries; } //支持传入多个几何要素进行叠加分析: if (params.operateGeometries) { var operateGeometries = []; for (var j = 0; j < params.operateGeometries.length; j++) { operateGeometries.push(this.convertGeometry(params.operateGeometries[j])); } params.operateGeometries = operateGeometries; } if (params.sourceRoute) { if (params.sourceRoute instanceof (external_ol_geom_LineString_default()) && params.sourceRoute.getCoordinates()) { var target = {}; target.type = "LINEM"; target.parts = [params.sourceRoute.getCoordinates()[0].length]; target.points = []; for (let i = 0; i < params.sourceRoute.getCoordinates()[0].length; i++) { let point = params.sourceRoute.getCoordinates()[0][i]; target.points = target.points.concat({x: point[0], y: point[1], measure: point[2]}) } params.sourceRoute = target; } } var me = this; if (params.operateRegions && core_Util_Util.isArray(params.operateRegions)) { params.operateRegions.map(function (geometry, key) { params.operateRegions[key] = me.convertGeometry(geometry); return params.operateRegions[key]; }); } if (params.sourceRoute && params.sourceRoute.components && core_Util_Util.isArray(params.sourceRoute.components)) { params.sourceRoute.components.map(function (geometry, key) { params.sourceRoute.components[key] = me.convertGeometry(geometry); return params.sourceRoute.components[key]; }); } return params; } _processFormat(resultFormat) { return (resultFormat) ? resultFormat : DataFormat.GEOJSON; } /** * @private * @function SpatialAnalystService.prototype.convertGeometry * @description 转换几何对象。 * @param {Object} ol3Geometry - 待转换的几何对象。 */ convertGeometry(ol3Geometry) { //判断是否传入的是geojson 并作相应处理 if(["FeatureCollection", "Feature", "Geometry"].indexOf(ol3Geometry.type) != -1){ return core_Util_Util.toSuperMapGeometry(ol3Geometry); } return core_Util_Util.toSuperMapGeometry(JSON.parse((new (external_ol_format_GeoJSON_default())()).writeGeometry(ol3Geometry))); } } ;// CONCATENATED MODULE: ./src/openlayers/services/ThemeService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ThemeService * @category iServer Map Theme * @classdesc 专题图服务类。 * @extends {ServiceBase} * @example * new ThemeService(url,{ * projection:projection * }).getThemeInfo(params,function(result){ * //doSomething * }); * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ThemeService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function ThemeService.prototype.getThemeInfo * @description 获取专题图信息。 * @param {ThemeParameters} params - 专题图参数类。 * @param {RequestCallback} callback 回调函数。 */ getThemeInfo(params, callback) { var me = this; var themeService = new ThemeService_ThemeService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); themeService.processAsync(params); } } ;// CONCATENATED MODULE: ./src/openlayers/services/TrafficTransferAnalystService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class TrafficTransferAnalystService * @extends {ServiceBase} * @category iServer TrafficTransferAnalyst * @classdesc 交通换乘分析服务类。 * @example * new TrafficTransferAnalystService(url).queryStop(params,function(result){ * //doSomething * }) * @param {string} url - 服务地址。 * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class TrafficTransferAnalystService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function TrafficTransferAnalystService.prototype.queryStop * @description 站点查询服务。 * @param {StopQueryParameters} params - 查询相关参数类。 * @param {RequestCallback} callback - 回调函数。 */ queryStop(params, callback) { var me = this; var stopQueryService = new StopQueryService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); stopQueryService.processAsync(params); } /** * @function TrafficTransferAnalystService.prototype.analysisTransferPath * @description 交通换乘线路查询服务。 * @param {TransferPathParameters} params - 查询相关参数类。 * @param {RequestCallback} callback - 回调函数。 */ analysisTransferPath(params, callback) { var me = this; var transferPathService = new TransferPathService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); transferPathService.processAsync(me._processParams(params)); } /** * @function TrafficTransferAnalystService.prototype.analysisTransferSolution * @description 交通换乘方案查询服务。 * @param {TransferSolutionParameters} params - 查询相关参数类。 * @param {RequestCallback} callback - 回调函数。 */ analysisTransferSolution(params, callback) { var me = this; var transferSolutionService = new TransferSolutionService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); transferSolutionService.processAsync(me._processParams(params)); } _processParams(params) { if (!params) { return {}; } if (params.transferLines && !core_Util_Util.isArray(params.transferLines)) { params.transferLines = [params.transferLines]; } if (params.points && core_Util_Util.isArray(params.points)) { params.points.map(function (point, key) { params.points[key] = (point instanceof (external_ol_geom_Point_default())) ? { x: point.getCoordinates()[0], y: point.getCoordinates()[1] } : point; return params.points[key]; }); } return params; } } ;// CONCATENATED MODULE: ./src/openlayers/services/WebPrintingJobService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class WebPrintingJobService * @category iServer WebPrintingJob * @version 10.1.0 * @classdesc Web 打印服务类。 * 提供:创建 Web 打印任务,获取 Web 打印任务内容,获取 Web 打印输出文档流,获取 Web 打印服务的布局模板信息。 * @extends {ServiceBase} * @param {string} url - 服务地址。请求打印地图服务的 URL 应为:http://{服务器地址}:{服务端口号}/iserver/services/webprinting/rest/webprinting/v1。 * @param {Object} options - 服务交互时所需的可选参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @example * new WebPrintingJobService(url).createWebPrintingJob(param,function(result){ * //doSomething * }) * @usage */ class WebPrintingJobService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function WebPrintingJobService.prototype.createWebPrintingJob * @description 创建 Web 打印任务。 * @param {WebPrintingJobParameters} params - Web 打印参数类。 * @param {RequestCallback} callback - 回调函数。 */ createWebPrintingJob(params, callback) { if (!params) { return; } var me = this; var webPrintingService = new WebPrintingService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); webPrintingService.createWebPrintingJob(me._processParams(params)); } /** * @function WebPrintingJobService.prototype.getPrintingJob * @description 获取 Web 打印输出文档任务。 * @param {string} jobId - Web 打印输入文档任务 ID。 * @param {RequestCallback} callback - 回调函数。 */ getPrintingJob(jobId, callback) { var me = this; var webPrintingService = new WebPrintingService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); webPrintingService.getPrintingJob(jobId); } /** * @function WebPrintingJobService.prototype.getPrintingJobResult * @description 获取 Web 打印任务的输出文档。 * @param {string} jobId - Web 打印输入文档任务 ID。 * @param {RequestCallback} callback - 回调函数。 */ getPrintingJobResult(jobId, callback) { var me = this; var webPrintingService = new WebPrintingService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); webPrintingService.getPrintingJobResult(jobId); } /** * @function WebPrintingJobService.prototype.getLayoutTemplates * @description 查询 Web 打印服务所有可用的模板信息。 * @param {RequestCallback} callback - 回调函数。 */ getLayoutTemplates(callback) { var me = this; var webPrintingService = new WebPrintingService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); webPrintingService.getLayoutTemplates(); } _processParams(params) { if (params.layoutOptions && params.layoutOptions.littleMapOptions) { params.layoutOptions.littleMapOptions.center = this._toPointObject( params.layoutOptions.littleMapOptions.center ); } if (params.exportOptions) { params.exportOptions.center = this._toPointObject(params.exportOptions.center); } return params; } _toPointObject(point) { if (core_Util_Util.isArray(point)) { return { x: point[0], y: point[1] }; } else if (point instanceof Point || point instanceof (external_ol_geom_Point_default())) { return { x: point.x, y: point.y }; } return point; } } ;// CONCATENATED MODULE: ./src/openlayers/services/ImageService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageService * @version 10.2.0 * @constructs ImageService * @classdesc 影像服务类。 * @category iServer Image * @extends {ServiceBase} * @example * ImageService(url,options).getCollections(function(result){ * //doSomething * }) * @param {string} url - 服务地址。例如: http://{ip}:{port}/iserver/{imageservice-imageserviceName}/restjsr/ * @param {Object} options - 参数。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ImageService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function ImageService.prototype.getCollections * @description 返回当前影像服务中的影像集合列表(Collections)。 * @param {RequestCallback} callback - 回调函数。 */ getCollections(callback) { var me = this; var ImageService = new ImageService_ImageService(this.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageService.getCollections(); } /** * @function ImageService.prototype.getCollectionByID * @description ID值等于`collectionId`参数值的影像集合(Collection)。ID值用于在服务中唯一标识该影像集合。 * @param {string} collectionId 影像集合(Collection)的ID,在一个影像服务中唯一标识影像集合。 * @param {RequestCallback} callback - 回调函数。 */ getCollectionByID(collectionId, callback) { var me = this; var ImageService = new ImageService_ImageService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageService.getCollectionByID(collectionId); } /** * @function ImageService.prototype.search * @description 查询与过滤条件匹配的影像数据。 * @param {ImageSearchParameter} [itemSearch] 查询参数。 * @param {RequestCallback} callback - 回调函数。 */ search(itemSearch, callback) { var me = this; var ImageService = new ImageService_ImageService(me.url, { proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageService.search(itemSearch); } } ;// CONCATENATED MODULE: ./src/openlayers/services/ImageCollectionService.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageCollectionService * @version 10.2.0 * @constructs ImageCollectionService * @classdesc 影像集合服务类。 * @category iServer Image * @extends {ServiceBase} * @example * new ImageCollectionService(url,options).getLegend(queryParams,function(result){ * //doSomething * }) * @param {string} url - 服务地址。例如: http://{ip}:{port}/iserver/{imageservice-imageserviceName}/restjsr/ * @param {Object} options - 参数。 * @param {string} options.collectionId 影像集合(Collection)的ID,在一个影像服务中唯一标识影像集合。 * @param {string} [options.proxy] - 服务代理地址。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。 * @param {Object} [options.headers] - 请求头。 * @usage */ class ImageCollectionService extends ServiceBase { constructor(url, options) { super(url, options); } /** * @function ImageCollectionService.prototype.getLegend * @param {Object} queryParams query参数。 * @param {ImageRenderingRule} [queryParams.renderingRule] 指定影像显示的风格,包含拉伸显示方式、颜色表、波段组合以及应用栅格函数进行快速处理等。不指定时,使用发布服务时所配置的风格。 * @param {RequestCallback} callback - 回调函数。 */ getLegend(queryParams, callback) { var me = this; var ImageCollectionService = new ImageCollectionService_ImageCollectionService(this.url, { collectionId: me.options.collectionId, proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageCollectionService.getLegend(queryParams); } /** * @function ImageCollectionService.prototype.getStatistics * @description 返回当前影像集合的统计信息。包括文件数量,文件大小等信息。 * @param {RequestCallback} callback - 回调函数。 */ getStatistics(callback) { var me = this; var ImageCollectionService = new ImageCollectionService_ImageCollectionService(me.url, { collectionId: me.options.collectionId, proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageCollectionService.getStatistics(); } /** * @function ImageCollectionService.prototype.getTileInfo * @description 返回影像集合所提供的服务瓦片的信息,包括:每层瓦片的分辨率,比例尺等信息,方便前端进行图层叠加。 * @param {RequestCallback} callback - 回调函数。 */ getTileInfo(callback) { var me = this; var ImageCollectionService = new ImageCollectionService_ImageCollectionService(me.url, { collectionId: me.options.collectionId, proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageCollectionService.getTileInfo(); } /** * @function ImageCollectionService.prototype.deleteItemByID * @description 删除影像集合中的指定ID(`featureId`)的Item对象,即从影像集合中删除指定的影像。 * @param {string} featureId Feature 的本地标识符。 * @param {RequestCallback} callback - 回调函数。 */ deleteItemByID(featureId, callback) { var me = this; var ImageCollectionService = new ImageCollectionService_ImageCollectionService(this.url, { collectionId: me.options.collectionId, proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageCollectionService.deleteItemByID(featureId); } /** * @function ImageCollectionService.prototype.getItemByID * @description 返回影像集合中的指定ID(`featureId`)的Item对象,即返回影像集合中指定的影像。 * @param {string} featureId Feature 的本地标识符。 * @param {RequestCallback} callback - 回调函数。 */ getItemByID(featureId, callback) { var me = this; var ImageCollectionService = new ImageCollectionService_ImageCollectionService(me.url, { collectionId: me.options.collectionId, proxy: me.options.proxy, withCredentials: me.options.withCredentials, crossOrigin: me.options.crossOrigin, headers: me.options.headers, eventListeners: { scope: me, processCompleted: callback, processFailed: callback } }); ImageCollectionService.getItemByID(featureId); } } ;// CONCATENATED MODULE: ./src/openlayers/services/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/openlayers/mapping/webmap/config/ProvinceCenter.json const ProvinceCenter_namespaceObject = JSON.parse('[{"name":"黑龙江省","coord":[127.64559817675396,48.48668098449708]},{"name":"内蒙古自治区","coord":[118.34519572208615,45.370218276977525]},{"name":"新疆维吾尔自治区","coord":[87.13479065593184,41.75497055053711]},{"name":"吉林省","coord":[126.12985278813787,43.57983207702637]},{"name":"辽宁省","coord":[124.02494773936439,41.105743408203125]},{"name":"甘肃省","coord":[102.87785725633012,37.69582366943361]},{"name":"河北省","coord":[115.66327227481898,39.33383178710938]},{"name":"北京市","coord":[116.62199343603638,40.25053787231445]},{"name":"山西省","coord":[112.45180235808988,37.666561126708984]},{"name":"天津市","coord":[117.35711842642581,39.406789779663086]},{"name":"陕西省","coord":[109.56294003056632,35.64754199981689]},{"name":"宁夏回族自治区","coord":[105.96110877640074,37.3081169128418]},{"name":"青海省","coord":[96.07301048277901,35.44417190551758]},{"name":"山东省","coord":[118.03833752951093,36.29800605773925]},{"name":"西藏自治区","coord":[87.47361520439412,31.6703872680664]},{"name":"河南省","coord":[113.07832397097275,33.87751102447509]},{"name":"江苏省","coord":[119.93926538201052,32.945452690124505]},{"name":"安徽省","coord":[117.15146765881019,32.024482727050774]},{"name":"四川省","coord":[102.28998890142759,30.182161331176758]},{"name":"湖北省","coord":[112.87798261431585,31.157071113586426]},{"name":"重庆市","coord":[107.870126637831,30.188085556030266]},{"name":"上海市","coord":[121.42561166015514,31.276043891906745]},{"name":"浙江省","coord":[119.75337092707514,29.175934791564945]},{"name":"湖南省","coord":[111.52770282777405,27.38110256195069]},{"name":"江西省","coord":[115.51091280655628,27.283511161804206]},{"name":"云南省","coord":[101.27053825991308,25.19783210754396]},{"name":"贵州省","coord":[106.49672346773299,26.92267990112305]},{"name":"福建省","coord":[117.9976766946587,25.939599990844727]},{"name":"广西壮族自治区","coord":[108.98706831086302,23.891559600830078]},{"name":"台湾省","coord":[120.82468432537434,23.602651596069336]},{"name":"香港特别行政区","coord":[114.21036850371561,22.374858856201172]},{"name":"海南省","coord":[109.62792940960824,19.163116455078125]},{"name":"广东省","coord":[113.32127888266032,22.873867034912106]},{"name":"澳门特别行政区","coord":[113.56819996291901,22.160347992976]}]'); ;// CONCATENATED MODULE: ./src/openlayers/mapping/webmap/config/MunicipalCenter.json const MunicipalCenter_namespaceObject = JSON.parse('[{"name":"克拉玛依市","coord":[85.01486759299489,45.406422237230046]},{"name":"昌吉回族自治州","coord":[88.7154624754753,44.26991024636568]},{"name":"石河子市","coord":[86.0208600035924,44.239045558096805]},{"name":"霍林郭勒市","coord":[114.73479243733115,44.16058374713977]},{"name":"本溪市","coord":[124.64357865201586,41.177197783134275]},{"name":"嘉峪关市","coord":[98.16891560537093,39.76279786284264]},{"name":"莱芜市","coord":[117.65723565456207,36.27916499211527]},{"name":"神农架林区","coord":[110.48296222218153,31.581260143666697]},{"name":"天门市","coord":[113.00615321481195,30.64105781887143]},{"name":"鄂州市","coord":[114.94764081970385,30.325634953844585]},{"name":"潜江市","coord":[112.70703817700621,30.349210666019893]},{"name":"仙桃市","coord":[113.34688900729822,30.315951161935402]},{"name":"萍乡市","coord":[113.88072263074415,27.47193090553213]},{"name":"台湾省","coord":[120.14338943402045,23.596002465926095]},{"name":"东莞市","coord":[113.89443658529342,22.897826158636448]},{"name":"中山市","coord":[113.37118387764659,22.501478858616522]},{"name":"珠海市","coord":[113.21799258934986,22.23782602992192]},{"name":"北海市","coord":[109.18248083043899,21.695773689750148]},{"name":"香港","coord":[114.20689279508653,22.36016760139811]},{"name":"舟山市","coord":[122.22514712841459,30.338633120695956]},{"name":"克孜勒苏柯尔克孜","coord":[74.62910472637343,39.59886016069875]},{"name":"喀什地区","coord":[77.19899922143753,37.85462871211595]},{"name":"阿克苏地区","coord":[81.43930290016381,41.067304799230456]},{"name":"和田地区","coord":[80.69780509160952,36.95287032287055]},{"name":"阿里地区","coord":[82.536487505389,32.69566569631762]},{"name":"日喀则地区","coord":[86.5996831353606,29.54861754814263]},{"name":"那曲地区","coord":[88.32523292667608,33.20600450932715]},{"name":"玉树藏族自治州","coord":[95.2107128446203,33.90320387919257]},{"name":"迪庆藏族自治州","coord":[99.42465312188943,28.052797714348895]},{"name":"怒江傈傈族自治州","coord":[98.85737910439825,26.98345757528851]},{"name":"大理白族自治州","coord":[99.93934374816013,25.684737357453045]},{"name":"德宏傣族景颇族自","coord":[98.13830877778075,24.593421919561205]},{"name":"保山市","coord":[99.19031013453166,24.979380341662]},{"name":"临沧市","coord":[99.62483778975081,24.058807858948214]},{"name":"普洱市","coord":[100.94440267992684,23.44121660743221]},{"name":"西双版纳傣族自治","coord":[100.86105801845994,21.882475641324206]},{"name":"拉萨市","coord":[91.3684790613129,30.14176592960237]},{"name":"山南地区","coord":[92.11665242621062,28.33000201578789]},{"name":"林芝地区","coord":[94.9307847458166,29.125110156601963]},{"name":"昌都地区","coord":[97.33912235873476,30.48520825551814]},{"name":"丽江市","coord":[100.65713436205135,26.96190318191959]},{"name":"攀枝花市","coord":[101.73355913301131,26.714486678752795]},{"name":"凉山彝族自治州","coord":[102.08678551422615,27.683020519860396]},{"name":"楚雄彝族自治州","coord":[101.68264761198458,25.369603845264024]},{"name":"红河哈尼族彝族自","coord":[102.95101719613119,23.624860095239875]},{"name":"文山壮族苗族自治","coord":[104.8708359910614,23.579587266862504]},{"name":"百色市","coord":[106.69546907589859,23.98220841166522]},{"name":"崇左市","coord":[107.3277087317123,22.49769755349952]},{"name":"防城港市","coord":[107.88939931155171,21.94550204069006]},{"name":"南宁市","coord":[108.67078983716917,23.12207641861882]},{"name":"钦州市","coord":[108.8532307305186,22.157690108421384]},{"name":"玉林市","coord":[110.26918466489103,22.391823643610415]},{"name":"湛江市","coord":[109.93033457863683,21.086751055633457]},{"name":"茂名市","coord":[110.80336192333934,22.069184739040775]},{"name":"阳江市","coord":[111.70471342186183,22.108751366417575]},{"name":"江门市","coord":[112.53715618649149,22.297368082806777]},{"name":"广州市","coord":[113.4949302208309,23.28359314707863]},{"name":"清远市","coord":[113.10957368131268,24.334444053233856]},{"name":"肇庆市","coord":[112.11117530204233,23.60241158796112]},{"name":"梧州市","coord":[111.01709510772797,23.518132876753846]},{"name":"贺州市","coord":[111.50423061842756,24.4095096817199]},{"name":"桂林市","coord":[110.44046163393094,25.353966673735407]},{"name":"柳州市","coord":[109.34854449214147,24.972408051485047]},{"name":"河池市","coord":[107.81191841865586,24.649291651298164]},{"name":"黔东南苗族侗族自","coord":[108.39952601614591,26.429286420465576]},{"name":"贵阳市","coord":[106.59784062851153,26.797907456479816]},{"name":"安顺市","coord":[105.76161265300635,25.988644902171018]},{"name":"黔西南布依族苗族","coord":[105.5954078788574,25.404850939549405]},{"name":"曲靖市","coord":[103.9164335632742,25.697243690315265]},{"name":"六盘水市","coord":[104.77723228072432,26.15402255629164]},{"name":"毕节地区","coord":[105.03867422931839,27.077913968069666]},{"name":"昭通市","coord":[104.29730513046874,27.62418247971078]},{"name":"宜宾市","coord":[104.76748901448207,28.553501804266475]},{"name":"乐山市","coord":[103.56027669102787,29.160754519210577]},{"name":"自贡市","coord":[104.63272827056402,29.273152614922402]},{"name":"内江市","coord":[104.82644562304716,29.61272653799929]},{"name":"遵义市","coord":[106.82413636302059,28.191847588570702]},{"name":"达州市","coord":[107.59704170009518,31.32138258839703]},{"name":"遂宁市","coord":[105.48979445433736,30.677687821242678]},{"name":"广安市","coord":[106.56708164098042,30.43500706741521]},{"name":"泸州市","coord":[105.42591761727707,28.50277238478137]},{"name":"资阳市","coord":[104.97995126874034,30.154251886139654]},{"name":"雅安市","coord":[102.69931299964517,29.892630706195035]},{"name":"眉山市","coord":[104.07052881858888,29.894202166560405]},{"name":"甘孜藏族自治州","coord":[100.50721042614238,30.975216556269658]},{"name":"果洛藏族自治州","coord":[99.30775565051923,34.03539865224808]},{"name":"海南藏族自治州","coord":[100.39969108016373,35.90048272566899]},{"name":"黄南藏族自治州","coord":[101.5360706381689,35.10286360841902]},{"name":"赣南藏族自治州","coord":[102.97083885806067,34.326752803339026]},{"name":"陇南市","coord":[105.24780098912132,33.57031117443431]},{"name":"天水市","coord":[105.53503634660417,34.62320421368087]},{"name":"定西市","coord":[104.58787768541339,35.08900966621695]},{"name":"临夏回族自治州","coord":[103.2612870434902,35.591577124455235]},{"name":"西宁市","coord":[101.57680657999033,36.84800271717157]},{"name":"海东地区","coord":[102.30909850729282,36.287400615025646]},{"name":"海北藏族自治州","coord":[100.27122484450717,37.892557516083826]},{"name":"金昌市","coord":[102.02244049169511,38.497330414886164]},{"name":"酒泉市","coord":[95.94486678270127,40.56891536586272]},{"name":"海西蒙古族藏族自","coord":[94.67143298050689,36.022725148503724]},{"name":"巴音郭楞蒙古自治","coord":[88.18116214759745,39.556478810319916]},{"name":"哈密地区","coord":[93.84302392518026,42.95015211178875]},{"name":"叶鲁番地区","coord":[89.82035217277885,42.399368632283505]},{"name":"乌鲁木齐市","coord":[88.00048109561487,43.549986370786]},{"name":"阿勒泰地区","coord":[88.11213933257655,47.05593413019629]},{"name":"博尔塔拉蒙古自治","coord":[82.26402238163408,44.671135542630864]},{"name":"伊犁哈萨克自治州","coord":[82.80778717477179,43.53783381365267]},{"name":"阿拉善盟","coord":[103.29923966842289,40.10955801781495]},{"name":"武威市","coord":[102.73362058791429,37.94211141321436]},{"name":"兰州市","coord":[103.73793563506032,36.27379827886003]},{"name":"中卫市","coord":[105.6943786030716,37.20654236148948]},{"name":"银川市","coord":[106.20022174140034,38.52103167597483]},{"name":"石嘴山市","coord":[106.41544011793628,38.84054137571417]},{"name":"乌海市","coord":[106.8984175998405,39.54616572239788]},{"name":"鄂尔多斯市","coord":[108.43285571424619,39.24036799350715]},{"name":"巴彦淖尔市","coord":[107.45840392808307,41.30159860424196]},{"name":"包头市","coord":[110.46472193224272,41.48017783644221]},{"name":"呼和浩特市","coord":[111.48365173603975,40.498363056149884]},{"name":"乌兰察布市","coord":[112.61568977597707,41.75789561273154]},{"name":"大同市","coord":[113.7107192749083,39.898956799744184]},{"name":"朔州市","coord":[112.65428748167508,39.681772914701924]},{"name":"忻州市","coord":[112.36127575589583,38.88990233614568]},{"name":"榆林市","coord":[109.68473112169593,38.19921027134876]},{"name":"延安市","coord":[109.52425222161318,36.406522726136814]},{"name":"庆阳市","coord":[107.73052193155061,36.183821532624464]},{"name":"固原市","coord":[106.20191575442442,36.11634909496382]},{"name":"白银市","coord":[104.68634478137065,36.51582865625868]},{"name":"宝鸡市","coord":[107.33534779230747,34.3387216485855]},{"name":"汉中市","coord":[107.03534754266246,33.00142998064871]},{"name":"广元市","coord":[105.92928137563939,32.21872447205537]},{"name":"巴中市","coord":[107.03422410306194,31.99874720836291]},{"name":"南充市","coord":[106.32964805032347,31.156657700184095]},{"name":"绵阳市","coord":[104.58949560201106,31.88628780630976]},{"name":"德阳市","coord":[104.41542984932845,31.110558133718676]},{"name":"成都市","coord":[103.8852290010473,30.777258040348634]},{"name":"阿坝藏族羌族自治","coord":[102.26209319552814,32.45725845387284]},{"name":"安康市","coord":[109.14236501848015,32.77467694678074]},{"name":"十堰市","coord":[110.39934083416314,32.376209039347906]},{"name":"襄阳市","coord":[111.97539147094662,31.93399822417465]},{"name":"宜昌市","coord":[111.22204852395754,30.772457669035354]},{"name":"恩施市","coord":[109.42158366502872,30.260366574390105]},{"name":"张家界市","coord":[110.59760006538717,29.330107409240718]},{"name":"吉首市","coord":[109.72176899848378,28.681903937242495]},{"name":"铜仁地区","coord":[108.54247523485463,28.11736237519646]},{"name":"重庆市","coord":[107.86007108564992,30.186253395053196]},{"name":"怀化市","coord":[109.94325166787243,27.43919084801186]},{"name":"益阳市","coord":[112.43060358108062,28.75127294553697]},{"name":"娄底市","coord":[111.41891416951897,27.696312460064604]},{"name":"常德市","coord":[111.72571610131646,29.27189463838195]},{"name":"荆州市","coord":[112.65896596965268,30.05161542755362]},{"name":"荆门市","coord":[112.6586855902184,31.01267124474617]},{"name":"岳阳市","coord":[113.2595036144316,29.106247116930163]},{"name":"长沙市","coord":[113.15415586456598,28.222934680488425]},{"name":"湘潭市","coord":[112.51092596317824,27.69881544105668]},{"name":"株州市","coord":[113.49665538546823,27.03993794610501]},{"name":"衡阳市","coord":[112.48849636578527,26.783613569970782]},{"name":"邵阳市","coord":[110.6723832117475,26.81652287086792]},{"name":"永州市","coord":[111.8565364154186,25.768488267811968]},{"name":"韶关市","coord":[113.53420325850979,24.69848878771937]},{"name":"惠州市","coord":[114.32029589634925,23.25504544231892]},{"name":"佛山市","coord":[112.95925897403649,23.10116677189257]},{"name":"云浮市","coord":[111.78042514904234,22.840400494105687]},{"name":"深圳市","coord":[114.13138648919008,22.649563063468342]},{"name":"汕尾市","coord":[115.57412892884373,23.06989642104901]},{"name":"河源市","coord":[114.89746229844398,23.97971937124767]},{"name":"揭阳市","coord":[116.04290004239446,23.304802704715357]},{"name":"汕头市","coord":[116.7008461897183,23.35898625947344]},{"name":"潮州市","coord":[116.75405548481658,23.854381508863064]},{"name":"梅州市","coord":[116.13719397345734,24.15633544812716]},{"name":"漳州市","coord":[117.38279760543345,24.41111215459575]},{"name":"厦门市","coord":[118.04275971554665,24.675908246507944]},{"name":"龙岩市","coord":[116.69341144552507,25.20284542644492]},{"name":"泉州市","coord":[118.12035864630246,25.22984144365049]},{"name":"莆田市","coord":[118.82439690138142,25.439653480972687]},{"name":"福州市","coord":[119.1608285845262,25.99117532466728]},{"name":"三明市","coord":[117.51188176216434,26.318292906961602]},{"name":"南平市","coord":[118.16153136678187,27.306303151805437]},{"name":"抚州市","coord":[116.3455359885574,27.487043655935366]},{"name":"鹰潭市","coord":[117.01082360702333,28.241253742969946]},{"name":"吉安市","coord":[114.91377151807418,26.957486660664525]},{"name":"赣州市","coord":[115.046455717572,25.81565075681663]},{"name":"郴州市","coord":[113.1544526703492,25.871927095452524]},{"name":"新余市","coord":[114.94161795877827,27.79044654578371]},{"name":"宜春市","coord":[115.04574494880995,28.306428044943356]},{"name":"南昌市","coord":[115.9963824234495,28.664803351584705]},{"name":"九江市","coord":[115.53225905704193,29.362905920276297]},{"name":"上饶市","coord":[117.8595355766598,28.765755150094634]},{"name":"景德镇市","coord":[117.25387030721845,29.33426823662448]},{"name":"黄山市","coord":[117.85476357809696,29.969632034273722]},{"name":"池州市","coord":[117.34517113140791,30.208089337922335]},{"name":"铜陵市","coord":[117.93160431300694,30.926442655001676]},{"name":"安庆市","coord":[116.54307680610799,30.524265461641296]},{"name":"黄石市","coord":[115.02354597728443,29.924060229331015]},{"name":"咸宁市","coord":[114.26967602231792,29.652174021136048]},{"name":"黄冈市","coord":[115.2859016705373,30.65856897065683]},{"name":"武汉市","coord":[114.34552076948799,30.68836237966767]},{"name":"随州市","coord":[113.3850627838818,31.87891659924412]},{"name":"信阳市","coord":[114.81374730587638,32.0309685135914]},{"name":"驻马店市","coord":[114.07756451509235,32.896720987266114]},{"name":"商洛市","coord":[109.82044421310393,33.77403373563189]},{"name":"西安市","coord":[109.11839808451401,34.225257215515896]},{"name":"渭南市","coord":[109.75732444226935,35.025913644359306]},{"name":"铜川市","coord":[108.98695328111377,35.19235092947735]},{"name":"咸阳市","coord":[108.36398776446165,34.84311348287181]},{"name":"三门峡市","coord":[110.80049688104964,34.31818709571671]},{"name":"运城市","coord":[111.1736679525165,35.19010372283576]},{"name":"洛阳市","coord":[111.87577573098216,34.33379926109848]},{"name":"平顶山市","coord":[112.80931281928427,33.759895800153096]},{"name":"漯河市","coord":[113.83505724178012,33.70034266174508]},{"name":"许昌市","coord":[113.78762484088509,34.051835688452435]},{"name":"郑州市","coord":[113.49619951867594,34.61181797865449]},{"name":"焦作市","coord":[113.13404280173008,35.134167097471625]},{"name":"晋城市","coord":[112.7495732073233,35.63186423091449]},{"name":"长治市","coord":[112.85900842873183,36.45872910742828]},{"name":"临汾市","coord":[111.49379787924448,36.22810800777857]},{"name":"太原市","coord":[112.15628804033796,37.91704444063036]},{"name":"吕梁市","coord":[111.31901105774872,37.712740463356496]},{"name":"晋中市","coord":[113.08199599739676,37.36532613794343]},{"name":"邯郸市","coord":[114.41824047234618,36.530119932543315]},{"name":"安阳市","coord":[113.88883283163116,35.7797611183252]},{"name":"鹤壁市","coord":[114.3654094911545,35.75770487428472]},{"name":"新乡市","coord":[113.9184107718167,35.348471214026716]},{"name":"开封市","coord":[114.52801677500626,34.61371216679872]},{"name":"周口市","coord":[114.88509782391864,33.69999759722657]},{"name":"阜阳市","coord":[115.44595951398213,32.98060371610532]},{"name":"淮南市","coord":[116.68941991880993,32.79972275772595]},{"name":"蚌埠市","coord":[117.38594715783302,33.106729536033896]},{"name":"淮北市","coord":[116.69651711889378,33.69527529383458]},{"name":"宿州市","coord":[117.30175405886838,33.943330421260015]},{"name":"亳州市","coord":[116.12410804185097,33.46769392946132]},{"name":"商丘市","coord":[115.59575176872548,34.28339840831147]},{"name":"菏泽市","coord":[115.53631974831816,35.197319393220624]},{"name":"濮阳市","coord":[115.3070485514902,35.775883510964334]},{"name":"聊城市","coord":[115.8870069012884,36.40529594548765]},{"name":"邢台市","coord":[114.74259008644859,37.251396750084155]},{"name":"石家庄市","coord":[114.56923838363613,38.13141710980106]},{"name":"阳泉市","coord":[113.39216149668508,38.09075470547468]},{"name":"保定市","coord":[115.261524468934,39.09118520781398]},{"name":"衡水市","coord":[115.8182936677897,37.715661598187154]},{"name":"德州市","coord":[116.4582273790399,37.19372347888644]},{"name":"沧州市","coord":[116.76192710911863,38.20240042039232]},{"name":"廊坊市","coord":[116.50410772133856,39.27896741763884]},{"name":"天津市","coord":[117.31988934444873,39.37154482470619]},{"name":"北京市","coord":[116.59734730757869,40.237112944270976]},{"name":"张家口市","coord":[115.1823606483226,40.83732566607167]},{"name":"唐山市","coord":[117.8693184261954,39.71862889477249]},{"name":"秦皇岛市","coord":[119.30467355367742,39.990574652162564]},{"name":"承德市","coord":[117.16275671911026,41.36623845548547]},{"name":"葫芦岛市","coord":[119.9342336210531,40.5628822626519]},{"name":"朝阳市","coord":[120.11853493535794,41.471852354885755]},{"name":"赤峰市","coord":[118.50943546234379,43.25452976059767]},{"name":"锦州市","coord":[121.5167549323861,41.45933087433065]},{"name":"营口市","coord":[122.58571915054674,40.42093503997384]},{"name":"丹东市","coord":[124.33549382902183,40.46369290272115]},{"name":"辽阳市","coord":[123.34064798039414,41.152331397771356]},{"name":"盘锦市","coord":[122.06718005354679,41.05573599862555]},{"name":"阜新市","coord":[121.93889757908204,42.27641773244204]},{"name":"鞍山市","coord":[122.78904432242356,40.77781183142038]},{"name":"沈阳市","coord":[122.99508899709724,42.1162195010079]},{"name":"铁岭市","coord":[124.23100515588399,42.72666083611828]},{"name":"扶顺市","coord":[124.46027188217573,41.82955407638859]},{"name":"通辽市","coord":[122.0729370657937,43.90889130864869]},{"name":"兴安盟","coord":[120.79456431092532,45.92003249442161]},{"name":"白城市","coord":[123.10619907715235,45.25475749267784]},{"name":"齐齐哈尔市","coord":[124.5462214659102,47.55395009317394]},{"name":"大兴安岭地区","coord":[124.50992855161529,52.18438447846694]},{"name":"黑河市","coord":[127.14721400335922,49.25080134026901]},{"name":"大庆市","coord":[124.40329830095243,46.401048760966745]},{"name":"绥化市","coord":[126.5214484055605,46.76992452194825]},{"name":"松原市","coord":[124.21244334807682,44.75779381338502]},{"name":"四平市","coord":[124.27839350328821,43.52139065090318]},{"name":"通化市","coord":[125.67392830706305,41.91771808663852]},{"name":"辽源市","coord":[125.33529527643432,42.758340204944986]},{"name":"吉林市","coord":[126.83350281902375,43.60730120049175]},{"name":"长春市","coord":[125.53597875970374,44.24624314701737]},{"name":"白山市","coord":[127.16780160322108,42.093893880305075]},{"name":"哈尔滨市","coord":[127.39125008786029,45.36200668820575]},{"name":"鹤岗市","coord":[130.4703811258197,47.66520688940109]},{"name":"伊春市","coord":[128.91240831703635,47.93833794565277]},{"name":"七台河市","coord":[131.2677920224311,45.945099776108584]},{"name":"鸡西市","coord":[132.38059153660274,45.722934218318535]},{"name":"双鸭山市","coord":[132.3184817002743,46.65813679030265]},{"name":"佳木斯市","coord":[132.26174446608726,47.17569713691394]},{"name":"呼伦贝尔市","coord":[122.3210739998419,50.18176996070858]},{"name":"孝感市","coord":[113.83749892135485,31.11757234692128]},{"name":"贵港市","coord":[110.07354588052804,23.380735604767374]},{"name":"黔南布依族苗族自","coord":[107.30931767543106,26.2976919432269]},{"name":"宁德市","coord":[119.52482556634342,27.013151692716413]},{"name":"温州市","coord":[120.30037042732202,27.8699145504001]},{"name":"台州市","coord":[120.88886782713843,28.670799172772313]},{"name":"丽水市","coord":[119.56796851966463,28.170268394477755]},{"name":"衢州市","coord":[118.79479802644406,28.865874397158763]},{"name":"金华市","coord":[119.99381920686633,29.093455548185744]},{"name":"绍兴市","coord":[120.46546691682343,29.69382513836818]},{"name":"宁波市","coord":[121.42142987830871,29.70001162878972]},{"name":"杭州市","coord":[119.4405685790891,29.87218307296989]},{"name":"宣城市","coord":[118.68748382914703,30.628143499626418]},{"name":"湖州市","coord":[119.98261306633574,30.7945175862809]},{"name":"嘉兴市","coord":[120.83889215988998,30.67538495499343]},{"name":"上海市","coord":[121.37534147322967,31.25628247908459]},{"name":"苏州市","coord":[120.6906182622391,31.381280695137775]},{"name":"无锡市","coord":[120.32182300914366,31.54113306724517]},{"name":"常州市","coord":[119.61953292830165,31.611878565375576]},{"name":"南京市","coord":[118.71890548838064,31.910863187910323]},{"name":"镇江市","coord":[119.42349332902813,31.97942313430778]},{"name":"合肥市","coord":[117.30651975617157,31.79407863049138]},{"name":"六安市","coord":[116.24668220575353,31.820846193819513]},{"name":"滁州市","coord":[117.88422385307969,32.51792621904418]},{"name":"泰州市","coord":[120.03124303305091,32.56503102346783]},{"name":"南通市","coord":[120.85599446760912,32.18496706099728]},{"name":"盐城市","coord":[120.01812490612667,33.54219948734023]},{"name":"淮安市","coord":[119.0749424205415,33.39203631772854]},{"name":"宿迁市","coord":[118.45404943216346,33.666258719120265]},{"name":"徐州市","coord":[117.77482249295966,34.30847766157078]},{"name":"济宁市","coord":[116.74147276546373,35.27488504351119]},{"name":"枣庄市","coord":[117.43359942491492,34.884162021736]},{"name":"连云港市","coord":[119.01553213785074,34.54316517587849]},{"name":"临沂市","coord":[118.31478835349617,35.28173079028279]},{"name":"日照市","coord":[119.14265350444272,35.54479073199592]},{"name":"青岛市","coord":[120.27779044405756,36.3464117375903]},{"name":"威海市","coord":[122.12963327195605,37.13879077904251]},{"name":"烟台市","coord":[120.7689567423966,37.19772002195597]},{"name":"潍坊市","coord":[119.02178548592039,36.49292234053931]},{"name":"淄博市","coord":[117.92936024367185,36.60871347163638]},{"name":"泰安市","coord":[116.93810893944303,36.0423330118612]},{"name":"济南市","coord":[117.34560282551296,36.769574973846304]},{"name":"东营市","coord":[118.4915054457184,37.52194690335787]},{"name":"滨州市","coord":[117.67610299757533,37.4439597758601]},{"name":"昆明市","coord":[102.93100245594789,25.481300763922075]},{"name":"玉溪市","coord":[102.23080854291823,24.156168324611663]},{"name":"塔城地区","coord":[83.60908162840168,45.3721852373893]},{"name":"张掖市","coord":[100.47710030600572,38.704239320458385]},{"name":"南阳市","coord":[112.1400670951149,33.03033276715801]},{"name":"扬州市","coord":[119.48949608990988,32.80956776339646]},{"name":"延边朝鲜族自治州","coord":[129.3577692895626,43.24968794080283]},{"name":"牡丹江市","coord":[129.87240796405672,44.7073040108322]},{"name":"澳门","coord":[113.56289691515346,22.14602596262204]},{"name":"吴忠市","coord":[106.76894508116403,37.72566765880316]},{"name":"来宾市","coord":[109.25592217010114,23.86346274681084]},{"name":"平凉市","coord":[107.0708132782897,35.30329631658711]},{"name":"马鞍山市","coord":[118.27245878467022,31.657727937739004]},{"name":"芜湖市","coord":[118.32992684415504,31.081688223101658]},{"name":"澄迈县","coord":[110.04198076060266,19.694955078668105]},{"name":"保亭黎族苗族自治","coord":[109.6055304964257,18.6101488675304]},{"name":"乐东黎族自治县","coord":[109.04051999525574,18.643137437909203]},{"name":"儋州市","coord":[109.3431358337404,19.550974957403195]},{"name":"定安县","coord":[110.38744429685676,19.47557074114284]},{"name":"屯昌县","coord":[110.00574767630334,19.367175093044388]},{"name":"白沙黎族自治县","coord":[109.36860737761768,19.214416393082217]},{"name":"琼中黎族苗族自治","coord":[109.86691465937548,19.073671135862682]},{"name":"东方市","coord":[108.86903802405428,19.017352815445214]},{"name":"昌江黎族自治县","coord":[108.9686431884767,19.182594167127824]},{"name":"海口市","coord":[110.420654296875,19.806565564640795]},{"name":"济源市","coord":[112.38051465474433,35.07958362422394]},{"name":"五指山市","coord":[109.53595187364496,18.832908264613966]},{"name":"大连市","coord":[121.96662235866603,39.444150542439914]},{"name":"文昌市三沙市","coord":[110.81828537536748,19.756501444162936]},{"name":"三亚市","coord":[109.38424600793707,18.39186315877128]},{"name":"万宁市","coord":[110.28485046979574,18.860240588635115]},{"name":"陵水黎族自治县","coord":[109.95577603229562,18.594712684620465]},{"name":"临高县","coord":[109.71915395436967,19.79420403032508]},{"name":"琼海市","coord":[110.41650700703043,19.22315873149372]}]'); ;// CONCATENATED MODULE: ./src/openlayers/mapping/webmap/config/SampleDataInfo.json const SampleDataInfo_namespaceObject = JSON.parse('[{"id":"SalesJan2009","fileName":"SalesJan2009","xField":"Longitude","yField":"Latitude","type":"POINT"},{"id":"Sacramentorealestatetransactions","fileName":"Ealestate transactions","xField":"longitude","yField":"latitude","type":"POINT"},{"id":"BeijingResidentialDistrict","fileName":"北京市住宅小区","xField":"SmX","yField":"SmY","type":"POINT"},{"id":"GlobalRecordOfOver7Earthquakes","fileName":"全球历史7级以上地震记录","xField":"经度","yField":"纬度","type":"POINT"},{"id":"ChinaRecordOfOver6Earthquakes","fileName":"中国历史6级以上地震记录","xField":"经度","yField":"纬度","type":"POINT"},{"id":"ChinaMeteorologicalObservationStation","fileName":"中国气象观测站","xField":"经度","yField":"纬度","type":"POINT"},{"id":"BeijingSubwayLine","fileName":"北京市地铁交通线路","type":"LINE"},{"id":"ChinaEarthquakeIntensityZone","fileName":"中国地震烈度区划面","type":"POLYGON"}]'); ;// CONCATENATED MODULE: external "ol.View" const external_ol_View_namespaceObject = ol.View; var external_ol_View_default = /*#__PURE__*/__webpack_require__.n(external_ol_View_namespaceObject); ;// CONCATENATED MODULE: external "ol.interaction.MouseWheelZoom" const external_ol_interaction_MouseWheelZoom_namespaceObject = ol.interaction.MouseWheelZoom; var external_ol_interaction_MouseWheelZoom_default = /*#__PURE__*/__webpack_require__.n(external_ol_interaction_MouseWheelZoom_namespaceObject); ;// CONCATENATED MODULE: external "ol.proj.proj4" const external_ol_proj_proj4_namespaceObject = ol.proj.proj4; ;// CONCATENATED MODULE: external "ol.proj.Units" const external_ol_proj_Units_namespaceObject = ol.proj.Units; var external_ol_proj_Units_default = /*#__PURE__*/__webpack_require__.n(external_ol_proj_Units_namespaceObject); ;// CONCATENATED MODULE: external "ol.layer" const external_ol_layer_namespaceObject = ol.layer; ;// CONCATENATED MODULE: external "ol.format.WMTSCapabilities" const external_ol_format_WMTSCapabilities_namespaceObject = ol.format.WMTSCapabilities; var external_ol_format_WMTSCapabilities_default = /*#__PURE__*/__webpack_require__.n(external_ol_format_WMTSCapabilities_namespaceObject); ;// CONCATENATED MODULE: external "ol.format.WMSCapabilities" const external_ol_format_WMSCapabilities_namespaceObject = ol.format.WMSCapabilities; var external_ol_format_WMSCapabilities_default = /*#__PURE__*/__webpack_require__.n(external_ol_format_WMSCapabilities_namespaceObject); ;// CONCATENATED MODULE: external "ol.geom" const external_ol_geom_namespaceObject = ol.geom; ;// CONCATENATED MODULE: external "ol.source.TileWMS" const external_ol_source_TileWMS_namespaceObject = ol.source.TileWMS; var external_ol_source_TileWMS_default = /*#__PURE__*/__webpack_require__.n(external_ol_source_TileWMS_namespaceObject); ;// CONCATENATED MODULE: external "ol.render.Feature" const external_ol_render_Feature_namespaceObject = ol.render.Feature; var external_ol_render_Feature_default = /*#__PURE__*/__webpack_require__.n(external_ol_render_Feature_namespaceObject); ;// CONCATENATED MODULE: external "ol.Collection" const external_ol_Collection_namespaceObject = ol.Collection; var external_ol_Collection_default = /*#__PURE__*/__webpack_require__.n(external_ol_Collection_namespaceObject); // EXTERNAL MODULE: ./node_modules/lodash.difference/index.js var lodash_difference = __webpack_require__(478); var lodash_difference_default = /*#__PURE__*/__webpack_require__.n(lodash_difference); ;// CONCATENATED MODULE: ./src/openlayers/mapping/WebMap.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ // eslint-disable-line import/extensions // eslint-disable-line import/extensions // eslint-disable-line import/extensions window.proj4 = (proj4_src_default()); window.Proj4js = (proj4_src_default()); //数据转换工具 const transformTools = new (external_ol_format_GeoJSON_default())(); // 迁徙图最大支持要素数量 const MAX_MIGRATION_ANIMATION_COUNT = 1000; //不同坐标系单位。计算公式中的值 const metersPerUnit = { DEGREES: 2 * Math.PI * 6370997 / 360, DEGREE: 2 * Math.PI * 6370997 / 360, FEET: 0.3048, METERS: 1, METER: 1, M: 1, USFEET: 1200 / 3937 }; const dpiConfig = { default: 96, // 常用dpi iServerWMTS: 90.7142857142857 // iserver使用的wmts图层dpi } /** * @class WebMap * @category iPortal/Online Resources Map * @classdesc 对接 iPortal/Online 地图类 * @param {Object} options - 参数 * @param {string} [options.target='map'] - 地图容器id * @param {Object | string} [options.webMap] - webMap对象,或者是获取webMap的url地址。存在webMap,优先使用webMap, id的选项则会被忽略 * @param {number} [options.id] - 地图的id * @param {string} [options.server] - 地图的地址,如果使用传入id,server则会和id拼接成webMap请求地址 * @param {function} [options.successCallback] - 成功加载地图后调用的函数 * @param {function} [options.errorCallback] - 加载地图失败调用的函数 * @param {string} [options.credentialKey] - 凭证密钥。例如为"key"、"token",或者用户自定义的密钥。用户申请了密钥,此参数必填 * @param {string} [options.credentialValue] - 凭证密钥对应的值,credentialKey和credentialValue必须一起使用 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie * @param {boolean} [options.excludePortalProxyUrl] - server传递过来的url是否带有代理 * @param {Object} [options.serviceProxy] - iportal内置代理信息, 仅矢量瓦片图层上图才会使用 * @param {string} [options.tiandituKey] - 天地图的key * @param {string} [options.googleMapsAPIKey] - 谷歌底图需要的key * @param {string} [options.proxy] - 代理地址,当域名不一致,请求会加上代理。避免跨域 * @param {string} [options.tileFormat] - 地图瓦片出图格式,png/webp * @param {Object} [options.mapSetting] - 地图可选参数 * @param {function} [options.mapSetting.mapClickCallback] - 地图被点击的回调函数 * @param {function} [options.mapSetting.overlays] - 地图的overlays * @param {function} [options.mapSetting.controls] - 地图的控件 * @param {function} [options.mapSetting.interactions] - 地图控制的参数 * @param {number} [options.restDataSingleRequestCount=1000] - 自定义restData分批请求,单次请求数量 * @extends {ol.Observable} * @usage */ class WebMap extends (external_ol_Observable_default()) { constructor(id, options) { super(); if (core_Util_Util.isObject(id)) { options = id; this.mapId = options.id; } else { this.mapId = id; } options = options || {}; this.server = options.server; this.successCallback = options.successCallback; this.errorCallback = options.errorCallback; this.credentialKey = options.credentialKey; this.credentialValue = options.credentialValue; this.withCredentials = options.withCredentials || false; this.target = options.target || "map"; this.excludePortalProxyUrl = options.excludePortalProxyUrl || false; this.serviceProxy = options.serviceProxy || null; this.tiandituKey = options.tiandituKey; this.googleMapsAPIKey = options.googleMapsAPIKey || ''; this.proxy = options.proxy; //计数叠加图层,处理过的数量(成功和失败都会计数) this.layerAdded = 0; this.layers = []; this.events = new Events(this, null, ["updateDataflowFeature"], true); this.webMap = options.webMap; this.tileFormat = options.tileFormat && options.tileFormat.toLowerCase(); this.restDataSingleRequestCount = options.restDataSingleRequestCount || 1000; this.createMap(options.mapSetting); if (this.webMap) { // webmap有可能是url地址,有可能是webmap对象 core_Util_Util.isString(this.webMap) ? this.createWebmap(this.webMap) : this.getMapInfoSuccess(options.webMap); } else { this.createWebmap(); } } /** * @private * @function WebMap.prototype._removeBaseLayer * @description 移除底图 */ _removeBaseLayer() { const map = this.map; const {layer, labelLayer} = this.baseLayer; // 移除天地图标签图层 labelLayer && map.removeLayer(labelLayer); // 移除图层 layer && map.removeLayer(layer); this.baseLayer = null; } /** * @private * @function WebMap.prototype._removeLayers * @description 移除叠加图层 */ _removeLayers() { const map = this.map; this.layers.forEach(({layerType, layer, labelLayer, pathLayer, dataflowService}) => { if (!layer) { return; } if (layerType === 'MIGRATION') { layer.remove(); return; } if (layerType === 'DATAFLOW_POINT_TRACK' || layerType === 'DATAFLOW_HEAT') { // 移除轨迹图层 pathLayer && map.removeLayer(pathLayer); // 取消订阅 dataflowService && dataflowService.unSubscribe(); } // 移除标签图层 labelLayer && map.removeLayer(labelLayer); // 移除图层 map.removeLayer(layer) }); this.layers = []; } /** * @private * @function WebMap.prototype.clear * @description 清空地图 */ _clear() { // 比例尺 this.scales = []; // 分辨率 this.resolutionArray = []; // 比例尺-分辨率 {scale: resolution} this.resolutions = {}; // 计数叠加图层,处理过的数量(成功和失败都会计数) this.layerAdded = 0; this._removeBaseLayer(); this._removeLayers(); } /** * @function WebMap.prototype.refresh * @version 10.1.0 * @description 重新渲染地图 */ refresh() { this._clear(); this.createWebmap(); } /** * @private * @function WebMap.prototype.createMap * @description 创建地图对象以及注册地图事件 * @param {Object} mapSetting - 关于地图的设置以及需要注册的事件 */ createMap(mapSetting) { let overlays, controls, interactions; if (mapSetting) { interactions = mapSetting.interactions; overlays = mapSetting.overlays; controls = mapSetting.controls; } this.map = new (external_ol_Map_default())({ interactions: interactions, overlays: overlays, controls: controls, target: this.target }); mapSetting && this.registerMapEvent({ mapClickCallback: mapSetting.mapClickCallback }); } /** * @private * @function WebMap.prototype.registerMapEvent * @description 注册地图事件 * @param {Object} mapSetting - 关于地图的设置以及需要注册的事件 */ registerMapEvent(mapSetting) { let map = this.map; map.on("click", function (evt) { mapSetting.mapClickCallback && mapSetting.mapClickCallback(evt); }); } /** * @private * @function WebMap.prototype.createWebmap * @description 创建webmap * @param {string} webMapUrl - 请求webMap的地址 */ createWebmap(webMapUrl) { let mapUrl; if (webMapUrl) { mapUrl = webMapUrl; } else { let urlArr = this.server.split(''); if (urlArr[urlArr.length - 1] !== '/') { this.server += '/'; } mapUrl = this.server + 'web/maps/' + this.mapId + '/map'; let filter = 'getUrlResource.json?url='; if (this.excludePortalProxyUrl && this.server.indexOf(filter) > -1) { //大屏需求,或者有加上代理的 let urlArray = this.server.split(filter); if (urlArray.length > 1) { mapUrl = urlArray[0] + filter + this.server + 'web/maps/' + this.mapId + '/map.json'; } } } this.getMapInfo(mapUrl); } /** * @private * @function WebMap.prototype.getMapInfo * @description 获取地图的json信息 * @param {string} url - 请求地图的url */ getMapInfo(url) { let that = this, mapUrl = url; if (url.indexOf('.json') === -1) { //传递过来的url,没有包括.json,在这里加上。 mapUrl = `${url}.json` } FetchRequest.get(that.getRequestUrl(mapUrl), null, { withCredentials: this.withCredentials }).then(function (response) { return response.json(); }).then(function (mapInfo) { that.getMapInfoSuccess(mapInfo); }).catch(function (error) { that.errorCallback && that.errorCallback(error, 'getMapFaild', that.map); }); } /** * @private * @function WebMap.prototype.getMapInfoSuccess * @description 获取地图的json信息 * @param {Object} mapInfo - webMap对象 */ async getMapInfoSuccess(mapInfo) { let that = this; if (mapInfo.succeed === false) { that.errorCallback && that.errorCallback(mapInfo.error, 'getMapFaild', that.map); return; } let handleResult = await that.handleCRS(mapInfo.projection, mapInfo.baseLayer.url); //存储地图的名称以及描述等信息,返回给用户 that.mapParams = { title: mapInfo.title, description: mapInfo.description }; if (handleResult.action === "BrowseMap") { that.createSpecLayer(mapInfo); } else if (handleResult.action === "OpenMap") { that.baseProjection = handleResult.newCrs || mapInfo.projection; that.webMapVersion = mapInfo.version; that.baseLayer = mapInfo.baseLayer; // that.mapParams = { // title: mapInfo.title, // description: mapInfo.description // }; //存储地图的名称以及描述等信息,返回给用户 that.isHaveGraticule = mapInfo.grid && mapInfo.grid.graticule; if (mapInfo.baseLayer && mapInfo.baseLayer.layerType === 'MAPBOXSTYLE') { // 添加矢量瓦片服务作为底图 that.addMVTMapLayer(mapInfo, mapInfo.baseLayer, 0).then(async () => { that.createView(mapInfo); if (!mapInfo.layers || mapInfo.layers.length === 0) { that.sendMapToUser(0); } else { await that.addLayers(mapInfo); } that.addGraticule(mapInfo); }).catch(function (error) { that.errorCallback && that.errorCallback(error, 'getMapFaild', that.map); }); } else { await that.addBaseMap(mapInfo); if (!mapInfo.layers || mapInfo.layers.length === 0) { that.sendMapToUser(0); } else { await that.addLayers(mapInfo); } that.addGraticule(mapInfo); } } else { // 不支持的坐标系 that.errorCallback && that.errorCallback({type: "Not support CS", errorMsg: `Not support CS: ${mapInfo.projection}`}, 'getMapFaild', that.map); return; } } /** * 处理坐标系(底图) * @private * @param {string} crs 必传参数,值是webmap2中定义的坐标系,可能是 1、EGSG:xxx 2、WKT string * @param {string} baseLayerUrl 可选参数,地图的服务地址;用于EPSG:-1 的时候,用于请求iServer提供的wkt * @return {Object} */ async handleCRS(crs, baseLayerUrl) { let that = this, handleResult = {}; let newCrs = crs, action = "OpenMap"; if (this.isCustomProjection(crs)) { // 去iServer请求wkt 否则只能预览出图 await FetchRequest.get(that.getRequestUrl(`${baseLayerUrl}/prjCoordSys.wkt`), null, { withCredentials: that.withCredentials, withoutFormatSuffix: true }).then(function (response) { return response.text(); }).then(async function (result) { if(result.indexOf("") === -1) { that.addProjctionFromWKT(result, crs); handleResult = {action, newCrs}; } else { throw 'ERROR'; } }).catch(function () { action = "BrowseMap"; handleResult = {action, newCrs} }); } else { if (crs.indexOf("EPSG") === 0 && crs.split(":")[1] <= 0) { // 自定义坐标系 rest map EPSG:-1(自定义坐标系) 支持编辑 // 未知坐标系情况特殊处理,只支持预览 1、rest map EPSG:-1000(没定义坐标系) 2、wms/wmts EPSG:0 (自定义坐标系) action = "BrowseMap"; } else if (crs === 'EPSG:910111' || crs === 'EPSG:910112') { // 早期数据存在的自定义坐标系 "EPSG:910111": "GCJ02MERCATOR", "EPSG:910112": "BDMERCATOR" newCrs = "EPSG:3857"; } else if (crs === 'EPSG:910101' || crs === 'EPSG:910102') { // 早期数据存在的自定义坐标系 "EPSG:910101": "GCJ02", "EPSG:910102": "BD", newCrs = "EPSG:4326"; } else if (crs.indexOf("EPSG") !== 0) { // wkt that.addProjctionFromWKT(newCrs); newCrs = that.getEpsgInfoFromWKT(crs); } handleResult = {action, newCrs}; } return handleResult; } /** * @private * @function WebMap.prototype.getScales * @description 根据级别获取每个级别对应的分辨率 * @param {Object} baseLayerInfo - 底图的图层信息 */ getScales(baseLayerInfo) { let scales = [], resolutions = {}, res, scale, resolutionArray = [], coordUnit = baseLayerInfo.coordUnit || external_ol_proj_namespaceObject.get(baseLayerInfo.projection).getUnits(); if (!coordUnit) { coordUnit = this.baseProjection == "EPSG:3857" ? "m" : "degree"; } if (baseLayerInfo.visibleScales && baseLayerInfo.visibleScales.length > 0) { //底部设置过固定比例尺,则使用设置的 baseLayerInfo.visibleScales.forEach(scale => { let value = 1 / scale; res = this.getResFromScale(value, coordUnit); scale = `1:${value}`; //多此一举转换,因为toLocalString会自动保留小数点后三位,and当第二位小数是0就会保存小数点后两位。所有为了统一。 resolutions[this.formatScale(scale)] = res; resolutionArray.push(res); scales.push(scale); }, this) } else if (baseLayerInfo.layerType === 'WMTS') { baseLayerInfo.scales.forEach(scale => { res = this.getResFromScale(scale, coordUnit, 90.7); scale = `1:${scale}`; //多此一举转换,因为toLocalString会自动保留小数点后三位,and当第二位小数是0就会保存小数点后两位。所有为了统一。 resolutions[this.formatScale(scale)] = res; resolutionArray.push(res); scales.push(scale); }, this) } else { let {minZoom = 0, maxZoom = 22} = baseLayerInfo, view = this.map.getView(); for (let i = minZoom; i <= maxZoom; i++) { res = view.getResolutionForZoom(i); scale = this.getScaleFromRes(res, coordUnit); if (scales.indexOf(scale) === -1) { //不添加重复的比例尺 scales.push(scale); let attr = scale.replace(/,/g, ""); resolutions[attr] = res; resolutionArray.push(res); } } } this.scales = scales; this.resolutions = resolutions; this.resolutionArray = resolutionArray; } /** * @private * @function WebMap.prototype.getResFromScale * @description 将比例尺转换为分辨率 * @param {number} scale - 比例尺 * @param {string} coordUnit - 比例尺单位 * @param {number} dpi */ getResFromScale(scale, coordUnit = "DEGREE", dpi = 96) { let mpu = metersPerUnit[coordUnit.toUpperCase()]; return scale * .0254 / dpi / mpu; } /** * @private * @function WebMap.prototype.getScaleFromRes * @description 将分辨率转换为比例尺 * @param {number} resolution - 分辨率 * @param {string} coordUnit - 比例尺单位 * @param {number} dpi */ getScaleFromRes(resolution, coordUnit = "DEGREE", dpi = 96) { let scale, mpu = metersPerUnit[coordUnit.toUpperCase()]; scale = resolution * dpi * mpu / .0254; return '1:' + scale; } /** * @private * @function WebMap.prototype.formatScale * @description 将有千位符的数字转为普通数字。例如:1,234 => 1234 * @param {number} scale - 比例尺分母 */ formatScale(scale) { return scale.replace(/,/g, ""); } /** * @private * @function WebMap.prototype.createSpecLayer * @description 创建坐标系为0和-1000的图层 * @param {Object} mapInfo - 地图信息 */ createSpecLayer(mapInfo) { let me = this, baseLayerInfo = mapInfo.baseLayer, url = baseLayerInfo.url, baseLayerType = baseLayerInfo.layerType; let extent = [mapInfo.extent.leftBottom.x, mapInfo.extent.leftBottom.y, mapInfo.extent.rightTop.x, mapInfo.extent.rightTop.y]; let proj = new external_ol_proj_namespaceObject.Projection({ extent, units: 'm', code: 'EPSG:0' }); external_ol_proj_namespaceObject.addProjection(proj); let options = { center: mapInfo.center, level: 0 } //添加view me.baseProjection = proj; let viewOptions = { center: options.center ? [options.center.x, options.center.y] : [0, 0], zoom: 0, projection: proj } if (['4', '5'].indexOf(core_Util_Util.getOlVersion()) < 0) { // 兼容 ol 4,5,6 viewOptions.multiWorld = true; } let view = new (external_ol_View_default())(viewOptions); me.map.setView(view); if (me.mapParams) { me.mapParams.extent = extent; me.mapParams.projection = mapInfo.projection; } if (url && url.indexOf("?token=") > -1) { //兼容iserver地址有token的情况 me.credentialKey = 'token'; me.credentialValue = mapInfo.baseLayer.credential = url.split("?token=")[1]; url = url.split("?token=")[0]; } let source; if (baseLayerType === "TILE") { FetchRequest.get(me.getRequestUrl(`${url}.json`), null, { withCredentials: this.withCredentials }).then(function (response) { return response.json(); }).then(function (result) { baseLayerInfo.originResult = result; let serverType = "IPORTAL", credential = baseLayerInfo.credential, keyfix = 'Token', keyParams = baseLayerInfo.url; if (baseLayerInfo.url.indexOf("www.supermapol.com") > -1 || baseLayerInfo.url.indexOf("itest.supermapol.com") > -1) { keyfix = 'Key'; keyParams = [keyParams]; serverType = "ONLINE"; } if (credential) { SecurityManager[`register${keyfix}`](keyParams, credential); } let options = { serverType, url, tileGrid: TileSuperMapRest.optionsFromMapJSON(url, result).tileGrid } if (url && !me.isSameDomain(url)) { options.tileProxy = me.server + 'apps/viewer/getUrlResource.png?url='; } source = new TileSuperMapRest(options); me.addSpecToMap(source); }).catch(function (error) { me.errorCallback && me.errorCallback(error, 'getMapFaild', me.map); }); } else if (baseLayerType === "WMS") { source = me.createWMSSource(baseLayerInfo); me.addSpecToMap(source); } else if (baseLayerType === "WMTS") { FetchRequest.get(me.getRequestUrl(url, true), null, { withCredentials: this.withCredentials }).then(function (response) { return response.text(); }).then(function (capabilitiesText) { baseLayerInfo.extent = [mapInfo.extent.leftBottom.x, mapInfo.extent.leftBottom.y, mapInfo.extent.rightTop.x, mapInfo.extent.rightTop.y]; baseLayerInfo.scales = me.getWMTSScales(baseLayerInfo.tileMatrixSet, capabilitiesText); baseLayerInfo.dpi = dpiConfig.iServerWMTS; source = me.createWMTSSource(baseLayerInfo); me.addSpecToMap(source); }).catch(function (error) { me.errorCallback && me.errorCallback(error, 'getMapFaild', me.map); }) } else { me.errorCallback && me.errorCallback({type: "Not support CS", errorMsg: `Not support CS: ${baseLayerType}`}, 'getMapFaild', me.map); } view && view.fit(extent); } /** * @private * @function WebMap.prototype.addSpecToMap * @description 将坐标系为0和-1000的图层添加到地图上 * @param {Object} mapInfo - 地图信息 */ addSpecToMap(source) { let layer = new external_ol_layer_namespaceObject.Tile({ source: source, zIndex: 0 }); this.map.addLayer(layer); this.sendMapToUser(0); } /** * @private * @function WebMap.prototype.getWMTSScales * @description 获取wmts的比例尺 * @param {Object} identifier - 图层存储的标识信息 * @param {Object} capabilitiesText - wmts信息 */ getWMTSScales(identifier, capabilitiesText) { const format = new (external_ol_format_WMTSCapabilities_default())(); let capabilities = format.read(capabilitiesText); let content = capabilities.Contents; let tileMatrixSet = content.TileMatrixSet; let scales = []; for (let i = 0; i < tileMatrixSet.length; i++) { if (tileMatrixSet[i].Identifier === identifier) { for (let h = 0; h < tileMatrixSet[i].TileMatrix.length; h++) { scales.push(tileMatrixSet[i].TileMatrix[h].ScaleDenominator) } break; } } return scales; } /** * @private * @function WebMap.prototype.addBaseMap * @description 添加底图 * @param {string} mapInfo - 请求地图的url */ async addBaseMap(mapInfo) { let {baseLayer} = mapInfo, layerType = baseLayer.layerType; //底图,使用默认的配置,不用存储的 if (layerType !== 'TILE' && layerType !== 'WMS' && layerType !== 'WMTS') { this.getInternetMapInfo(baseLayer); } else if (layerType === 'WMTS') { // 通过请求完善信息 await this.getWmtsInfo(baseLayer); } else if (layerType === 'TILE') { await this.getTileInfo(baseLayer); } else if(layerType === 'WMS') { await this.getWmsInfo(baseLayer); } baseLayer.projection = mapInfo.projection; if (!baseLayer.extent) { baseLayer.extent = [mapInfo.extent.leftBottom.x, mapInfo.extent.leftBottom.y, mapInfo.extent.rightTop.x, mapInfo.extent.rightTop.y]; } this.createView(mapInfo); let layer = this.createBaseLayer(baseLayer, 0, null, null, true); //底图增加图层类型,DV分享需要用它来识别版权信息 layer.setProperties({ layerType: layerType }); this.map.addLayer(layer); if (this.mapParams) { this.mapParams.extent = baseLayer.extent; this.mapParams.projection = mapInfo.projection; } if (baseLayer.labelLayerVisible) { //存在天地图路网 let labelLayer = new external_ol_layer_namespaceObject.Tile({ source: this.createTiandituSource(baseLayer.layerType, mapInfo.projection, true), zIndex: baseLayer.zIndex || 1, visible: baseLayer.visible }); this.map.addLayer(labelLayer); // 挂载带baseLayer上,便于删除 baseLayer.labelLayer = labelLayer; } this.limitScale(mapInfo, baseLayer); } validScale(scale) { if (!scale) { return false; } const scaleNum = scale.split(':')[1]; if (!scaleNum) { return false; } const res = 1 / +scaleNum; if (res === Infinity || res >= 1) { return false; } return true; } limitScale(mapInfo, baseLayer) { if (this.validScale(mapInfo.minScale) && this.validScale(mapInfo.maxScale)) { let visibleScales, minScale, maxScale; if (baseLayer.layerType === 'WMTS') { visibleScales = baseLayer.scales; minScale = +mapInfo.minScale.split(':')[1]; maxScale = +mapInfo.maxScale.split(':')[1]; } else { const scales = this.scales.map((scale) => { return 1 / scale.split(':')[1]; }); if (Array.isArray(baseLayer.visibleScales) && baseLayer.visibleScales.length && baseLayer.visibleScales) { visibleScales = baseLayer.visibleScales; } else { visibleScales = scales; } minScale = 1 / +mapInfo.minScale.split(':')[1]; maxScale = 1 / +mapInfo.maxScale.split(':')[1]; } const minVisibleScale = this.findNearest(visibleScales, minScale); const maxVisibleScale = this.findNearest(visibleScales, maxScale); let minZoom = visibleScales.indexOf(minVisibleScale); let maxZoom = visibleScales.indexOf(maxVisibleScale); if (minZoom > maxZoom) { [minZoom, maxZoom] = [maxZoom, minZoom]; } if (minZoom !== 0 || maxZoom !== visibleScales.length - 1) { this.map.setView( new (external_ol_View_default())( Object.assign({}, this.map.getView().options_, { maxResolution: undefined, minResolution: undefined, minZoom, maxZoom, constrainResolution: false }) ) ); this.map.addInteraction( new (external_ol_interaction_MouseWheelZoom_default())({ constrainResolution: true }) ); } } } parseNumber(scaleStr) { return Number(scaleStr.split(":")[1]) } findNearest(scales, target) { let resultIndex = 0 let targetScaleD = target; for (let i = 1, len = scales.length; i < len; i++) { if ( Math.abs(scales[i] - targetScaleD) < Math.abs(scales[resultIndex] - targetScaleD) ) { resultIndex = i } } return scales[resultIndex] } /** * @private * @function WebMap.prototype.addMVTMapLayer * @description 添加地图服务mapboxstyle图层 * @param {Object} mapInfo - 地图信息 * @param {Object} layerInfo - mapboxstyle图层信息 */ addMVTMapLayer(mapInfo, layerInfo, zIndex) { layerInfo.zIndex = zIndex; // 获取地图详细信息 return this.getMapboxStyleLayerInfo(mapInfo, layerInfo).then((msLayerInfo) => { // 创建图层 return this.createMVTLayer(msLayerInfo).then(layer => { let layerID = core_Util_Util.newGuid(8); if (layerInfo.name) { layer.setProperties({ name: layerInfo.name, layerID: layerID, layerType: 'VECTOR_TILE' }); } layerInfo.visibleScale && this.setVisibleScales(layer, layerInfo.visibleScale); //否则没有ID,对不上号 layerInfo.layer = layer; layerInfo.layerID = layerID; this.map.addLayer(layer); }); }).catch(function (error){ throw error; }); } /** * @private * @function WebMap.prototype.createView * @description 创建地图视图 * @param {Object} options - 关于地图的信息 */ createView(options) { let oldcenter = options.center, zoom = options.level !== undefined ? options.level : 1, maxZoom = options.maxZoom || 22, extent, projection = this.baseProjection; let center = []; for (let key in oldcenter) { center.push(oldcenter[key]); } if (center.length === 0) { //兼容wms center = [0, 0]; } //与DV一致用底图的默认范围,不用存储的范围。否则会导致地图拖不动 this.baseLayerExtent = extent = options.baseLayer && options.baseLayer.extent; if (this.mapParams) { this.mapParams.extent = extent; this.mapParams.projection = projection; } //当前中心点不在extent内,就用extent的中心点 todo !(0,external_ol_extent_namespaceObject.containsCoordinate)(extent, center) && (center = (0,external_ol_extent_namespaceObject.getCenter)(extent)); // 计算当前最大分辨率 let baseLayer = options.baseLayer; let maxResolution; if ((baseLayer.visibleScales && baseLayer.visibleScales.length > 0) || (baseLayer.scales && baseLayer.scales.length > 0)) { //底图有固定比例尺,就直接获取。不用view计算 this.getScales(baseLayer); } else if (options.baseLayer && extent && extent.length === 4) { let width = extent[2] - extent[0]; let height = extent[3] - extent[1]; let maxResolution1 = width / 512; let maxResolution2 = height / 512; maxResolution = Math.max(maxResolution1, maxResolution2); } // if(options.baseLayer.visibleScales && options.baseLayer.visibleScales.length > 0){ // maxZoom = options.baseLayer.visibleScales.length; // } this.map.setView(new (external_ol_View_default())({ zoom, center, projection, maxZoom, maxResolution })); let viewOptions = {}; if (baseLayer.scales && baseLayer.scales.length > 0 && baseLayer.layerType === "WMTS" || this.resolutionArray && this.resolutionArray.length > 0) { viewOptions = { zoom, center, projection, resolutions: this.resolutionArray, maxZoom }; } else if (baseLayer.layerType === "WMTS") { viewOptions = { zoom, center, projection, maxZoom }; this.getScales(baseLayer); } else { viewOptions = { zoom, center, projection, maxResolution, maxZoom }; this.getScales(baseLayer); } if (['4', '5'].indexOf(core_Util_Util.getOlVersion()) < 0) { // 兼容 ol 4,5,6 viewOptions.multiWorld = true; viewOptions.showFullExtent = true; viewOptions.enableRotation = false; viewOptions.constrainResolution = true; //设置此参数,是因为需要显示整数级别。为了可视比例尺中包含当前比例尺 } this.map.setView(new (external_ol_View_default())(viewOptions)); if (options.visibleExtent) { const view = this.map.getView(); const resolution = view.getResolutionForExtent(options.visibleExtent, this.map.getSize()); view.setResolution(resolution); view.setCenter((0,external_ol_extent_namespaceObject.getCenter)(options.visibleExtent)); } } /** * @private * @function WebMap.prototype.createBaseLayer * @description 创建矢量图层,包括底图及其叠加的矢量图层 * @param {Object} layerInfo - 关于地图的信息 * @param {number} index - 当前图层在地图中的index * @param {boolean} isCallBack - 是否调用回调函数 * @param {scope} {Object} this对象 */ createBaseLayer(layerInfo, index, isCallBack, scope, isBaseLayer) { let source, that = this; if (scope) { // 解决异步回调 that = scope; } let layerType = layerInfo.layerType; //底图和rest地图兼容 if (layerType.indexOf('TIANDITU_VEC') > -1 || layerType.indexOf('TIANDITU_IMG') > -1 || layerType.indexOf('TIANDITU_TER') > -1) { layerType = layerType.substr(0, 12); } switch (layerType) { case "TIANDITU_VEC": case "TIANDITU_IMG": case "TIANDITU_TER": source = this.createTiandituSource(layerType, layerInfo.projection); break; case "BAIDU": source = this.createBaiduSource(); break; case 'BING': source = this.createBingSource(layerInfo, layerInfo.projection); break; case "WMS": source = this.createWMSSource(layerInfo); break; case "WMTS": source = that.createWMTSSource(layerInfo); break; case 'TILE': case 'SUPERMAP_REST': source = that.createDynamicTiledSource(layerInfo, isBaseLayer); break; case 'CLOUD': case 'CLOUD_BLACK': case 'OSM': case 'JAPAN_ORT': case 'JAPAN_RELIEF': case 'JAPAN_PALE': case 'JAPAN_STD': case 'GOOGLE_CN': case 'GOOGLE': source = this.createXYZSource(layerInfo); break; default: break; } var layer = new external_ol_layer_namespaceObject.Tile({ source: source, zIndex: layerInfo.zIndex || 1, visible: layerInfo.visible }); var layerID = core_Util_Util.newGuid(8); if (layerInfo.name) { layer.setProperties({ name: layerInfo.name, layerID: layerID }); } if (layerInfo.visible === undefined || layerInfo.visible === null) { layerInfo.visible = true; } layer.setVisible(layerInfo.visible); layerInfo.opacity && layer.setOpacity(layerInfo.opacity); //layerInfo没有存储index属性 index && layer.setZIndex(index); //否则没有ID,对不上号 layerInfo.layer = layer; layerInfo.layerID = layerID; let {visibleScale, autoUpdateTime} = layerInfo, minResolution, maxResolution; if (visibleScale) { maxResolution = this.resolutions[visibleScale.minScale]; minResolution = this.resolutions[visibleScale.maxScale]; //比例尺和分别率是反比的关系 maxResolution > 1 ? layer.setMaxResolution(Math.ceil(maxResolution)) : layer.setMaxResolution(maxResolution * 1.1); layer.setMinResolution(minResolution); } if (autoUpdateTime && !layerInfo.autoUpdateInterval) { //自动更新 layerInfo.autoUpdateInterval = setInterval(() => { that.updateTileToMap(layerInfo, index); }, autoUpdateTime); } if (isCallBack) { layer.setZIndex(0); // wmts that.map.addLayer(layer); } return layer; } /** * @private * @function WebMap.prototype.updateTileToMap * @description 获取底图对应的图层信息,不是用请求回来的底图信息 * @param {Object} layerInfo - 图层信息 * @param {number} layerIndex - 图层index */ updateTileToMap(layerInfo, layerIndex) { this.map.removeLayer(layerInfo.layer); this.map.addLayer(this.createBaseLayer(layerInfo, layerIndex)); } /** * @private * @function WebMap.prototype.getInternetMapInfo * @description 获取底图对应的图层信息,不是用请求回来的底图信息 * @param {Object} baseLayerInfo - 底图信息 * @returns {Object} 底图的具体信息 */ getInternetMapInfo(baseLayerInfo) { const baiduBounds = [-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892]; const bounds_4326 = [-180, -90, 180, 90]; const osmBounds = [-20037508.34, -20037508.34, 20037508.34, 20037508.34]; const japanReliefBounds = [12555667.53929, 1281852.98656, 17525908.86651, 7484870.70596]; const japanOrtBounds = [-19741117.14519, -10003921.36848, 19981677.71404, 19660983.56089]; baseLayerInfo.units = "m"; switch (baseLayerInfo.layerType) { case ('BAIDU'): baseLayerInfo.iServerUrl = 'https://map.baidu.com/'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 1; baseLayerInfo.maxZoom = 19; baseLayerInfo.level = 1; baseLayerInfo.extent = baiduBounds; // thumbnail: this.getImagePath('bmap.png') 暂时不用到缩略图 break; case ('CLOUD'): baseLayerInfo.url = 'http://t2.dituhui.com/FileService/image?map=quanguo&type=web&x={x}&y={y}&z={z}'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 1; baseLayerInfo.maxZoom = 18; baseLayerInfo.level = 1; baseLayerInfo.extent = baiduBounds; break; case ('CLOUD_BLACK'): baseLayerInfo.url = 'http://t3.dituhui.com/MapService/getGdp?x={x}&y={y}&z={z}'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 1; baseLayerInfo.maxZoom = 18; baseLayerInfo.level = 1; baseLayerInfo.extent = baiduBounds; break; case ('tencent'): baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 1; baseLayerInfo.maxZoom = 18; baseLayerInfo.level = 1; baseLayerInfo.extent = baiduBounds; break; case ('TIANDITU_VEC_3857'): case ('TIANDITU_IMG_3857'): case ('TIANDITU_TER_3857'): baseLayerInfo.iserverUrl = 'https://map.tianditu.gov.cn/'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 0; baseLayerInfo.maxZoom = 19; baseLayerInfo.level = 1; baseLayerInfo.extent = baiduBounds; if (baseLayerInfo.layerType === "TIANDITU_TER_3857") { baseLayerInfo.maxZoom = 14; } break; case ('TIANDITU_VEC_4326'): case ('TIANDITU_IMG_4326'): case ('TIANDITU_TER_4326'): baseLayerInfo.iserverUrl = 'https://map.tianditu.gov.cn/'; baseLayerInfo.epsgCode = 'EPSG:4326'; baseLayerInfo.minZoom = 0; baseLayerInfo.maxZoom = 19; baseLayerInfo.level = 1; baseLayerInfo.extent = bounds_4326; if (baseLayerInfo.layerType === "TIANDITU_TER_4326") { baseLayerInfo.maxZoom = 14; } break; case ('OSM'): baseLayerInfo.url = 'http://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 1; baseLayerInfo.maxZoom = 19; baseLayerInfo.level = 1; baseLayerInfo.extent = osmBounds; baseLayerInfo.iserverUrl = 'https://www.openstreetmap.org'; break; case ('GOOGLE'): baseLayerInfo.url = `https://maps.googleapis.com/maps/vt?pb=!1m5!1m4!1i{z}!2i{x}!3i{y}!4i256!2m3!1e0!2sm!3i540264686!3m12!2s${this.getLang()}!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&key=${this.googleMapsAPIKey}`; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 1; baseLayerInfo.maxZoom = 22; baseLayerInfo.level = 1; baseLayerInfo.extent = osmBounds; baseLayerInfo.iserverUrl = 'https://www.google.cn/maps'; break; case ('JAPAN_STD'): baseLayerInfo.url = 'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 1; baseLayerInfo.maxZoom = 19; baseLayerInfo.level = 0; baseLayerInfo.extent = osmBounds; break; case ('JAPAN_PALE'): baseLayerInfo.url = 'https://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 2; baseLayerInfo.maxZoom = 19; baseLayerInfo.level = 2; baseLayerInfo.extent = osmBounds; break; case ('JAPAN_RELIEF'): baseLayerInfo.url = 'https://cyberjapandata.gsi.go.jp/xyz/relief/{z}/{x}/{y}.png'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 5; baseLayerInfo.maxZoom = 14; baseLayerInfo.level = 5; baseLayerInfo.extent = japanReliefBounds; break; case ('JAPAN_ORT'): baseLayerInfo.url = 'https://cyberjapandata.gsi.go.jp/xyz/ort/{z}/{x}/{y}.jpg'; baseLayerInfo.epsgCode = 'EPSG:3857'; baseLayerInfo.minZoom = 2; baseLayerInfo.maxZoom = 12; baseLayerInfo.level = 2; baseLayerInfo.extent = japanOrtBounds; break; } } /** * @private * @function WebMap.prototype.createDynamicTiledSource * @description 获取supermap iServer类型的地图的source。 * @param {Object} layerInfo * @param {boolean} isBaseLayer 是否是底图 */ createDynamicTiledSource(layerInfo, isBaseLayer) { let serverType = "IPORTAL", credential = layerInfo.credential ? layerInfo.credential.token : undefined, keyfix = 'Token', keyParams = layerInfo.url; if (layerInfo.url.indexOf("www.supermapol.com") > -1 || layerInfo.url.indexOf("itest.supermapol.com") > -1) { keyfix = 'Key'; keyParams = [keyParams]; serverType = "ONLINE"; } if (credential) { SecurityManager[`register${keyfix}`](keyParams, credential); } // extent: isBaseLayer ? layerInfo.extent : ol.proj.transformExtent(layerInfo.extent, layerInfo.projection, this.baseProjection), let options = { transparent: true, url: layerInfo.url, wrapX: false, serverType: serverType, // crossOrigin: 'anonymous', //在IE11.0.9600版本,会影响通过注册服务打开的iserver地图,不出图。因为没有携带cookie会报跨域问题 // extent: this.baseLayerExtent, // prjCoordSys: {epsgCode: isBaseLayer ? layerInfo.projection.split(':')[1] : this.baseProjection.split(':')[1]}, format: layerInfo.format }; if(!isBaseLayer && !this.isCustomProjection(this.baseProjection )){ options.prjCoordSys = { epsgCode : this.baseProjection.split(':')[1]}; } if (layerInfo.visibleScales && layerInfo.visibleScales.length > 0) { let visibleResolutions = []; for (let i in layerInfo.visibleScales) { let resolution = core_Util_Util.scaleToResolution(layerInfo.visibleScales[i], dpiConfig.default, layerInfo.coordUnit); visibleResolutions.push(resolution); } layerInfo.visibleResolutions = visibleResolutions; let tileGrid = new (external_ol_tilegrid_TileGrid_default())({ extent: layerInfo.extent, resolutions: visibleResolutions }); options.tileGrid = tileGrid; } else { options.extent = this.baseLayerExtent; //bug:ISVJ-2412,不添加下列代码出不了图。参照iserver ol3出图方式 let tileGrid = new (external_ol_tilegrid_TileGrid_default())({ extent: layerInfo.extent, resolutions: this.getResolutionsFromBounds(layerInfo.extent) }); options.tileGrid = tileGrid; } //主机名相同时不添加代理,iportal geturlResource不支持webp代理 if (layerInfo.url && !this.isSameDomain(layerInfo.url) && layerInfo.format !== 'webp') { options.tileProxy = this.server + 'apps/viewer/getUrlResource.png?url='; } let source = new TileSuperMapRest(options); SecurityManager[`register${keyfix}`](layerInfo.url); return source; } /** * @private * @function WebMap.prototype.getResolutionsFromBounds * @description 获取比例尺数组 * @param {Array.} bounds 范围数组 * @returns {styleResolutions} 比例尺数组 */ getResolutionsFromBounds(bounds) { let styleResolutions = []; let temp = Math.abs(bounds[0] - bounds[2]) / 512; for (let i = 0; i < 22; i++) { if (i === 0) { styleResolutions[i] = temp; continue; } temp = temp / 2; styleResolutions[i] = temp; } return styleResolutions; } /** * @private * @function WebMap.prototype.createTiandituSource * @description 创建天地图的source。 * @param layerType 图层类型 * @param projection 地理坐标系 * @param isLabel 是否有路网图层 * @returns {Tianditu} 天地图的source */ createTiandituSource(layerType, projection, isLabel) { let options = { layerType: layerType.split('_')[1].toLowerCase(), isLabel: isLabel || false, projection: projection, url: `https://t{0-7}.tianditu.gov.cn/{layer}_{proj}/wmts?tk=${this.tiandituKey}` }; return new Tianditu(options); } /** * @private * @function WebMap.prototype.createBaiduSource * @description 创建百度地图的source。 * @returns {BaiduMap} baidu地图的source */ createBaiduSource() { return new BaiduMap() } /** * @private * @function WebMap.prototype.createBingSource * @description 创建bing地图的source。 * @returns {ol.source.XYZ} bing地图的source */ createBingSource(layerInfo, projection) { let url = 'https://dynamic.t0.tiles.ditu.live.com/comp/ch/{quadKey}?it=G,TW,L,LA&mkt=zh-cn&og=109&cstl=w4c&ur=CN&n=z'; return new (external_ol_source_XYZ_default())({ wrapX: false, projection: projection, crossOrigin: 'anonymous', tileUrlFunction: function (coordinates) { let /*quadDigits = '', */[z, x, y] = [...coordinates]; y = y > 0 ? y - 1 : -y - 1; let index = ''; for (let i = z; i > 0; i--) { let b = 0; let mask = 1 << (i - 1); if ((x & mask) !== 0) { b++; } if ((y & mask) !== 0) { b += 2; } index += b.toString() } return url.replace('{quadKey}', index); } }) } /** * @private * @function WebMap.prototype.createXYZSource * @description 创建图层的XYZsource。 * @param {Object} layerInfo - 图层信息 * @returns {ol.source.XYZ} xyz的source */ createXYZSource(layerInfo) { return new (external_ol_source_XYZ_default())({ url: layerInfo.url, wrapX: false, crossOrigin: 'anonymous' }) } /** * @private * @function WebMap.prototype.createWMSSource * @description 创建wms地图source。 * @param {Object} layerInfo - 图层信息。 * @returns {ol.source.TileWMS} wms的source */ createWMSSource(layerInfo) { let that = this; return new (external_ol_source_TileWMS_default())({ url: layerInfo.url, wrapX: false, params: { LAYERS: layerInfo.layers ? layerInfo.layers[0] : "0", FORMAT: 'image/png', VERSION: layerInfo.version || "1.3.0" }, projection: layerInfo.projection || that.baseProjection, tileLoadFunction: function (imageTile, src) { imageTile.getImage().src = src } }) } /** * @private * @function WebMap.prototype.getTileLayerExtent * @description 获取(Supermap RestMap)的图层参数。 * @param {Object} layerInfo - 图层信息。 * @param {function} callback - 获得tile图层参数执行的回调函数 * @param {function} failedCallback - 失败回调函数 */ async getTileLayerExtent(layerInfo, callback, failedCallback) { let that = this; // 默认使用动态投影方式请求数据 let dynamicLayerInfo = await that.getTileLayerExtentInfo(layerInfo) if (dynamicLayerInfo.succeed === false) { if (dynamicLayerInfo.error.code === 400) { // dynamicLayerInfo.error.code === 400 不支持动态投影,请求restmap原始信息 let originLayerInfo = await that.getTileLayerExtentInfo(layerInfo, false); if (originLayerInfo.succeed === false) { failedCallback(); } else { Object.assign(layerInfo, originLayerInfo); callback(layerInfo); } } else { failedCallback(); } } else { Object.assign(layerInfo, dynamicLayerInfo); callback(layerInfo); } } /** * @private * @function WebMap.prototype.getTileLayerExtentInfo * @description 获取rest map的图层参数。 * @param {Object} layerInfo - 图层信息。 * @param {boolean} isDynamic - 是否请求动态投影信息 */ getTileLayerExtentInfo(layerInfo, isDynamic = true) { let that = this, token, url = layerInfo.url.trim(), credential = layerInfo.credential, options = { withCredentials: this.withCredentials, withoutFormatSuffix: true }; if (isDynamic) { let projection = { epsgCode: that.baseProjection.split(":")[1] } if (!that.isCustomProjection(that.baseProjection)) { // bug IE11 不会自动编码 url += '.json?prjCoordSys=' + encodeURI(JSON.stringify(projection)); } } if (credential) { url = `${url}&token=${encodeURI(credential.token)}`; token = credential.token; } return FetchRequest.get(that.getRequestUrl(`${url}.json`), null, options).then(function (response) { return response.json(); }).then(async (result) => { if (result.succeed === false) { return result } let format = 'png'; if(that.tileFormat === 'webp') { const isSupportWebp = await that.isSupportWebp(layerInfo.url, token); format = isSupportWebp ? 'webp' : 'png'; } return { units: result.coordUnit && result.coordUnit.toLowerCase(), coordUnit: result.coordUnit, visibleScales: result.visibleScales, extent: [result.bounds.left, result.bounds.bottom, result.bounds.right, result.bounds.top], projection: `EPSG:${result.prjCoordSys.epsgCode}`, format } }).catch((error) => { return { succeed: false, error: error } }); } /** * @private * @function WebMap.prototype.getTileInfo * @description 获取rest map的图层参数。 * @param {Object} layerInfo - 图层信息。 * @param {function} callback - 获得wmts图层参数执行的回调函数 */ getTileInfo(layerInfo, callback, mapInfo) { let that = this; let options = { withCredentials: this.withCredentials, withoutFormatSuffix: true }; if (layerInfo.url.indexOf("?token=") > -1) { that.credentialKey = 'token'; that.credentialValue = layerInfo.credential = layerInfo.url.split("?token=")[1]; layerInfo.url = layerInfo.url.split("?token=")[0]; } return FetchRequest.get(that.getRequestUrl(`${layerInfo.url}.json`), null, options).then(function (response) { return response.json(); }).then(async function (result) { // layerInfo.projection = mapInfo.projection; // layerInfo.extent = [mapInfo.extent.leftBottom.x, mapInfo.extent.leftBottom.y, mapInfo.extent.rightTop.x, mapInfo.extent.rightTop.y]; // 比例尺 单位 if(result && result.code && result.code !== 200) { throw result; } if (result.visibleScales) { layerInfo.visibleScales = result.visibleScales; layerInfo.coordUnit = result.coordUnit; } layerInfo.maxZoom = result.maxZoom; layerInfo.maxZoom = result.minZoom; let token = layerInfo.credential ? layerInfo.credential.token : undefined; layerInfo.format = 'png'; // china_dark为默认底图,还是用png出图 if(that.tileFormat === 'webp' && layerInfo.url !== 'https://maptiles.supermapol.com/iserver/services/map_China/rest/maps/China_Dark') { const isSupprtWebp = await that.isSupportWebp(layerInfo.url, token); layerInfo.format = isSupprtWebp ? 'webp' : 'png'; } // 请求结果完成 继续添加图层 if (mapInfo) { //todo 这个貌似没有用到,下次优化 callback && callback(mapInfo, null, true, that); } else { callback && callback(layerInfo); } }).catch(function (error) { that.errorCallback && that.errorCallback(error, 'getTileInfo', that.map) }); } /** * @private * @function WebMap.prototype.getWMTSUrl * @description 获取wmts请求文档的url * @param {string} url - 图层信息。 * @param {boolean} isKvp - 是否为kvp模式 */ getWMTSUrl(url, isKvp) { let splitStr = '?'; if (url.indexOf('?') > -1) { splitStr = '&' } if (isKvp) { url += splitStr + 'SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetCapabilities'; } else { url += splitStr + '/1.0.0/WMTSCapabilities.xml'; } return this.getRequestUrl(url, true); } /** * @private * @function WebMap.prototype.getWmtsInfo * @description 获取wmts的图层参数。 * @param {Object} layerInfo - 图层信息。 * @param {function} callback - 获得wmts图层参数执行的回调函数 */ getWmtsInfo(layerInfo, callback) { let that = this; let options = { withCredentials: that.withCredentials, withoutFormatSuffix: true }; const isKvp = !layerInfo.requestEncoding || layerInfo.requestEncoding === 'KVP'; return FetchRequest.get(that.getWMTSUrl(layerInfo.url, isKvp), null, options).then(function (response) { return response.text(); }).then(function (capabilitiesText) { const format = new (external_ol_format_WMTSCapabilities_default())(); let capabilities = format.read(capabilitiesText); if (that.isValidResponse(capabilities)) { let content = capabilities.Contents; let tileMatrixSet = content.TileMatrixSet, layers = content.Layer, layer, idx, layerFormat, style = 'default'; for (let n = 0; n < layers.length; n++) { if (layers[n].Identifier === layerInfo.layer) { idx = n; layer = layers[idx]; layerFormat = layer.Format[0]; var layerBounds = layer.WGS84BoundingBox; // tileMatrixSetLink = layer.TileMatrixSetLink; break; } } layer && layer.Style && layer.Style.forEach(value => { if (value.isDefault) { style = value.Identifier; } }); let scales = [], matrixIds = []; for (let i = 0; i < tileMatrixSet.length; i++) { if (tileMatrixSet[i].Identifier === layerInfo.tileMatrixSet) { let wmtsLayerEpsg = `EPSG:${tileMatrixSet[i].SupportedCRS.split('::')[1]}`; for (let h = 0; h < tileMatrixSet[i].TileMatrix.length; h++) { scales.push(tileMatrixSet[i].TileMatrix[h].ScaleDenominator); matrixIds.push(tileMatrixSet[i].TileMatrix[h].Identifier); } //bug wmts出图需要加上origin,否则会出现出图不正确的情况。偏移或者瓦片出不了 let origin = tileMatrixSet[i].TileMatrix[0].TopLeftCorner; layerInfo.origin = ["EPSG:4326", "EPSG:4490"].indexOf(wmtsLayerEpsg) > -1 ? [origin[1], origin[0]] : origin; break; } } let name = layerInfo.name, extent; if (layerBounds) { if (layerBounds[0] < -180) { layerBounds[0] = -180; } if (layerBounds[1] < -90) { layerBounds[1] = -90; } if (layerBounds[2] > 180) { layerBounds[2] = 180; } if (layerBounds[3] > 90) { layerBounds[3] = 90; } extent = external_ol_proj_namespaceObject.transformExtent(layerBounds, 'EPSG:4326', that.baseProjection); } else { extent = external_ol_proj_namespaceObject.get(that.baseProjection).getExtent() } layerInfo.tileUrl = that.getTileUrl(capabilities.OperationsMetadata.GetTile.DCP.HTTP.Get, layer, layerFormat, isKvp); //将需要的参数补上 layerInfo.extent = extent; layerInfo.name = name; layerInfo.orginEpsgCode = layerInfo.projection; layerInfo.overLayer = true; layerInfo.scales = scales; layerInfo.style = style; layerInfo.title = name; layerInfo.unit = "m"; layerInfo.layerFormat = layerFormat; layerInfo.matrixIds = matrixIds; callback && callback(layerInfo); } }).catch(function (error) { that.errorCallback && that.errorCallback(error, 'getWmtsFaild', that.map) }); } /** * @private * @function WebMap.prototype.getWmsInfo * @description 获取wms的图层参数。 * @param {Object} layerInfo - 图层信息。 */ getWmsInfo(layerInfo) { let that = this; let url = layerInfo.url.trim(); url += (url.indexOf('?') > -1 ? '&SERVICE=WMS&REQUEST=GetCapabilities' : '?SERVICE=WMS&REQUEST=GetCapabilities'); let options = { withCredentials: that.withCredentials, withoutFormatSuffix: true }; let promise = new Promise(function (resolve) { return FetchRequest.get(that.getRequestUrl(url, true), null, options).then(function (response) { return response.text(); }).then(async function (capabilitiesText) { const format = new (external_ol_format_WMSCapabilities_default())(); let capabilities = format.read(capabilitiesText); if (capabilities) { let layers = capabilities.Capability.Layer.Layer, proj = layerInfo.projection; layerInfo.subLayers = layerInfo.layers[0]; layerInfo.version = capabilities.version; for (let i = 0; i < layers.length; i++) { // 图层名比对 if (layerInfo.layers[0] === layers[i].name) { let layer = layers[i]; if (layer.bbox[proj]) { let bbox = layer.bbox[proj].bbox; // wmts 130 坐标轴是否反向,目前还无法判断 // 后续还需继续完善WKT 增加坐标轴方向值 // 目前wkt信息 来自https://epsg.io/ // 提供坐标方向值的网站 如:https://www.epsg-registry.org/export.htm?wkt=urn:ogc:def:crs:EPSG::4490 if ((layerInfo.version === "1.3.0" && layerInfo.projection === "EPSG:4326") || (layerInfo.version === "1.3.0" && layerInfo.projection === "EPSG:4490")) { layerInfo.extent = [bbox[1], bbox[0], bbox[3], bbox[2]]; } else { layerInfo.extent = bbox; } break; } } } } resolve(); }).catch(function (error) { that.errorCallback && that.errorCallback(error, 'getWMSFaild', that.map) resolve(); }) }); return promise; } /** * @private * @function WebMap.prototype.getTileUrl * @description 获取wmts的图层参数。 * @param {Object} getTileArray - 图层信息。 * @param {string} layer - 选择的图层 * @param {string} format - 选择的出图方式 * @param {boolean} isKvp - 是否是kvp方式 */ getTileUrl(getTileArray, layer, format, isKvp) { let url; if (isKvp) { getTileArray.forEach(data => { if (data.Constraint[0].AllowedValues.Value[0].toUpperCase() === 'KVP') { url = data.href; } }) } else { const reuslt = layer.ResourceURL.filter(resource => { return resource.format === format; }) url = reuslt[0].template; } return url; } /** * @private * @function WebMap.prototype.createWMTSSource * @description 获取WMTS类型图层的source。 * @param {Object} layerInfo - 图层信息。 * @returns {ol.source.WMTS} wmts的souce */ createWMTSSource(layerInfo) { let extent = layerInfo.extent || external_ol_proj_namespaceObject.get(layerInfo.projection).getExtent(); // 单位通过坐标系获取 (PS: 以前代码非4326 都默认是米) let unit = external_ol_proj_namespaceObject.get(this.baseProjection).getUnits(); return new (external_ol_source_WMTS_default())({ url: layerInfo.tileUrl || layerInfo.url, layer: layerInfo.layer, format: layerInfo.layerFormat, style: layerInfo.style, matrixSet: layerInfo.tileMatrixSet, requestEncoding: layerInfo.requestEncoding || 'KVP', tileGrid: this.getWMTSTileGrid(extent, layerInfo.scales, unit, layerInfo.dpi, layerInfo.origin, layerInfo.matrixIds), tileLoadFunction: function (imageTile, src) { if (src.indexOf('tianditu.gov.cn') >= 0) { imageTile.getImage().src = `${src}&tk=${Util.getParameters(layerInfo.url)['tk']}`; return; } imageTile.getImage().src = src } }) } /** * @private * @function WebMap.prototype.getWMTSTileGrid * @description 获取wmts的瓦片。 * @param {Object} extent - 图层范围。 * @param {number} scales - 图层比例尺 * @param {string} unit - 单位 * @param {number} dpi - dpi * @param {Array} origin 瓦片的原点 * @returns {ol.tilegrid.WMTS} wmts的瓦片 */ getWMTSTileGrid(extent, scales, unit, dpi, origin, matrixIds) { let resolutionsInfo = this.getReslutionsFromScales(scales, dpi || dpiConfig.iServerWMTS, unit); return new (external_ol_tilegrid_WMTS_default())({ origin, extent: extent, resolutions: resolutionsInfo.res, matrixIds: matrixIds || resolutionsInfo.matrixIds }); } /** * @private * @function WebMap.prototype.getReslutionsFromScales * @description 根据比例尺(比例尺分母)、地图单位、dpi、获取一个分辨率数组 * @param {Array.} scales - 比例尺(比例尺分母) * @param {number} dpi - 地图dpi * @param {string} unit - 单位 * @param {number} datumAxis * @returns {{res: Array, matrixIds: Array}} */ getReslutionsFromScales(scales, dpi, unit, datumAxis) { unit = (unit && unit.toLowerCase()) || 'degrees'; dpi = dpi || dpiConfig.iServerWMTS; datumAxis = datumAxis || 6378137; let res = [], matrixIds = []; //给个默认的 if (core_Util_Util.isArray(scales)) { scales && scales.forEach(function (scale, idx) { if (scale > 1.0) { matrixIds.push(idx); res.push(this.getResolutionFromScale(scale, dpi, unit, datumAxis)); } }, this); } else { let tileMatrixSet = scales['TileMatrix']; tileMatrixSet && tileMatrixSet.forEach(function (tileMatrix) { matrixIds.push(tileMatrix['Identifier']); res.push(this.getResolutionFromScale(tileMatrix['ScaleDenominator'], dpi, unit, datumAxis)); }, this); } return { res: res, matrixIds: matrixIds }; } /** * @private * @function WebMap.prototype.getResolutionFromScale * @description 获取一个WMTS source需要的tileGrid * @param {number} scale - 比例尺(比例尺分母) * @param {number} dpi - 地图dpi * @param {string} unit - 单位 * @param {number} datumAxis * @returns {{res: Array, matrixIds: Array}} */ getResolutionFromScale(scale, dpi = dpiConfig.default, unit, datumAxis) { //radio = 10000; let res; scale = +scale; scale = (scale > 1.0) ? (1.0 / scale) : scale; if (unit === 'degrees' || unit === 'dd' || unit === 'degree') { res = 0.0254 * 10000 / dpi / scale / ((Math.PI * 2 * datumAxis) / 360) / 10000; } else { res = 0.0254 * 10000 / dpi / scale / 10000; } return res; } /** * @private * @function WebMap.prototype.isValidResponse * @description 返回信息是否符合对应类型的标准 * @param {Object} response - 返回的信息 * @returns {boolean} */ isValidResponse(response) { let responseEnum = ['Contents', 'OperationsMetadata'], valid = true; for (let i = 0; i < responseEnum.length; i++) { if (!response[responseEnum[i]] || response.error) { valid = false; break; } } return valid; } /** * @private * @function WebMap.prototype.addLayers * @description 添加叠加图层 * @param {Object} mapInfo - 地图信息 */ async addLayers(mapInfo) { let layers = mapInfo.layers, that = this; let features = [], len = layers.length; if (len > 0) { //存储地图上所有的图层对象 this.layers = layers; for (let index = 0; index< layers.length; index++) { const layer = layers[index]; //加上底图的index let layerIndex = index + 1, dataSource = layer.dataSource, isSampleData = dataSource && dataSource.type === "SAMPLE_DATA" && !!dataSource.name; //SAMPLE_DATA是本地示例数据 if (layer.layerType === "MAPBOXSTYLE") { that.addMVTMapLayer(mapInfo, layer, layerIndex).then(() => { that.layerAdded++; that.sendMapToUser(len); }).catch(function (error) { that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(error, 'getLayerFaild', that.map); }); } else if ((dataSource && dataSource.serverId) || layer.layerType === "MARKER" || layer.layerType === 'HOSTED_TILE' || isSampleData) { //数据存储到iportal上了 let dataSource = layer.dataSource, serverId = dataSource ? dataSource.serverId : layer.serverId; if (!serverId && !isSampleData) { await that.addLayer(layer, null, layerIndex); that.layerAdded++; that.sendMapToUser(len); return; } if ((layer.layerType === "MARKER") || (dataSource && (!dataSource.accessType || dataSource.accessType === 'DIRECT')) || isSampleData) { //原来二进制文件 let url = isSampleData ? `${that.server}apps/dataviz/libs/sample-datas/${dataSource.name}.json` : `${that.server}web/datas/${serverId}/content.json?pageSize=9999999¤tPage=1`; url = that.getRequestUrl(url); FetchRequest.get(url, null, { withCredentials: this.withCredentials }).then(function (response) { return response.json() }).then(async function (data) { if (data.succeed === false) { //请求失败 that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(data.error, 'getLayerFaild', that.map); return; } if (data && data.type) { if (data.type === "JSON" || data.type === "GEOJSON") { data.content = data.content.type ? data.content : JSON.parse(data.content); features = that.geojsonToFeature(data.content, layer); } else if (data.type === 'EXCEL' || data.type === 'CSV') { if (layer.dataSource && layer.dataSource.administrativeInfo) { //行政规划信息 data.content.rows.unshift(data.content.colTitles); let {divisionType, divisionField} = layer.dataSource.administrativeInfo; let geojson = that.excelData2FeatureByDivision(data.content, divisionType, divisionField); features = that._parseGeoJsonData2Feature({allDatas: {features: geojson.features}, fileCode: layer.projection}); } else { features = await that.excelData2Feature(data.content, layer); } } else if (data.type === 'SHP') { let content = JSON.parse(data.content); data.content = content.layers[0]; features = that.geojsonToFeature(data.content, layer); } await that.addLayer(layer, features, layerIndex); that.layerAdded++; that.sendMapToUser(len); } }).catch(function (error) { that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(error, 'getLayerFaild', that.map); }) } else { //关系型文件 let isMapService = layer.layerType === 'HOSTED_TILE', serverId = dataSource ? dataSource.serverId : layer.serverId; that.checkUploadToRelationship(serverId).then(function (result) { if (result && result.length > 0) { let datasetName = result[0].name, featureType = result[0].type.toUpperCase(); that.getDataService(serverId, datasetName).then(async function (data) { let dataItemServices = data.dataItemServices; if (dataItemServices.length === 0) { that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(null, 'getLayerFaild', that.map); return; } if (isMapService) { //需要判断是使用tile还是mvt服务 let dataService = that.getService(dataItemServices, 'RESTDATA'); that.isMvt(dataService.address, datasetName).then(async info => { await that.getServiceInfoFromLayer(layerIndex, len, layer, dataItemServices, datasetName, featureType, info); }).catch(async () => { //判断失败就走之前逻辑,>数据量用tile await that.getServiceInfoFromLayer(layerIndex, len, layer, dataItemServices, datasetName, featureType); }) } else { await that.getServiceInfoFromLayer(layerIndex, len, layer, dataItemServices, datasetName, featureType); } }); } else { that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(null, 'getLayerFaild', that.map); } }).catch(function (error) { that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(error, 'getLayerFaild', that.map); }) } } else if (dataSource && dataSource.type === "USER_DATA") { that.addGeojsonFromUrl(layer, len, layerIndex, false); } else if (layer.layerType === "TILE"){ that.getTileLayerExtent(layer, function (layerInfo) { that.map.addLayer(that.createBaseLayer(layerInfo, layerIndex)); that.layerAdded++; that.sendMapToUser(len); }, function (e) { that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(e, 'getLayerFaild', that.map); }) } else if (layer.layerType === 'SUPERMAP_REST' || layer.layerType === "WMS" || layer.layerType === "WMTS") { if (layer.layerType === "WMTS") { that.getWmtsInfo(layer, function (layerInfo) { that.map.addLayer(that.createBaseLayer(layerInfo, layerIndex)); that.layerAdded++; that.sendMapToUser(len); }) } else if(layer.layerType === "WMS") { that.getWmsInfo(layer).then(() => { that.map.addLayer(that.createBaseLayer(layer, layerIndex)); that.layerAdded++; that.sendMapToUser(len); }) } else { layer.projection = that.baseProjection; that.map.addLayer(that.createBaseLayer(layer, layerIndex)); that.layerAdded++; that.sendMapToUser(len); } } else if (dataSource && dataSource.type === "REST_DATA") { //从restData获取数据 that.getFeaturesFromRestData(layer, layerIndex, len); } else if (dataSource && dataSource.type === "REST_MAP" && dataSource.url) { //示例数据 queryFeatureBySQL(dataSource.url, dataSource.layerName, 'smid=1', null, null, function (result) { var recordsets = result && result.result.recordsets; var recordset = recordsets && recordsets[0]; var attributes = recordset.fields; if (recordset && attributes) { let fileterAttrs = []; for (var i in attributes) { var value = attributes[i]; if (value.indexOf('Sm') !== 0 || value === "SmID") { fileterAttrs.push(value); } } that.getFeatures(fileterAttrs, layer, async function (features) { await that.addLayer(layer, features, layerIndex); that.layerAdded++; that.sendMapToUser(len); }, function (e) { that.layerAdded++; that.errorCallback && that.errorCallback(e, 'getFeatureFaild', that.map); }); } }, function (e) { that.errorCallback && that.errorCallback(e, 'getFeatureFaild', that.map); }) } else if (layer.layerType === "DATAFLOW_POINT_TRACK" || layer.layerType === "DATAFLOW_HEAT") { that.getDataflowInfo(layer, async function () { await that.addLayer(layer, features, layerIndex); that.layerAdded++; that.sendMapToUser(len); }, function (e) { that.layerAdded++; that.errorCallback && that.errorCallback(e, 'getFeatureFaild', that.map); }) } } } } /** * @private * @function WebMap.prototype.addGeojsonFromUrl * @description 从web服务输入geojson地址的图层 * @param {Object} layerInfo - 图层信息 * @param {number} len - 总的图层数量 * @param {number} layerIndex - 当前图层index * @param {boolean} withCredentials - 是否携带cookie */ addGeojsonFromUrl(layerInfo, len, layerIndex, withCredentials = this.withCredentials) { // 通过web添加geojson不需要携带cookie let {dataSource} = layerInfo, {url} = dataSource, that = this; FetchRequest.get(url, null, { withCredentials, withoutFormatSuffix: true }).then(function (response) { return response.json() }).then(async function (data) { if (!data || data.succeed === false) { //请求失败 if (len) { that.errorCallback && that.errorCallback(data.error, 'autoUpdateFaild', that.map) } else { that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(data.error, 'getLayerFaild', that.map); } return; } var features; if (data.type === 'CSV' || data.type === 'EXCEL') { if (layerInfo.dataSource && layerInfo.dataSource.administrativeInfo) { //行政规划信息 data.content.rows.unshift(data.content.colTitles); let {divisionType, divisionField} = layerInfo.dataSource.administrativeInfo; let geojson = that.excelData2FeatureByDivision(data.content, divisionType, divisionField); features = that._parseGeoJsonData2Feature({allDatas: {features: geojson.features}, fileCode: layerInfo.projection}); } else { features = await that.excelData2Feature(data.content, layerInfo); } } else { var geoJson = data.content ? JSON.parse(data.content) : data; features = that.geojsonToFeature(geoJson, layerInfo); } if (len) { //上图 await that.addLayer(layerInfo, features, layerIndex); that.layerAdded++; that.sendMapToUser(len); } else { //自动更新 that.map.removeLayer(layerInfo.layer); layerInfo.labelLayer && that.map.removeLayer(layerInfo.labelLayer); await that.addLayer(layerInfo, features, layerIndex); } }).catch(function (error) { that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(error, 'getLayerFaild', that.map); }) } /** * @private * @function WebMap.prototype.getServiceInfoFromLayer * @description 判断使用哪种服务上图 * @param {number} layerIndex - 图层对应的index * @param {number} len - 成功添加的图层个数 * @param {Object} layer - 图层信息 * @param {Array.} dataItemServices - 数据发布的服务 * @param {string} datasetName - 数据服务的数据集名称 * @param {string} featureType - feature类型 * @param {Object} info - 数据服务的信息 */ async getServiceInfoFromLayer(layerIndex, len, layer, dataItemServices, datasetName, featureType, info) { let that = this; let isMapService = info ? !info.isMvt : layer.layerType === 'HOSTED_TILE', isAdded = false; for (let i = 0; i < dataItemServices.length; i++) { const service = dataItemServices[i]; if (isAdded) { return; } //有服务了,就不需要循环 if (service && isMapService && service.serviceType === 'RESTMAP') { isAdded = true; //地图服务,判断使用mvt还是tile that.getTileLayerInfo(service.address).then(function (restMaps) { restMaps.forEach(function (restMapInfo) { let bounds = restMapInfo.bounds; layer.layerType = 'TILE'; layer.orginEpsgCode = that.baseProjection; layer.units = restMapInfo.coordUnit && restMapInfo.coordUnit.toLowerCase(); layer.extent = [bounds.left, bounds.bottom, bounds.right, bounds.top]; layer.visibleScales = restMapInfo.visibleScales; layer.url = restMapInfo.url; layer.sourceType = 'TILE'; that.map.addLayer(that.createBaseLayer(layer, layerIndex)); that.layerAdded++; that.sendMapToUser(len); }) }) } else if (service && !isMapService && service.serviceType === 'RESTDATA') { isAdded = true; if (info && info.isMvt) { let bounds = info.bounds; layer = Object.assign(layer, { layerType: "VECTOR_TILE", epsgCode: info.epsgCode, projection: `EPSG:${info.epsgCode}`, bounds: bounds, extent: [bounds.left, bounds.bottom, bounds.right, bounds.top], name: layer.name, url: info.url, visible: layer.visible, featureType: featureType, serverId: layer.serverId.toString() }); that.map.addLayer(await that.addVectorTileLayer(layer, layerIndex, 'RESTDATA')); that.layerAdded++; that.sendMapToUser(len); } else { //数据服务 isAdded = true; //关系型文件发布的数据服务 that.getDatasources(service.address).then(function (datasourceName) { layer.dataSource.dataSourceName = datasourceName + ":" + datasetName; layer.dataSource.url = `${service.address}/data`; that.getFeaturesFromRestData(layer, layerIndex, len); }); } } } if (!isAdded) { //循环完成了,也没有找到合适的服务。有可能服务被删除 that.layerAdded++; that.sendMapToUser(len); that.errorCallback && that.errorCallback(null, 'getLayerFaild', that.map); } } /** * @private * @function WebMap.prototype.getDataflowInfo * @description 获取数据流服务的参数 * @param {Object} layerInfo - 图层信息 * @param {function} success - 成功回调函数 * @param {function} faild - 失败回调函数 */ getDataflowInfo(layerInfo, success, faild) { let that = this; let url = layerInfo.url, token; let requestUrl = that.getRequestUrl(`${url}.json`, false); if (layerInfo.credential && layerInfo.credential.token) { token = layerInfo.credential.token; requestUrl += `?token=${token}`; } FetchRequest.get(requestUrl, null, { withCredentials: this.withCredentials }).then(function (response) { return response.json() }).then(function (result) { layerInfo.featureType = "POINT"; if (result && result.featureMetaData) { layerInfo.featureType = result.featureMetaData.featureType.toUpperCase(); } layerInfo.wsUrl = result.urls[0].url; success(); }).catch(function () { faild(); }); } /** * @private * @function WebMap.prototype.getFeaturesFromRestData * @description 从数据服务中获取feature * @param {Object} layer - 图层信息 * @param {number} layerIndex - 图层index * @param {number} layerLength - 图层数量 */ getFeaturesFromRestData(layer, layerIndex, layerLength) { let that = this, dataSource = layer.dataSource, url = layer.dataSource.url, dataSourceName = dataSource.dataSourceName || layer.name; let requestUrl = that.formatUrlWithCredential(url), serviceOptions = {}; serviceOptions.withCredentials = this.withCredentials; if (!this.excludePortalProxyUrl && !Util.isInTheSameDomain(requestUrl)) { serviceOptions.proxy = this.getProxy(); } if(['EPSG:0'].includes(layer.projection)) { // 不支持动态投影restData服务 that.layerAdded++; that.sendMapToUser(layerLength); that.errorCallback && that.errorCallback({}, 'getFeatureFaild', that.map); return; } //因为itest上使用的https,iserver是http,所以要加上代理 getFeatureBySQL(requestUrl, [decodeURIComponent(dataSourceName)], serviceOptions, async function (result) { let features = that.parseGeoJsonData2Feature({ allDatas: { features: result.result.features.features }, fileCode: that.baseProjection, //因为获取restData用了动态投影,不需要再进行坐标转换。所以此处filecode和底图坐标系一致 featureProjection: that.baseProjection }); await that.addLayer(layer, features, layerIndex); that.layerAdded++; that.sendMapToUser(layerLength); }, function (err) { that.layerAdded++; that.sendMapToUser(layerLength); that.errorCallback && that.errorCallback(err, 'getFeatureFaild', that.map) }, that.baseProjection.split("EPSG:")[1], this.restDataSingleRequestCount); } /** * @private * @function WebMap.prototype.getFeatures * @description 从地图中获取feature * @param {Object} fields - 图层信息 * @param {number} layerInfo - 图层index * @param {number} success - 成功回调 * @param {number} faild - 失败回调 */ getFeatures(fields, layerInfo, success, faild) { var that = this; var source = layerInfo.dataSource; var fileCode = layerInfo.projection; queryFeatureBySQL(source.url, source.layerName, null, fields, null, function (result) { var recordsets = result.result.recordsets[0]; var features = recordsets.features.features; var featuresObj = that.parseGeoJsonData2Feature({ allDatas: { features }, fileCode: fileCode, featureProjection: that.baseProjection }, 'JSON'); success(featuresObj); }, function (err) { faild(err); }); } /** * @private * @function WebMap.prototype.sendMapToUser * @description 将所有叠加图层叠加后,返回最终的map对象给用户,供他们操作使用 * @param {number} layersLen - 叠加图层总数 */ sendMapToUser(layersLen) { const lens = this.isHaveGraticule ? layersLen + 1 : layersLen; if (this.layerAdded === lens && this.successCallback) { this.successCallback(this.map, this.mapParams, this.layers, this.baseLayer); } } /** * @private * @function WebMap.prototype.excelData2Feature * @description 将csv和xls文件内容转换成ol.feature * @param {Object} content - 文件内容 * @param {Object} layerInfo - 图层信息 * @returns {Array} ol.feature的数组集合 */ async excelData2Feature(content, layerInfo) { let rows = content.rows, colTitles = content.colTitles; // 解决V2恢复的数据中含有空格 for (let i in colTitles) { if (core_Util_Util.isString(colTitles[i])) { colTitles[i] = core_Util_Util.trim(colTitles[i]); } } let fileCode = layerInfo.projection, dataSource = layerInfo.dataSource, baseLayerEpsgCode = this.baseProjection, features = [], xField = core_Util_Util.trim((layerInfo.xyField && layerInfo.xyField.xField) || (layerInfo.from && layerInfo.from.xField)), yField = core_Util_Util.trim((layerInfo.xyField && layerInfo.xyField.yField) || (layerInfo.from && layerInfo.from.yField)), xIdx = colTitles.indexOf(xField), yIdx = colTitles.indexOf(yField); // todo 优化 暂时这样处理 if (layerInfo.layerType === 'MIGRATION') { try { if (dataSource.type === 'PORTAL_DATA') { const {dataMetaInfo} = await FetchRequest.get(`${this.server}web/datas/${dataSource.serverId}.json`, null, { withCredentials: this.withCredentials }).then(res => res.json()); // eslint-disable-next-line require-atomic-updates layerInfo.xyField = { xField: dataMetaInfo.xField, yField: dataMetaInfo.yField } if (!dataMetaInfo.xIndex) { xIdx = colTitles.indexOf(dataMetaInfo.xField); yIdx = colTitles.indexOf(dataMetaInfo.yField); } else { xIdx = dataMetaInfo.xIndex; yIdx = dataMetaInfo.yIndex; } } else if (dataSource.type === 'SAMPLE_DATA') { // 示例数据从本地拿xyField const sampleData = SampleDataInfo_namespaceObject.find(item => item.id === dataSource.name) || {}; xField = sampleData.xField; yField = sampleData.yField layerInfo.xyField = { xField, yField } xIdx = colTitles.findIndex(item => item === xField); yIdx = colTitles.findIndex(item => item === yField); } } catch (error) { console.error(error); } } for (let i = 0, len = rows.length; i < len; i++) { let rowDatas = rows[i], attributes = {}, geomX = rows[i][xIdx], geomY = rows[i][yIdx]; // 位置字段信息不存在 过滤数据 if (geomX !== '' && geomY !== '') { let olGeom = new external_ol_geom_namespaceObject.Point([+geomX, +geomY]); if (fileCode !== baseLayerEpsgCode) { olGeom.transform(fileCode, baseLayerEpsgCode); } for (let j = 0, leng = rowDatas.length; j < leng; j++) { let field = colTitles[j]; if (field === undefined || field === null) {continue;} field = field.trim(); if (Object.keys(attributes).indexOf(field) > -1) { //说明前面有个一模一样的字段 const newField = field + '_1'; attributes[newField] = rowDatas[j]; } else { attributes[field] = rowDatas[j]; } } let feature = new (external_ol_Feature_default())({ geometry: olGeom, attributes }); features.push(feature); } } return Promise.resolve(features); } /** * @private * @function WebMap.prototype.excelData2FeatureByDivision * @description 行政区划数据处理 * @param {Object} content - 文件内容 * @param {Object} layerInfo - 图层信息 * @returns {Object} geojson对象 */ excelData2FeatureByDivision(content, divisionType, divisionField) { let me = this; let asyncInport; if (divisionType === 'Province') { asyncInport = window.ProvinceData; } else if (divisionType === 'City') { asyncInport = window.MunicipalData; } else if (divisionType === 'GB-T_2260') { // let geojso; asyncInport = window.AdministrativeArea; } if (asyncInport) { let geojson = me.changeExcel2Geojson(asyncInport.features, content.rows, divisionType, divisionField); return geojson; } } /** * @private * @function WebMap.prototype._parseGeoJsonData2Feature * @description 将geojson的数据转换成ol.Feature * @param {Object} metaData - 文件内容 * @returns {Array.} features */ _parseGeoJsonData2Feature(metaData) { let allFeatures = metaData.allDatas.features, features = []; for (let i = 0, len = allFeatures.length; i < len; i++) { //不删除properties转换后,属性全都在feature上 let properties = Object.assign({}, allFeatures[i].properties); delete allFeatures[i].properties; let feature = transformTools.readFeature(allFeatures[i], { dataProjection: metaData.fileCode, featureProjection: this.baseProjection || 'ESPG:4326' }); feature.setProperties({attributes: properties}); features.push(feature); } return features; } /** * @private * @function WebMap.prototype.changeExcel2Geojson * @description 将excel和csv数据转换成标准geojson数据 * @param {Array} features - feature对象 * @param {Array} datas - 数据内容 * @param {string} divisionType - 行政区划类型 * @param {string} divisionField - 行政区划字段 * @returns {Object} geojson对象 */ changeExcel2Geojson(features, datas, divisionType, divisionField) { let geojson = { type: 'FeatureCollection', features: [] }; if (datas.length < 2) { return geojson; //只有一行数据时为标题 } let titles = datas[0], rows = datas.slice(1), fieldIndex = titles.findIndex(title => title === divisionField); rows.forEach(row => { let feature; if (divisionType === 'GB-T_2260') { feature = features.find(item => item.properties.GB === row[fieldIndex]) } else { feature = core_Util_Util.getHighestMatchAdministration(features, row[fieldIndex]); } //todo 需提示忽略无效数据 if (feature) { let newFeature = window.cloneDeep(feature); newFeature.properties = {}; row.forEach((item, idx) => { //空格问题,看见DV多处处理空格问题,TODO统一整理 let key = titles[idx].trim(); newFeature.properties[key] = item; }); geojson.features.push(newFeature); } }); return geojson; } /** * @private * @function WebMap.prototype.geojsonToFeature * @description geojson 转换为 feature * @param {Object} layerInfo - 图层信息 * @returns {Array} ol.feature的数组集合 */ geojsonToFeature(geojson, layerInfo) { let allFeatures = geojson.features, features = []; for (let i = 0, len = allFeatures.length; i < len; i++) { //转换前删除properties,这样转换后属性不会重复存储 let featureAttr = allFeatures[i].properties || {}; delete allFeatures[i].properties; let feature = transformTools.readFeature(allFeatures[i], { dataProjection: layerInfo.projection || 'EPSG:4326', featureProjection: this.baseProjection || 'ESPG:4326' }); //geojson格式的feature属性没有坐标系字段,为了统一,再次加上 let coordinate = feature.getGeometry().getCoordinates(); if (allFeatures[i].geometry.type === 'Point') { // 标注图层 还没有属性值时候不加 if (allFeatures[i].properties) { allFeatures[i].properties.lon = coordinate[0]; allFeatures[i].properties.lat = coordinate[1]; } } // 标注图层特殊处理 let isMarker = false; let attributes; let useStyle; if (allFeatures[i].dv_v5_markerInfo) { //因为优化代码之前,属性字段都存储在propertise上,markerInfo没有 attributes = Object.assign({}, allFeatures[i].dv_v5_markerInfo, featureAttr); if (attributes.lon) { //标注图层不需要 delete attributes.lon; delete attributes.lat; } } if (allFeatures[i].dv_v5_markerStyle) { useStyle = allFeatures[i].dv_v5_markerStyle; isMarker = true; } let properties; if (isMarker) { properties = Object.assign({}, { attributes }, { useStyle }); //feature上添加图层的id,为了对应图层 feature.layerId = layerInfo.timeId; } else if (layerInfo.featureStyles) { //V4 版本标注图层处理 let style = JSON.parse(layerInfo.featureStyles[i].style); let attr = featureAttr; let imgUrl; if (attr._smiportal_imgLinkUrl.indexOf('http://') > -1 || attr._smiportal_imgLinkUrl.indexOf('https://') > -1) { imgUrl = attr._smiportal_imgLinkUrl; } else if (attr._smiportal_imgLinkUrl !== undefined && attr._smiportal_imgLinkUrl !== null && attr._smiportal_imgLinkUrl !== '') { //上传的图片,加上当前地址 imgUrl = `${core_Util_Util.getIPortalUrl()}resources/markerIcon/${attr._smiportal_imgLinkUrl}` } attributes = { dataViz_description: attr._smiportal_description, dataViz_imgUrl: imgUrl, dataViz_title: attr._smiportal_title, dataViz_url: attr._smiportal_otherLinkUrl }; style.anchor = [0.5, 1]; style.src = style.externalGraphic; useStyle = style; properties = Object.assign({}, { attributes }, { useStyle }); delete attr._smiportal_description; delete attr._smiportal_imgLinkUrl; delete attr._smiportal_title; delete attr._smiportal_otherLinkUrl; } else { properties = {attributes: featureAttr}; } feature.setProperties(properties); features.push(feature); } return features; } /** * @private * @function WebMap.prototype.parseGeoJsonData2Feature * @description 将从restData地址上获取的json转换成feature(从iserver中获取的json转换成feature) * @param {Object} metaData - json内容 * @returns {Array} ol.feature的数组集合 */ parseGeoJsonData2Feature(metaData) { let allFeatures = metaData.allDatas.features, features = []; for (let i = 0, len = allFeatures.length; i < len; i++) { let properties = allFeatures[i].properties; delete allFeatures[i].properties; let feature = transformTools.readFeature(allFeatures[i], { dataProjection: metaData.fileCode || 'EPSG:4326', featureProjection: metaData.featureProjection || this.baseProjection || 'EPSG:4326' }); //geojson格式的feature属性没有坐标系字段,为了统一,再次加上 let geometry = feature.getGeometry(); // 如果不存在geometry,也不需要组装feature if(!geometry) {continue;} let coordinate = geometry.getCoordinates(); if (allFeatures[i].geometry.type === 'Point') { properties.lon = coordinate[0]; properties.lat = coordinate[1]; } feature.setProperties({ attributes: properties }); features.push(feature); } return features; } /** * @private * @function WebMap.prototype.addLayer * @description 将叠加图层添加到地图上 * @param {Object} layerInfo - 图层信息 * @param {Array} features - 图层上的feature集合 * @param {number} index 图层的顺序 */ async addLayer(layerInfo, features, index) { let layer, that = this; if (layerInfo.layerType === "VECTOR") { if (layerInfo.featureType === "POINT") { if (layerInfo.style.type === 'SYMBOL_POINT') { layer = this.createSymbolLayer(layerInfo, features); } else { layer = await this.createGraphicLayer(layerInfo, features); } } else { //线和面 layer = await this.createVectorLayer(layerInfo, features) } } else if (layerInfo.layerType === "UNIQUE") { layer = await this.createUniqueLayer(layerInfo, features); } else if (layerInfo.layerType === "RANGE") { layer = await this.createRangeLayer(layerInfo, features); } else if (layerInfo.layerType === "HEAT") { layer = this.createHeatLayer(layerInfo, features); } else if (layerInfo.layerType === "MARKER") { layer = await this.createMarkerLayer(features); } else if (layerInfo.layerType === "DATAFLOW_POINT_TRACK") { layer = await this.createDataflowLayer(layerInfo, index); } else if (layerInfo.layerType === "DATAFLOW_HEAT") { layer = this.createDataflowHeatLayer(layerInfo); } else if (layerInfo.layerType === "RANK_SYMBOL") { layer = await this.createRankSymbolLayer(layerInfo, features); } else if (layerInfo.layerType === "MIGRATION") { layer = this.createMigrationLayer(layerInfo, features); } let layerID = core_Util_Util.newGuid(8); if (layer) { layerInfo.name && layer.setProperties({ name: layerInfo.name, layerID: layerID, layerType: layerInfo.layerType }); //刷新下图层,否则feature样式出不来 if (layerInfo && layerInfo.style && layerInfo.style.imageInfo) { let img = new Image(); img.src = layerInfo.style.imageInfo.url; img.onload = function () { layer.getSource().changed(); }; } if (layerInfo.layerType === 'MIGRATION') { layer.appendTo(this.map); // 在这里恢复图层可见性状态 layer.setVisible(layerInfo.visible); // 设置鼠标样式为默认 layer.setCursor(); } else { layerInfo.opacity != undefined && layer.setOpacity(layerInfo.opacity); layer.setVisible(layerInfo.visible); this.map.addLayer(layer); } layer.setZIndex(index); const {visibleScale, autoUpdateTime} = layerInfo; visibleScale && this.setVisibleScales(layer, visibleScale); if (autoUpdateTime && !layerInfo.autoUpdateInterval) { //自动更新数据 let dataSource = layerInfo.dataSource; if (dataSource.accessType === "DIRECT" && !dataSource.url) { // 二进制数据更新feautre所需的url dataSource.url = `${this.server}web/datas/${dataSource.serverId}/content.json?pageSize=9999999¤tPage=1` } layerInfo.autoUpdateInterval = setInterval(() => { that.updateFeaturesToMap(layerInfo, index, true); }, autoUpdateTime); } } layerInfo.layer = layer; layerInfo.layerID = layerID; if (layerInfo.labelStyle && layerInfo.labelStyle.labelField && layerInfo.layerType !== "DATAFLOW_POINT_TRACK") { //存在标签专题图 //过滤条件过滤feature features = layerInfo.filterCondition ? this.getFiterFeatures(layerInfo.filterCondition, features) : features; this.addLabelLayer(layerInfo, features); } } /** * @private * @function WebMap.prototype.updateFeaturesToMap * @description 更新地图上的feature,适用于专题图 * @param {Object} layerInfo - 图层信息 * @param {number} index 图层的顺序 */ updateFeaturesToMap(layerInfo, layerIndex) { let that = this, dataSource = layerInfo.dataSource, url = layerInfo.dataSource.url, dataSourceName = dataSource.dataSourceName || layerInfo.name; if (dataSource.type === "USER_DATA" || dataSource.accessType === "DIRECT") { that.addGeojsonFromUrl(layerInfo, null, layerIndex) } else { let requestUrl = that.formatUrlWithCredential(url), serviceOptions = {}; serviceOptions.withCredentials = this.withCredentials; if (!this.excludePortalProxyUrl && !Util.isInTheSameDomain(requestUrl)) { serviceOptions.proxy = this.getProxy(); } //因为itest上使用的https,iserver是http,所以要加上代理 getFeatureBySQL(requestUrl, [dataSourceName], serviceOptions, async function (result) { let features = that.parseGeoJsonData2Feature({ allDatas: { features: result.result.features.features }, fileCode: layerInfo.projection, featureProjection: that.baseProjection }); //删除之前的图层和标签图层 that.map.removeLayer(layerInfo.layer); layerInfo.labelLayer && that.map.removeLayer(layerInfo.labelLayer); await that.addLayer(layerInfo, features, layerIndex); }, function (err) { that.errorCallback && that.errorCallback(err, 'autoUpdateFaild', that.map); }, undefined, this.restDataSingleRequestCount); } } /** * @private * @function WebMap.prototype.addVectorTileLayer * @description 添加vectorTILE图层 * @param {Object} layerInfo - 图层信息 * @param {number} index 图层的顺序 * @param {string} type 创建的图层类型,restData为创建数据服务的mvt, restMap为创建地图服务的mvt * @returns {ol.layer.VectorTile} 图层对象 */ async addVectorTileLayer(layerInfo, index, type) { let layer; if (type === 'RESTDATA') { //用的是restdata服务的mvt layer = await this.createDataVectorTileLayer(layerInfo) } let layerID = core_Util_Util.newGuid(8); if (layer) { layerInfo.name && layer.setProperties({ name: layerInfo.name, layerID: layerID }); layerInfo.opacity != undefined && layer.setOpacity(layerInfo.opacity); layer.setVisible(layerInfo.visible); layer.setZIndex(index); } layerInfo.layer = layer; layerInfo.layerID = layerID; return layer; } /** * @private * @function WebMap.prototype.createDataVectorTileLayer * @description 创建vectorTILE图层 * @param {Object} layerInfo - 图层信息 * @returns {ol.layer.VectorTile} 图层对象 */ async createDataVectorTileLayer(layerInfo) { //创建图层 var format = new (external_ol_format_MVT_default())({ featureClass: (external_ol_Feature_default()) }); //要加上这一句,否则坐标,默认都是3857 (external_ol_format_MVT_default()).prototype.readProjection = function () { return new external_ol_proj_namespaceObject.Projection({ code: '', units: (external_ol_proj_Units_default()).TILE_PIXELS }); }; let featureType = layerInfo.featureType; let style = await StyleUtils.toOpenLayersStyle(this.getDataVectorTileStyle(featureType), featureType); return new external_ol_layer_namespaceObject.VectorTile({ //设置避让参数 source: new VectorTileSuperMapRest({ url: layerInfo.url, projection: layerInfo.projection, tileType: "ScaleXY", format: format }), style: style }); } /** * @private * @function WebMap.prototype.getDataVectorTileStyle * @description 获取数据服务的mvt上图的默认样式 * @param {string} featureType - 要素类型 * @returns {Object} 样式参数 */ getDataVectorTileStyle(featureType) { let styleParameters = { radius: 8, //圆点半径 fillColor: '#EE4D5A', //填充色 fillOpacity: 0.9, strokeColor: '#ffffff', //边框颜色 strokeWidth: 1, strokeOpacity: 1, lineDash: 'solid', type: "BASIC_POINT" }; if (["LINE", "LINESTRING", "MULTILINESTRING"].indexOf(featureType) > -1) { styleParameters.strokeColor = '#4CC8A3'; styleParameters.strokeWidth = 2; } else if (["REGION", "POLYGON", "MULTIPOLYGON"].indexOf(featureType) > -1) { styleParameters.fillColor = '#826DBA'; } return styleParameters; } /** * @private * @function WebMap.prototype.getFiterFeatures * @description 通过过滤条件查询满足的feature * @param {string} filterCondition - 过滤条件 * @param {Array} allFeatures - 图层上的feature集合 */ getFiterFeatures(filterCondition, allFeatures) { let condition = this.parseFilterCondition(filterCondition); let filterFeatures = []; for (let i = 0; i < allFeatures.length; i++) { let feature = allFeatures[i]; let filterResult = false; try { const properties = feature.get('attributes'); const conditions = parseCondition(condition, Object.keys(properties)); const filterFeature = parseConditionFeature(properties); const sql = 'select * from json where (' + conditions + ')'; filterResult = window.jsonsql.query(sql, { attributes: filterFeature }); } catch (err) { //必须把要过滤得内容封装成一个对象,主要是处理jsonsql(line : 62)中由于with语句遍历对象造成的问题 continue; } if (filterResult && filterResult.length > 0) { //afterFilterFeatureIdx.push(i); filterFeatures.push(feature); } } return filterFeatures; } /** * @private * @function WebMap.prototype.parseFilterCondition * @description 1、替换查询语句 中的 and / AND / or / OR / = / != * 2、匹配 Name in ('', ''),多条件需用()包裹 * @param {string} filterCondition - 过滤条件 * @return {string} 换成组件能识别的字符串 */ parseFilterCondition(filterCondition) { return filterCondition .replace(/=/g, "==") .replace(/AND|and/g, "&&") .replace(/or|OR/g, "||") .replace(/<==/g, "<=") .replace(/>==/g, ">=") .replace(/\(?[^\(]+?\s*in\s*\([^\)]+?\)\)?/gi, (res) => { // res格式:(省份 in ('四川', '河南')) const data = res.match(/([^(]+?)\s*in\s*\(([^)]+?)\)/i); return data.length === 3 ? `(${data[2] .split(",") .map((c) => `${data[1]} == ${c.trim()}`) .join(" || ")})` : res; }); } /** * @private * @function WebMap.prototype.createGraphicLayer * @description 添加大数据图层到地图上 * @param {Object} layerInfo - 图层信息 * @param {Array} features - feature的集合 * @return {ol.layer.image} 大数据图层 */ async createGraphicLayer(layerInfo, features) { features = layerInfo.filterCondition ? this.getFiterFeatures(layerInfo.filterCondition, features) : features; let graphics = await this.getGraphicsFromFeatures(features, layerInfo.style, layerInfo.featureType); let source = new Graphic({ graphics: graphics, render: 'canvas', map: this.map, isHighLight: false }); return new external_ol_layer_namespaceObject.Image({ source: source }); } /** * @private * @function WebMap.prototype.getGraphicsFromFeatures * @description 将feature转换成大数据图层对应的Graphics要素 * @param {Array} features - feature的集合 * @param {Object} style - 图层样式 * @param {string} featureType - feature的类型 * @return {Array} 大数据图层要素数组 */ async getGraphicsFromFeatures(features, style, featureType) { let olStyle = await StyleUtils.getOpenlayersStyle(style, featureType), shape = olStyle.getImage(); let graphics = []; //构建graphic for (let i in features) { let graphic = new Graphic_Graphic(features[i].getGeometry()); graphic.setStyle(shape); graphic.setProperties({attributes: features[i].get('attributes')}) graphics.push(graphic); } return graphics; } /** * @private * @function WebMap.prototype.createSymbolLayer * @description 添加符号图层 * @param {Object} layerInfo - 图层信息 * @param {Array} features - feature的集合 * @return {ol.layer.Vector} 符号图层 */ createSymbolLayer(layerInfo, features) { let style = StyleUtils.getSymbolStyle(layerInfo.style); return new external_ol_layer_namespaceObject.Vector({ style: style, source: new (external_ol_source_Vector_default())({ features: layerInfo.filterCondition ? this.getFiterFeatures(layerInfo.filterCondition, features) : features, wrapX: false }), renderMode: 'image' }); } /** * @private * @function WebMap.prototype.addLabelLayer * @description 添加标签图层 * @param {Object} layerInfo - 图层信息 * @param {Array} features -feature的集合 * @returns {ol.layer.Vector} 图层对象 */ addLabelLayer(layerInfo, features) { let labelStyle = layerInfo.labelStyle; let style = this.getLabelStyle(labelStyle, layerInfo); let layer = layerInfo.labelLayer = new external_ol_layer_namespaceObject.Vector({ declutter: true, styleOL: style, labelField: labelStyle.labelField, source: new (external_ol_source_Vector_default())({ features: features, wrapX: false }) }); layer.setStyle(features => { let labelField = labelStyle.labelField; let label = features.get('attributes')[labelField.trim()] + ""; if (label === "undefined") { return null; } let styleOL = layer.get('styleOL'); let text = styleOL.getText(); if (text && text.setText) { text.setText(label); } return styleOL; }); this.map.addLayer(layer); layer.setVisible(layerInfo.visible); layer.setZIndex(1000); const {visibleScale} = layerInfo; visibleScale && this.setVisibleScales(layer, visibleScale); return layer; } /** * @private * @function WebMap.prototype.setVisibleScales * @description 改变图层可视范围 * @param {Object} layer - 图层对象。ol.Layer * @param {Object} visibleScale - 图层样式参数 */ setVisibleScales(layer, visibleScale) { let maxResolution = this.resolutions[visibleScale.minScale], minResolution = this.resolutions[visibleScale.maxScale]; //比例尺和分别率是反比的关系 maxResolution > 1 ? layer.setMaxResolution(Math.ceil(maxResolution)) : layer.setMaxResolution(maxResolution * 1.1); layer.setMinResolution(minResolution); } /** * @private * @function WebMap.prototype.getLabelStyle * @description 获取标签样式 * @param {Object} parameters - 标签图层样式参数 * @param {Object} layerInfo - 图层样式参数 * @returns {ol.style.Style} 标签样式 */ getLabelStyle(parameters, layerInfo) { let style = layerInfo.style || layerInfo.pointStyle; const {radius = 0, strokeWidth = 0} = style, beforeOffsetY = -(radius + strokeWidth); const { fontSize = '14px', fontFamily, fill, backgroundFill, offsetX = 0, offsetY = beforeOffsetY, placement = "point", textBaseline = "bottom", textAlign = 'center', outlineColor = "#000000", outlineWidth = 0 } = parameters; const option = { font: `${fontSize} ${fontFamily}`, placement, textBaseline, fill: new (external_ol_style_Fill_default())({color: fill}), backgroundFill: new (external_ol_style_Fill_default())({color: backgroundFill}), padding: [3, 3, 3, 3], offsetX: layerInfo.featureType === 'POINT' ? offsetX : 0, offsetY: layerInfo.featureType === 'POINT' ? offsetY : 0, overflow: true, maxAngle: 0 }; if (layerInfo.featureType === 'POINT') { //线面不需要此参数,否则超出线面overflow:true,也不会显示标签 option.textAlign = textAlign; } if (outlineWidth > 0) { option.stroke = new (external_ol_style_Stroke_default())({ color: outlineColor, width: outlineWidth }); } return new (external_ol_style_Style_default())({ text: new (external_ol_style_Text_default())(option) }); } /** * @private * @function WebMap.prototype.createVectorLayer * @description 创建vector图层 * @param {Object} layerInfo - 图层信息 * @param {Array} features -feature的集合 * @returns {ol.layer.Vector} 矢量图层 */ async createVectorLayer(layerInfo, features) { const {featureType, style} = layerInfo; let newStyle; if (featureType === 'LINE' && core_Util_Util.isArray(style)) { const [outlineStyle, strokeStyle] = style; newStyle = strokeStyle.lineDash === 'solid' ? StyleUtils.getRoadPath(strokeStyle, outlineStyle) : StyleUtils.getPathway(strokeStyle, outlineStyle); } else { newStyle = await StyleUtils.toOpenLayersStyle(layerInfo.style, layerInfo.featureType); } return new external_ol_layer_namespaceObject.Vector({ style: newStyle, source: new (external_ol_source_Vector_default())({ features: layerInfo.filterCondition ? this.getFiterFeatures(layerInfo.filterCondition, features) : features, wrapX: false }) }); } /** * @private * @function WebMap.prototype.createHeatLayer * @description 创建热力图图层 * @param {Object} layerInfo - 图层信息 * @param {Array} features -feature的集合 * @returns {ol.layer.Heatmap} 热力图图层 */ createHeatLayer(layerInfo, features) { //因为热力图,随着过滤,需要重新计算权重 features = layerInfo.filterCondition ? this.getFiterFeatures(layerInfo.filterCondition, features) : features; let source = new (external_ol_source_Vector_default())({ features: features, wrapX: false }); let layerOptions = { source: source }; let themeSetting = layerInfo.themeSetting; layerOptions.gradient = themeSetting.colors.slice(); layerOptions.radius = parseInt(themeSetting.radius); //自定义颜色 let customSettings = themeSetting.customSettings; for (let i in customSettings) { layerOptions.gradient[i] = customSettings[i]; } // 权重字段恢复 if (themeSetting.weight) { this.changeWeight(features, themeSetting.weight); } return new external_ol_layer_namespaceObject.Heatmap(layerOptions); } /** * @private * @function WebMap.prototype.changeWeight * @description 改变当前权重字段 * @param {Array} features - feature的集合 * @param {string} weightFeild - 权重字段 */ changeWeight(features, weightFeild) { let that = this; this.fieldMaxValue = {}; this.getMaxValue(features, weightFeild); let maxValue = this.fieldMaxValue[weightFeild]; features.forEach(function (feature) { let attributes = feature.get('attributes'); try { let value = attributes[weightFeild]; feature.set('weight', value / maxValue); } catch (e) { that.errorCallback && that.errorCallback(e); } }) } /** * @private * @function WebMap.prototype.getMaxValue * @description 获取当前字段对应的最大值,用于计算权重 * @param {Array} features - feature 数组 * @param {string} weightField - 权重字段 */ getMaxValue(features, weightField) { let values = [], that = this, attributes; let field = weightField; if (this.fieldMaxValue[field]) { return; } features.forEach(function (feature) { //收集当前权重字段对应的所有值 attributes = feature.get('attributes'); try { values.push(parseFloat(attributes[field])); } catch (e) { that.errorCallback && that.errorCallback(e); } }); this.fieldMaxValue[field] = ArrayStatistic.getArrayStatistic(values, 'Maximum'); } /** * @private * @function WebMap.prototype.createUniqueLayer * @description 获取当前字段对应的最大值,用于计算权重 * @param {Object} layerInfo - 图层信息 * @param {Array} features - 所有feature结合 */ async createUniqueLayer(layerInfo, features) { let styleSource = await this.createUniqueSource(layerInfo, features); let layer = new external_ol_layer_namespaceObject.Vector({ styleSource: styleSource, source: new (external_ol_source_Vector_default())({ features: layerInfo.filterCondition ? this.getFiterFeatures(layerInfo.filterCondition, features) : features, wrapX: false }) }); layer.setStyle(feature => { let styleSource = layer.get('styleSource'); let labelField = styleSource.themeField; let label = feature.get('attributes')[labelField]; let styleGroup = styleSource.styleGroups.find(item => { return item.value === label; }) return styleGroup.olStyle; }); return layer; } /** * @private * @function WebMap.prototype.createUniqueSource * @description 创建单值图层的source * @param {Object} parameters- 图层信息 * @param {Array} features - feature 数组 * @returns {{map: *, style: *, isHoverAble: *, highlightStyle: *, themeField: *, styleGroups: Array}} */ async createUniqueSource(parameters, features) { //找到合适的专题字段 let styleGroup = await this.getUniqueStyleGroup(parameters, features); return { map: this.map, //必传参数 API居然不提示 style: parameters.style, isHoverAble: parameters.isHoverAble, highlightStyle: parameters.highlightStyle, themeField: parameters.themeSetting.themeField, styleGroups: styleGroup }; } /** * @private * @function WebMap.prototype.getUniqueStyleGroup * @description 获取单值专题图的styleGroup * @param {Object} parameters- 图层信息 * @param {Array} features - feature 数组 * @returns {Array} 单值样式 */ async getUniqueStyleGroup(parameters, features) { // 找出所有的单值 let featureType = parameters.featureType, style = parameters.style, themeSetting = parameters.themeSetting; let fieldName = themeSetting.themeField; let names = [], customSettings = themeSetting.customSettings; for (let i in features) { let attributes = features[i].get('attributes'); let name = attributes[fieldName]; let isSaved = false; for (let j in names) { if (names[j] === name) { isSaved = true; break; } } if (!isSaved) { names.push(name); } } //生成styleGroup let styleGroup = []; const usedColors = this.getCustomSettingColors(customSettings, featureType).map(item => item.toLowerCase()); const curentColors = this.getUniqueColors(themeSetting.colors || this.defaultParameters.themeSetting.colors, names.length + Object.keys(customSettings).length).map(item => item.toLowerCase()); const newColors = lodash_difference_default()(curentColors, usedColors); for(let index = 0; index < names.length; index++) { const name = names[index]; //兼容之前自定义是用key,现在因为数据支持编辑,需要用属性值。 let key = this.webMapVersion === "1.0" ? index : name; let custom = customSettings[key]; if(core_Util_Util.isString(custom)) { //兼容之前自定义只存储一个color custom = this.getCustomSetting(style, custom, featureType); customSettings[key] = custom; } if (!custom) { custom = this.getCustomSetting(style, newColors.shift(), featureType); } // 转化成 ol 样式 let olStyle, type = custom.type; if(type === 'SYMBOL_POINT') { olStyle = StyleUtils.getSymbolStyle(custom); } else if(type === 'SVG_POINT') { olStyle = await StyleUtils.getSVGStyle(custom); } else if(type === 'IMAGE_POINT') { olStyle = StyleUtils.getImageStyle(custom); } else { olStyle = await StyleUtils.toOpenLayersStyle(custom, featureType); } styleGroup.push({ olStyle: olStyle, style: customSettings[key], value: name }); } return styleGroup; } /** * @description 获取单值专题图自定义样式对象 * @param {Object} style - 图层上的样式 * @param {string} color - 单值对应的颜色 * @param {string} featureType - 要素类型 */ getCustomSetting(style, color, featureType) { let newProps = {}; if (featureType === "LINE") { newProps.strokeColor = color; } else { newProps.fillColor = color; } let customSetting = Object.assign(style, newProps) return customSetting; } getCustomSettingColors(customSettings, featureType) { const keys = Object.keys(customSettings); const colors = []; keys.forEach(key => { //兼容之前自定义只存储一个color if (core_Util_Util.isString(customSettings[key])) { colors.push(customSettings[key]); return; } if (featureType === "LINE") { colors.push(customSettings[key].strokeColor); } else { colors.push(customSettings[key].fillColor); } }); return colors; } getUniqueColors(colors, valuesLen) { return ColorsPickerUtil.getGradientColors(colors, valuesLen); } /** * @private * @function WebMap.prototype.createRangeLayer * @description 创建分段图层 * @param {Object} layerInfo- 图层信息 * @param {Array} features - 所有feature结合 * @returns {ol.layer.Vector} 单值图层 */ async createRangeLayer(layerInfo, features) { //这里获取styleGroup要用所以的feature let styleSource = await this.createRangeSource(layerInfo, features); let layer = new external_ol_layer_namespaceObject.Vector({ styleSource: styleSource, source: new (external_ol_source_Vector_default())({ features: layerInfo.filterCondition ? this.getFiterFeatures(layerInfo.filterCondition, features) : features, wrapX: false }) }); layer.setStyle(feature => { let styleSource = layer.get('styleSource'); if (styleSource) { let labelField = styleSource.themeField; let value = Number(feature.get('attributes')[labelField.trim()]); let styleGroups = styleSource.styleGroups; for (let i = 0; i < styleGroups.length; i++) { if (i === 0) { if (value >= styleGroups[i].start && value <= styleGroups[i].end) { return styleGroups[i].olStyle; } } else { if (value > styleGroups[i].start && value <= styleGroups[i].end) { return styleGroups[i].olStyle; } } } } }); return layer; } /** * @private * @function WebMap.prototype.createRangeSource * @description 创建分段专题图的图层source * @param {Object} parameters- 图层信息 * @param {Array} features - 所以的feature集合 * @returns {Object} 图层source */ async createRangeSource(parameters, features) { //找到合适的专题字段 let styleGroup = await this.getRangeStyleGroup(parameters, features); if (styleGroup) { return { style: parameters.style, themeField: parameters.themeSetting.themeField, styleGroups: styleGroup }; } else { return false; } } /** * @private * @function WebMap.prototype.getRangeStyleGroup * @description 获取分段专题图的styleGroup样式 * @param {Object} parameters- 图层信息 * @param {Array} features - 所以的feature集合 * @returns {Array} styleGroups */ async getRangeStyleGroup(parameters, features) { // 找出分段值 let featureType = parameters.featureType, themeSetting = parameters.themeSetting, style = parameters.style; let count = themeSetting.segmentCount, method = themeSetting.segmentMethod, colors = themeSetting.colors, customSettings = themeSetting.customSettings, fieldName = themeSetting.themeField; let values = [], attributes; let segmentCount = count; let segmentMethod = method; let that = this; features.forEach(function (feature) { attributes = feature.get("attributes"); try { if (attributes) { //过滤掉非数值的数据 let value = attributes[fieldName.trim()]; if (value !== undefined && value !== null && core_Util_Util.isNumber(value)) { values.push(parseFloat(value)); } } else if (feature.get(fieldName) && core_Util_Util.isNumber(feature.get(fieldName))) { if (feature.get(fieldName)) { values.push(parseFloat(feature.get(fieldName))); } } } catch (e) { that.errorCallback && that.errorCallback(e); } }); let segements; try { segements = ArrayStatistic.getArraySegments(values, segmentMethod, segmentCount); } catch (e) { that.errorCallback && that.errorCallback(e); } if (segements) { let itemNum = segmentCount; if (attributes && segements[0] === segements[attributes.length - 1]) { itemNum = 1; segements.length = 2; } //保留两位有效数 for (let key in segements) { let value = segements[key]; if (Number(key) === 0) { // 最小的值下舍入,要用两个等于号。否则有些值判断不对 value = Math.floor(value * 100) / 100; } else { // 其余上舍入 value = Math.ceil(value * 100) / 100 + 0.1; // 加0.1 解决最大值没有样式问题 } segements[key] = Number(value.toFixed(2)); } //获取一定量的颜色 let curentColors = colors; curentColors = ColorsPickerUtil.getGradientColors(curentColors, itemNum, 'RANGE'); for (let index = 0; index < itemNum; index++) { if (index in customSettings) { if (customSettings[index]["segment"]["start"]) { segements[index] = customSettings[index]["segment"]["start"]; } if (customSettings[index]["segment"]["end"]) { segements[index + 1] = customSettings[index]["segment"]["end"]; } } } //生成styleGroup let styleGroups = []; for (let i = 0; i < itemNum; i++) { let color = curentColors[i]; if (i in customSettings) { if (customSettings[i].color) { color = customSettings[i].color; } } if (featureType === "LINE") { style.strokeColor = color; } else { style.fillColor = color; } // 转化成 ol 样式 let olStyle = await StyleUtils.toOpenLayersStyle(style, featureType); let start = segements[i]; let end = segements[i + 1]; styleGroups.push({ olStyle: olStyle, color: color, start: start, end: end }); } return styleGroups; } else { return false; } } /** * @private * @function WebMap.prototype.createMarkerLayer * @description 创建标注图层 * @param {Array} features - 所以的feature集合 * @returns {ol.layer.Vector} 矢量图层 */ async createMarkerLayer(features) { features && await this.setEachFeatureDefaultStyle(features); return new external_ol_layer_namespaceObject.Vector({ source: new (external_ol_source_Vector_default())({ features: features, wrapX: false }) }); } /** * @private * @function WebMap.prototype.createDataflowLayer * @description 创建数据流图层 * @param {Object} layerInfo- 图层信息 * @param {number} layerIndex - 图层的zindex * @returns {ol.layer.Vector} 数据流图层 */ async createDataflowLayer(layerInfo, layerIndex) { let layerStyle = layerInfo.pointStyle, style; //获取样式 style = await StyleUtils.getOpenlayersStyle(layerStyle, layerInfo.featureType); let source = new (external_ol_source_Vector_default())({ wrapX: false }), labelLayer, labelSource, pathLayer, pathSource; let layer = new external_ol_layer_namespaceObject.Vector({ styleOL: style, source: source }); if (layerInfo.labelStyle && layerInfo.visible) { //有标签图层 labelLayer = this.addLabelLayer(layerInfo); //和编辑页面保持一致 labelLayer.setZIndex(1000); labelSource = labelLayer.getSource(); } const {visibleScale} = layerInfo; if (layerInfo.lineStyle && layerInfo.visible) { pathLayer = await this.createVectorLayer({style: layerInfo.lineStyle, featureType: "LINE"}); pathSource = pathLayer.getSource(); pathLayer.setZIndex(layerIndex); this.map.addLayer(pathLayer); visibleScale && this.setVisibleScales(pathLayer, visibleScale); // 挂载到layerInfo上,便于删除 layerInfo.pathLayer = pathLayer; } let featureCache = {}, labelFeatureCache = {}, pathFeatureCache = {}, that = this; this.createDataflowService(layerInfo, function (featureCache, labelFeatureCache, pathFeatureCache) { return function (feature) { that.events.triggerEvent('updateDataflowFeature', { feature: feature, identifyField: layerInfo.identifyField, layerID: layerInfo.layerID }); if (layerInfo.filterCondition) { //过滤条件 const condition = that.parseFilterCondition(layerInfo.filterCondition); const properties = feature.get('attributes'); const conditions = parseCondition(condition, Object.keys(properties)); const filterFeature = parseConditionFeature(properties); const sql = 'select * from json where (' + conditions + ')'; let filterResult = window.jsonsql.query(sql, { attributes: filterFeature }); if (filterResult && filterResult.length > 0) { that.addDataflowFeature(feature, layerInfo.identifyField, { dataflowSource: source, featureCache: featureCache, labelSource: labelSource, labelFeatureCache: labelFeatureCache, pathSource: pathSource, pathFeatureCache: pathFeatureCache, maxPointCount: layerInfo.maxPointCount }); } } else { that.addDataflowFeature(feature, layerInfo.identifyField, { dataflowSource: source, featureCache: featureCache, labelSource: labelSource, labelFeatureCache: labelFeatureCache, pathSource: pathSource, pathFeatureCache: pathFeatureCache, maxPointCount: layerInfo.maxPointCount }); } } }(featureCache, labelFeatureCache, pathFeatureCache)); this.setFeatureStyle(layer, layerInfo.directionField, layerStyle.type); return layer; } /** * @private * @function WebMap.prototype.addDataflowFeature * @description 添加数据流的feature * @param {Object} feature - 服务器更新的feature * @param {string} identifyField - 标识feature的字段 * @param {Object} options - 其他参数 */ addDataflowFeature(feature, identifyField, options) { options.dataflowSource && this.addFeatureFromDataflowService(options.dataflowSource, feature, identifyField, options.featureCache); options.labelSource && this.addFeatureFromDataflowService(options.labelSource, feature, identifyField, options.labelFeatureCache); options.pathSource && this.addPathFeature(options.pathSource, feature, identifyField, options.pathFeatureCache, options.maxPointCount); } /** * @private * @function WebMap.prototype.addPathFeature * @description 添加数据流图层中轨迹线的feature * @param {Object} source - 轨迹线图层的source * @param {Object} feature - 轨迹线feature * @param {string} identifyField - 标识feature的字段 * @param {Object} featureCache - 存储feature * @param {number} maxPointCount - 轨迹线最多点个数数量 */ addPathFeature(source, feature, identifyField, featureCache, maxPointCount) { let coordinates = []; var geoID = feature.get(identifyField); if (featureCache[geoID]) { //加过feautre coordinates = featureCache[geoID].getGeometry().getCoordinates(); coordinates.push(feature.getGeometry().getCoordinates()); if (maxPointCount && coordinates.length > maxPointCount) { coordinates.splice(0, coordinates.length - maxPointCount); } featureCache[geoID].getGeometry().setCoordinates(coordinates); } else { coordinates.push(feature.getGeometry().getCoordinates()); featureCache[geoID] = new (external_ol_Feature_default())({ geometry: new external_ol_geom_namespaceObject.LineString(coordinates) }); source.addFeature(featureCache[geoID]); } } /** * @private * @function WebMap.prototype.setFeatureStyle * @description 设置feature样式 * @param {Object} layer - 图层对象 * @param {string} directionField - 方向字段 * @param {string} styleType - 样式的类型 */ setFeatureStyle(layer, directionField, styleType) { let layerStyle = layer.get('styleOL'); layer.setStyle(feature => { //有转向字段 let value, image; if (directionField !== undefined && directionField !== "未设置" && directionField !== "None") { value = feature.get('attributes')[directionField]; } else { value = 0; } if (value > 360 || value < 0) { return null; } if (styleType === "SYMBOL_POINT") { image = layerStyle.getText(); } else { image = layerStyle.getImage(); } //默认用户使用的是角度,换算成弧度 let rotate = (Math.PI * value) / 180; image && image.setRotation(rotate); return layerStyle; }); } /** * @private * @function WebMap.prototype.createDataflowHeatLayer * @description 创建数据流服务的热力图图层 * @param {Object} layerInfo - 图层参数 * @returns {ol.layer.Heatmap} 热力图图层对象 */ createDataflowHeatLayer(layerInfo) { let source = this.createDataflowHeatSource(layerInfo); let layerOptions = { source: source }; layerOptions.gradient = layerInfo.themeSetting.colors.slice(); layerOptions.radius = parseInt(layerInfo.themeSetting.radius); if (layerInfo.themeSetting.customSettings) { let customSettings = layerInfo.themeSetting.customSettings; for (let i in customSettings) { layerOptions.gradient[i] = customSettings[i]; } } return new external_ol_layer_namespaceObject.Heatmap(layerOptions); } /** * @private * @function WebMap.prototype.createDataflowHeatSource * @description 创建数据流服务的热力图的source * @param {Object} layerInfo - 图层参数 * @returns {ol.souce.Vector} 热力图source对象 */ createDataflowHeatSource(layerInfo) { let that = this, source = new (external_ol_source_Vector_default())({ wrapX: false }); let featureCache = {}; this.createDataflowService(layerInfo, function (featureCache) { return function (feature) { if (layerInfo.filterCondition) { //过滤条件 let condition = that.parseFilterCondition(layerInfo.filterCondition); const properties = feature.get('attributes'); const conditions = parseCondition(condition, Object.keys(properties)); const filterFeature = parseConditionFeature(properties); const sql = 'select * from json where (' + conditions + ')'; let filterResult = window.jsonsql.query(sql, { attributes: filterFeature }); if (filterResult && filterResult.length > 0) { that.addDataflowFeature(feature, layerInfo.identifyField, { dataflowSource: source, featureCache: featureCache }); } } else { that.addDataflowFeature(feature, layerInfo.identifyField, { dataflowSource: source, featureCache: featureCache }); } // 权重字段恢复 if (layerInfo.themeSetting.weight) { that.changeWeight(source.getFeatures(), layerInfo.themeSetting.weight); } } }(featureCache)); return source; } /** * @private * @function WebMap.prototype.addFeatureFromDataflowService * @description 将feature添加到数据流图层 * @param {Object} source - 图层对应的source * @param {Object} feature - 需要添加到图层的feature * @param {Object} identifyField - feature的标识字段 * @param {Object} featureCache - 存储已添加到图层的feature对象 */ addFeatureFromDataflowService(source, feature, identifyField, featureCache) { //判断是否有这个feature,存在feature就更新位置。 var geoID = feature.get(identifyField); if (geoID !== undefined && featureCache[geoID]) { /*if(that.addFeatureFinish) { //feature全都加上图层,就缩放范围 MapManager.zoomToExtent(LayerUtil.getBoundsFromFeatures(source.getFeatures())); that.addFeatureFinish = false; }*/ featureCache[geoID].setGeometry(feature.getGeometry()); featureCache[geoID].setProperties(feature.getProperties()); source.changed(); } else { source.addFeature(feature); featureCache[geoID] = feature; } } /** * @private * @function WebMap.prototype.createDataflowService * @description 将feature添加到数据流图层 * @param {Object} layerInfo - 图层参数 * @param {Object} callback - 回调函数 */ createDataflowService(layerInfo, callback) { let that = this; let dataflowService = new DataFlowService(layerInfo.wsUrl).initSubscribe(); dataflowService.on('messageSucceeded', function (e) { let geojson = JSON.parse(e.value.data); let feature = transformTools.readFeature(geojson, { dataProjection: layerInfo.projection || "EPSG:4326", featureProjection: that.baseProjection || 'EPSG:4326' }); feature.setProperties({attributes: geojson.properties}); callback(feature); }); layerInfo.dataflowService = dataflowService; } /** * @private * @function WebMap.prototype.setEachFeatureDefaultStyle * @description 为标注图层上的feature设置样式 * @param {Array} features - 所以的feature集合 */ async setEachFeatureDefaultStyle(features) { let that = this; features = (core_Util_Util.isArray(features) || features instanceof (external_ol_Collection_default())) ? features : [features]; for(let i = 0; i < features.length; i++) { const feature = features[i]; let geomType = feature.getGeometry().getType().toUpperCase(); // let styleType = geomType === "POINT" ? 'MARKER' : geomType; let defaultStyle = feature.getProperties().useStyle; if (defaultStyle) { if (geomType === 'POINT' && defaultStyle.text) { //说明是文字的feature类型 geomType = "TEXT"; } let attributes = that.setFeatureInfo(feature); feature.setProperties({ useStyle: defaultStyle, attributes }); //标注图层的feature上需要存一个layerId,为了之后样式应用到图层上使用 // feature.layerId = timeId; if (geomType === 'POINT' && defaultStyle.src && defaultStyle.src.indexOf('http://') === -1 && defaultStyle.src.indexOf('https://') === -1) { //说明地址不完整 defaultStyle.src = that.server + defaultStyle.src; } } else { defaultStyle = StyleUtils.getMarkerDefaultStyle(geomType, that.server); } feature.setStyle(await StyleUtils.toOpenLayersStyle(defaultStyle, geomType)) } } /** * @private * @function WebMap.prototype.setFeatureInfo * @description 为feature设置属性 * @param {Array} feature - 单个feature * @returns {Object} 属性 */ setFeatureInfo(feature) { let attributes = feature.get('attributes'), defaultAttr = { dataViz_title: '', dataViz_description: '', dataViz_imgUrl: '', dataViz_url: '' }, newAttribute = Object.assign(defaultAttr, attributes); let properties = feature.getProperties(); for (let key in newAttribute) { if (properties[key]) { newAttribute[key] = properties[key]; delete properties[key]; } } return newAttribute; } /** * @private * @function WebMap.prototype.createRankSymbolLayer * @description 创建等级符号图层 * @param {Object} layerInfo - 图层信息 * @param {Array} features - 添加到图层上的features * @returns {ol.layer.Vector} 矢量图层 */ async createRankSymbolLayer(layerInfo, features) { let styleSource = await this.createRankStyleSource(layerInfo, features, layerInfo.featureType); let layer = new external_ol_layer_namespaceObject.Vector({ styleSource, source: new (external_ol_source_Vector_default())({ features: layerInfo.filterCondition ? this.getFiterFeatures(layerInfo.filterCondition, features) : features, wrapX: false }), renderMode: 'image' }); layer.setStyle(feature => { let styleSource = layer.get('styleSource'); let themeField = styleSource.parameters.themeSetting.themeField; let value = Number(feature.get('attributes')[themeField]); let styleGroups = styleSource.styleGroups; for (let i = 0, len = styleGroups.length; i < len; i++) { if (value >= styleGroups[i].start && value < styleGroups[i].end) { return styleSource.styleGroups[i].olStyle; } } }); return layer; } /** * @private * @function WebMap.prototype.createRankSymbolLayer * @description 创建等级符号图层的source * @param {Object} parameters - 图层信息 * @param {Array} features - 添加到图层上的features * @param {string} featureType - feature的类型 * @returns {Object} styleGroups */ async createRankStyleSource(parameters, features, featureType) { let themeSetting = parameters.themeSetting, themeField = themeSetting.themeField; let styleGroups = await this.getRankStyleGroup(themeField, features, parameters, featureType); return styleGroups ? {parameters, styleGroups} : false } /** * @private * @function WebMap.prototype.getRankStyleGroup * @description 获取等级符号的style * @param {string} themeField - 分段字段 * @param {Array} features - 添加到图层上的features * @param {Object} parameters - 图层参数 * @param {string} featureType - feature的类型 * @returns {Array} stylegroup */ async getRankStyleGroup(themeField, features, parameters, featureType) { // 找出所有的单值 let values = [], segements = [], style = parameters.style, themeSetting = parameters.themeSetting, segmentMethod = themeSetting.segmentMethod || this.defaultParameters.themeSetting.segmentMethod, segmentCount = themeSetting.segmentCount || this.defaultParameters.themeSetting.segmentCount, customSettings = themeSetting.customSettings, minR = parameters.themeSetting.minRadius, maxR = parameters.themeSetting.maxRadius, fillColor = style.fillColor, colors = parameters.themeSetting.colors; features.forEach(feature => { let attributes = feature.get('attributes'), value = attributes[themeField]; // 过滤掉空值和非数值 if (value == null || !core_Util_Util.isNumber(value)) { return; } values.push(Number(value)); }); try { segements = ArrayStatistic.getArraySegments(values, segmentMethod, segmentCount); } catch (error) { console.error(error); } // 处理自定义 分段 for (let i = 0; i < segmentCount; i++) { if (i in customSettings) { let startValue = customSettings[i]['segment']['start'], endValue = customSettings[i]['segment']['end']; startValue != null && (segements[i] = startValue); endValue != null && (segements[i + 1] = endValue); } } //生成styleGroup let styleGroup = []; if (segements && segements.length) { let len = segements.length, incrementR = (maxR - minR) / (len - 1), // 半径增量 start, end, radius = Number(((maxR + minR) / 2).toFixed(2)); // 获取颜色 let rangeColors = colors ? ColorsPickerUtil.getGradientColors(colors, len, 'RANGE') : []; for (let j = 0; j < len - 1; j++) { start = Number(segements[j].toFixed(2)); end = Number(segements[j + 1].toFixed(2)); // 这里特殊处理以下分段值相同的情况(即所有字段值相同) radius = start === end ? radius : minR + Math.round(incrementR * j); // 最后一个分段时将end+0.01,避免取不到最大值 end = j === len - 2 ? end + 0.01 : end; // 处理自定义 半径 radius = customSettings[j] && customSettings[j].radius ? customSettings[j].radius : radius; // 转化成 ol 样式 style.radius = radius; style.fillColor = customSettings[j] && customSettings[j].color ? customSettings[j].color : rangeColors[j] || fillColor; let olStyle = await StyleUtils.getOpenlayersStyle(style, featureType, true); styleGroup.push({olStyle: olStyle, radius, start, end, fillColor: style.fillColor}); } return styleGroup; } else { return false; } } /** * @private * @function WebMap.prototype.checkUploadToRelationship * @description 检查是否上传到关系型 * @param {string} fileId - 文件的id * @returns {Promise} 关系型文件一些参数 */ checkUploadToRelationship(fileId) { let url = this.getRequestUrl(`${this.server}web/datas/${fileId}/datasets.json`); return FetchRequest.get(url, null, { withCredentials: this.withCredentials }).then(function (response) { return response.json() }).then(function (result) { return result; }); } /** * @private * @function WebMap.prototype.getDatasources * @description 获取关系型文件发布的数据服务中数据源的名称 * @param {string} url - 获取数据源信息的url * @returns {Promise} 数据源名称 */ getDatasources(url) { let requestUrl = this.getRequestUrl(`${url}/data/datasources.json`); return FetchRequest.get(requestUrl, null, { withCredentials: this.withCredentials }).then(function (response) { return response.json() }).then(function (datasource) { let datasourceNames = datasource.datasourceNames; return datasourceNames[0]; }); } /** * @private * @function WebMap.prototype.getDataService * @description 获取上传的数据信息 * @param {string} fileId - 文件id * @param {string} datasetName 数据服务的数据集名称 * @returns {Promise} 数据的信息 */ getDataService(fileId, datasetName) { let url = this.getRequestUrl(`${this.server}web/datas/${fileId}.json`); return FetchRequest.get(url, null, { withCredentials: this.withCredentials }).then(function (response) { return response.json() }).then(function (result) { result.fileId = fileId; result.datasetName = datasetName; return result; }); } /** * @private * @function WebMap.prototype.getRootUrl * @description 获取请求地址 * @param {string} url 请求的地址 * @param {boolean} 请求是否带上Credential. * @returns {Promise} 请求地址 */ getRequestUrl(url, excludeCreditial) { url = excludeCreditial ? url : this.formatUrlWithCredential(url); //如果传入进来的url带了代理则不需要处理 if (this.excludePortalProxyUrl) { return; } return Util.isInTheSameDomain(url) ? url : `${this.getProxy()}${encodeURIComponent(url)}`; } /** * @description 给url带上凭证密钥 * @param {string} url - 地址 */ formatUrlWithCredential(url) { if (this.credentialValue) { //有token之类的配置项 url = url.indexOf("?") === -1 ? `${url}?${this.credentialKey}=${this.credentialValue}` : `${url}&${this.credentialKey}=${this.credentialValue}`; } return url; } /** * @private * @function WebMap.prototype.getProxy * @description 获取代理地址 * @returns {Promise} 代理地址 */ getProxy(type) { if (!type) { type = 'json'; } return this.proxy || this.server + `apps/viewer/getUrlResource.${type}?url=`; } /** * @private * @function WebMap.prototype.getTileLayerInfo * @description 获取地图服务的信息 * @param {string} url 地图服务的url(没有地图名字) * @returns {Promise} 地图服务信息 */ getTileLayerInfo(url) { let that = this, epsgCode = that.baseProjection.split('EPSG:')[1]; let requestUrl = that.getRequestUrl(`${url}/maps.json`); return FetchRequest.get(requestUrl, null, { withCredentials: this.withCredentials }).then(function (response) { return response.json() }).then(function (mapInfo) { let promises = []; if (mapInfo) { mapInfo.forEach(function (info) { let mapUrl = that.getRequestUrl(`${info.path}.json?prjCoordSys=${encodeURI(JSON.stringify({epsgCode: epsgCode}))}`) let promise = FetchRequest.get(mapUrl, null, { withCredentials: that.withCredentials }).then(function (response) { return response.json() }).then(function (restMapInfo) { restMapInfo.url = info.path; return restMapInfo }); promises.push(promise); }); } return Promise.all(promises).then(function (allRestMaps) { return allRestMaps }) }); } /** * 通过wkt参数扩展支持多坐标系 * * @param {string} wkt 字符串 * @param {string} crsCode epsg信息,如: "EPSG:4490" * * @returns {boolean} 坐标系是否添加成功 */ addProjctionFromWKT(wkt, crsCode) { if (typeof (wkt) !== 'string') { //参数类型错误 return false; } else { if (wkt === "EPSG:4326" || wkt === "EPSG:3857") { return true; } else { let epsgCode = crsCode || this.getEpsgInfoFromWKT(wkt); if (epsgCode) { proj4_src_default().defs(epsgCode, wkt); // 重新注册proj4到ol.proj,不然不会生效 if (external_ol_proj_proj4_namespaceObject && external_ol_proj_proj4_namespaceObject.register) { external_ol_proj_proj4_namespaceObject.register((proj4_src_default())); } else if (window.ol.proj && window.ol.proj.setProj4) { window.ol.proj.setProj4((proj4_src_default())) } return true; } else { // 参数类型非wkt标准 return false; } } } } /** * 通过wkt参数获取坐标信息 * * @param {string} wkt 字符串 * @returns {string} epsg 如:"EPSG:4326" */ getEpsgInfoFromWKT(wkt) { if (typeof (wkt) !== 'string') { return false; } else if (wkt.indexOf("EPSG") === 0) { return wkt; } else { let lastAuthority = wkt.lastIndexOf("AUTHORITY") + 10, endString = wkt.indexOf("]", lastAuthority) - 1; if (lastAuthority > 0 && endString > 0) { return `EPSG:${wkt.substring(lastAuthority, endString).split(",")[1].substr(1)}`; } else { return false; } } } /** * @private * @function WebMap.prototype.createMigrationLayer * @description 创建迁徙图 * @param {Object} layerInfo 图层信息 * @param {Array} features 要素数组 * @returns {ol.layer} 图层 */ createMigrationLayer(layerInfo, features) { // 获取图层外包DOM if (!window.EChartsLayer.prototype.getContainer) { window.EChartsLayer.prototype.getContainer = function () { return this.$container; }; } // 设置图层可见性 if (!window.EChartsLayer.prototype.setVisible) { window.EChartsLayer.prototype.setVisible = function (visible) { if (visible) { let options = this.get('options'); if (options) { this.setChartOptions(options); this.unset('options'); } } else { let options = this.getChartOptions(); this.set('options', options); this.clear(); this.setChartOptions({}); } }; } // 设置图层层级 if (!window.EChartsLayer.prototype.setZIndex) { window.EChartsLayer.prototype.setZIndex = function (zIndex) { let container = this.getContainer(); if (container) { container.style.zIndex = zIndex; } }; } /** * 设置鼠标样式 * .cursor-default > div { * cursor: default !important; * } */ if (!window.EChartsLayer.prototype.setCursor) { window.EChartsLayer.prototype.setCursor = function (cursor = 'default') { let container = this.getContainer(); if (container && cursor === 'default') { container.classList.add('cursor-default'); } } } let properties = getFeatureProperties(features); let lineData = this.createLinesData(layerInfo, properties); let pointData = this.createPointsData(lineData, layerInfo, properties); let options = this.createOptions(layerInfo, lineData, pointData); let layer = new window.EChartsLayer(options, { // hideOnMoving: true, // hideOnZooming: true //以下三个参数,如果不按照这样设置,会造成不可见图层时,缩放还会出现图层 hideOnMoving: false, hideOnZooming: false, forcedPrecomposeRerender: true }); layer.type = 'ECHARTS'; return layer; } /** * @private * @function WebMap.prototype.createOptions * @description 创建echarts的options * @param {Object} layerInfo 图层信息 * @param {Array} lineData 线数据 * @param {Array} pointData 点数据 * @returns {Object} echarts参数 */ createOptions(layerInfo, lineData, pointData) { let series; let lineSeries = this.createLineSeries(layerInfo, lineData); if (pointData && pointData.length) { let pointSeries = this.createPointSeries(layerInfo, pointData); series = lineSeries.concat(pointSeries); } else { series = lineSeries.slice(); } let options = { series } return options; } /** * @private * @function WebMap.prototype.createLineSeries * @description 创建线系列 * @param {Object} layerInfo 图层参数 * @param {Array} lineData 线数据 * @returns {Object} 线系列 */ createLineSeries(layerInfo, lineData) { let lineSetting = layerInfo.lineSetting; let animationSetting = layerInfo.animationSetting; let linesSeries = [ // 轨迹线样式 { name: 'line-series', type: 'lines', zlevel: 1, silent: true, effect: { show: animationSetting.show, constantSpeed: animationSetting.constantSpeed, trailLength: 0, symbol: animationSetting.symbol, symbolSize: animationSetting.symbolSize }, lineStyle: { normal: { color: lineSetting.color, type: lineSetting.type, width: lineSetting.width, opacity: lineSetting.opacity, curveness: lineSetting.curveness } }, data: lineData } ]; if (lineData.length > MAX_MIGRATION_ANIMATION_COUNT) { // linesSeries[0].large = true; // linesSeries[0].largeThreshold = 100; linesSeries[0].blendMode = 'lighter'; } return linesSeries; } /** * @private * @function WebMap.prototype.createPointSeries * @description 创建点系列 * @param {Object} layerInfo 图层参数 * @param {Array} pointData 点数据 * @returns {Object} 点系列 */ createPointSeries(layerInfo, pointData) { let lineSetting = layerInfo.lineSetting; let animationSetting = layerInfo.animationSetting; let labelSetting = layerInfo.labelSetting; let pointSeries = [{ name: 'point-series', coordinateSystem: 'geo', zlevel: 2, silent: true, label: { normal: { show: labelSetting.show, position: 'right', formatter: '{b}', color: labelSetting.color, fontFamily: labelSetting.fontFamily } }, itemStyle: { normal: { color: lineSetting.color || labelSetting.color } }, data: pointData }] if (animationSetting.show) { // 开启动画 pointSeries[0].type = 'effectScatter'; pointSeries[0].rippleEffect = { brushType: 'stroke' } } else { // 关闭动画 pointSeries[0].type = 'scatter'; } return pointSeries; } /** * @private * @function WebMap.prototype.createPointsData * @param {Array} lineData 线数据 * @param {Object} layerInfo 图层信息 * @param {Array} properties 属性 * @returns {Array} 点数据 */ createPointsData(lineData, layerInfo, properties) { let data = [], labelSetting = layerInfo.labelSetting; // 标签隐藏则直接返回 if (!labelSetting.show || !lineData.length) { return data; } let fromData = [], toData = []; lineData.forEach((item, idx) => { let coords = item.coords, fromCoord = coords[0], toCoord = coords[1], fromProperty = properties[idx][labelSetting.from], toProperty = properties[idx][labelSetting.to]; // 起始字段去重 let f = fromData.find(d => { return d.value[0] === fromCoord[0] && d.value[1] === fromCoord[1] }); !f && fromData.push({ name: fromProperty, value: fromCoord }) // 终点字段去重 let t = toData.find(d => { return d.value[0] === toCoord[0] && d.value[1] === toCoord[1] }); !t && toData.push({ name: toProperty, value: toCoord }) }); data = fromData.concat(toData); return data; } /** * @private * @function WebMap.prototype.createLinesData * @param {Object} layerInfo 图层信息 * @param {Array} properties 属性 * @returns {Array} 线数据 */ createLinesData(layerInfo, properties) { let data = []; if (properties && properties.length) { // 重新获取数据 let from = layerInfo.from, to = layerInfo.to, fromCoord, toCoord; if (from.type === 'XY_FIELD' && from['xField'] && from['yField'] && to['xField'] && to['yField']) { properties.forEach(property => { let fromX = property[from['xField']], fromY = property[from['yField']], toX = property[to['xField']], toY = property[to['yField']]; if (!fromX || !fromY || !toX || !toY) { return; } fromCoord = [property[from['xField']], property[from['yField']]]; toCoord = [property[to['xField']], property[to['yField']]]; data.push({ coords: [fromCoord, toCoord] }) }); } else if (from.type === 'PLACE_FIELD' && from['field'] && to['field']) { const centerDatas = ProvinceCenter_namespaceObject.concat(MunicipalCenter_namespaceObject); properties.forEach(property => { let fromField = property[from['field']], toField = property[to['field']]; fromCoord = centerDatas.find(item => { return core_Util_Util.isMatchAdministrativeName(item.name, fromField); }) toCoord = centerDatas.find(item => { return core_Util_Util.isMatchAdministrativeName(item.name, toField); }) if (!fromCoord || !toCoord) { return; } data.push({ coords: [fromCoord.coord, toCoord.coord] }) }); } } return data; } /** * @private * @function WebMap.prototype.getService * @description 获取当前数据发布的服务中的某种类型服务 * @param {Array.} services 服务集合 * @param {string} type 服务类型,RESTDATA, RESTMAP * @returns {Object} 服务 */ getService(services, type) { let service = services.filter((info) => { return info && info.serviceType === type; }); return service[0]; } /** * @private * @function WebMap.prototype.isMvt * @description 判断当前能否使用数据服务的mvt上图方式 * @param {string} serviceUrl 数据服务的地址 * @param {string} datasetName 数据服务的数据集名称 * @returns {Object} 数据服务的信息 */ isMvt(serviceUrl, datasetName) { let that = this; return this.getDatasetsInfo(serviceUrl, datasetName).then((info) => { //判断是否和底图坐标系一直 if (info.epsgCode == that.baseProjection.split('EPSG:')[1]) { return FetchRequest.get(that.getRequestUrl(`${info.url}/tilefeature.mvt`), null, { withCredentials: that.withCredentials }).then(function (response) { return response.json() }).then(function (result) { info.isMvt = result.error && result.error.code === 400; return info; }).catch(() => { return info; }); } return info; }) } /** * @private * @function WebMap.prototype.getDatasetsInfo * @description 获取数据集信息 * @param {string} serviceUrl 数据服务的地址 * @param {string} datasetName 数据服务的数据集名称 * @returns {Object} 数据服务的信息 */ getDatasetsInfo(serviceUrl, datasetName) { let that = this; return that.getDatasources(serviceUrl).then(function (datasourceName) { //判断mvt服务是否可用 let url = `${serviceUrl}/data/datasources/${datasourceName}/datasets/${datasetName}.json`; return FetchRequest.get(that.getRequestUrl(url), null, { withCredentials: that.withCredentials }).then(function (response) { return response.json() }).then(function (datasetsInfo) { return { epsgCode: datasetsInfo.datasetInfo.prjCoordSys.epsgCode, bounds: datasetsInfo.datasetInfo.bounds, url //返回的是原始url,没有代理。因为用于请求mvt }; }); }) } /** * @private * @function WebMap.prototype.isRestMapMapboxStyle * @description 仅判断是否为restmap mvt地图服务 rest-map服务的Mapbox Style资源地址是这样的: .../iserver/services/map-Population/rest/maps/PopulationDistribution/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true * @param {Object} layerInfo webmap中的MapStylerLayer * @returns {boolean} 是否为restmap mvt地图服务 */ isRestMapMapboxStyle(layerInfo) { const restMapMVTStr = '/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true&tileURLTemplate=ZXY' let dataSource = layerInfo.dataSource; let layerType = layerInfo.layerType; if (dataSource && dataSource.type === "EXTERNAL" && dataSource.url.indexOf(restMapMVTStr) > -1 && (layerType === "MAPBOXSTYLE" || layerType === "VECTOR_TILE")) { return true } return false } /** * @private * @function WebMap.prototype.getMapboxStyleLayerInfo * @description 获取mapboxstyle图层信息 * @param {Object} layerInfo 图层信息 * @returns {Object} 图层信息 */ getMapboxStyleLayerInfo(mapInfo, layerInfo) { let _this = this; return new Promise((resolve, reject) => { return _this.getMapLayerExtent(layerInfo).then(layer => { return _this.getMapboxStyle(mapInfo, layer).then(styleLayer => { Object.assign(layer, styleLayer); resolve(layer) }).catch(error => { reject(error); }) }).catch(error => { reject(error); }) }) } /** * @private * @function WebMap.prototype.getMapLayerExtent * @description 获取mapboxstyle图层信息 * @param {Object} layerInfo 图层信息 * @returns {Object} 图层信息 */ getMapLayerExtent(layerInfo) { const restMapMVTStr = '/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true&tileURLTemplate=ZXY' let dataSource = layerInfo.dataSource; let url = dataSource.url; if (this.isRestMapMapboxStyle(layerInfo)) { url = url.replace(restMapMVTStr, '') } url = this.getRequestUrl(url + '.json') let credential = layerInfo.credential; let credentialValue,keyfix; //携带令牌(restmap用的首字母大写,但是这里要用小写) if (credential) { keyfix = Object.keys(credential)[0] credentialValue = credential[keyfix]; url = `${url}?${keyfix}=${credentialValue}`; } return FetchRequest.get(url, null, { withCredentials: this.withCredentials, withoutFormatSuffix: true, headers: { 'Content-Type': 'application/json;chartset=uft-8' } }).then(function (response) { return response.json(); }).then((result) => { layerInfo.visibleScales = result.visibleScales; layerInfo.coordUnit = result.coordUnit; layerInfo.scale = result.scale; layerInfo.epsgCode = result.prjCoordSys.epsgCode; layerInfo.bounds = result.bounds; return layerInfo; }).catch(error => { throw error; }) } /** * @private * @function WebMap.prototype.getMapboxStyle * @description 获取mapboxstyle --- ipt中自定义底图请求mapboxstyle目前有两种url格式 * rest-map服务的Mapbox Style资源地址是这样的: .../iserver/services/map-Population/rest/maps/PopulationDistribution/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true * restjsr片服务的Mapbox Style资源地址是这样的:.../iserver/services/map-china400/restjsr/v1/vectortile/maps/China/style.json * @param {Object} mapboxstyle图层信息 * @returns {Object} 图层信息 */ getMapboxStyle(mapInfo, layerInfo) { let _this = this; let url = layerInfo.url || layerInfo.dataSource.url; let styleUrl = url; if (styleUrl.indexOf('/restjsr/') > -1) { styleUrl = `${styleUrl}/style.json`; } styleUrl = this.getRequestUrl(styleUrl) let credential = layerInfo.credential; //携带令牌(restmap用的首字母大写,但是这里要用小写) let credentialValue, keyfix; if (credential) { keyfix = Object.keys(credential)[0] credentialValue = credential[keyfix]; styleUrl = `${styleUrl}?${keyfix}=${credentialValue}`; } return FetchRequest.get(styleUrl, null, { withCredentials: this.withCredentials, withoutFormatSuffix: true, headers: { 'Content-Type': 'application/json;chartset=uft-8' } }).then(function (response) { return response.json(); }).then(styles => { _this._matchStyleObject(styles); let bounds = layerInfo.bounds; // 处理携带令牌的情况 if (credentialValue) { styles.sprite = `${styles.sprite}?${keyfix}=${credentialValue}`; let sources = styles.sources; let sourcesNames = Object.keys(sources); sourcesNames.forEach(function (sourceName) { styles.sources[sourceName].tiles.forEach(function (tiles, i) { styles.sources[sourceName].tiles[i] = `${tiles}?${keyfix}=${credentialValue}` }) }) } let newLayerInfo = { url: url, sourceType: 'VECTOR_TILE', layerType: 'VECTOR_TILE', styles: styles, extent: bounds && [bounds.left, bounds.bottom, bounds.right, bounds.top], bounds: layerInfo.bounds, projection: "EPSG:" + layerInfo.epsgCode, epsgCode: layerInfo.epsgCode, name: layerInfo.name } Object.assign(layerInfo, newLayerInfo) if (layerInfo.zIndex > 0) { // 过滤styles 非底图mapboxstyle图层才需此处理 _this.modifyMapboxstyleLayer(mapInfo, layerInfo); } return layerInfo; }).catch(error => { return error; }) } /** * @private * @function WebMap.prototype.modifyMapboxstyleLayer * @description mapboxstyle图层:1. layer id重复问题 2.叠加图层背景色问题 * @param {Object} mapInfo 地图信息 * @param {Object} layerInfo 当前要添加到地图的图层 */ modifyMapboxstyleLayer(mapInfo, layerInfo) { let that = this; if (mapInfo.layers && mapInfo.layers.length === 0) {return;} let curLayers = layerInfo.styles.layers; if (!curLayers) {return;} // 非底图,则移除"background"图层 curLayers = curLayers.filter(layer => layer.type !== "background"); layerInfo.styles.layers = curLayers; // 处理mapboxstyle图层layer id重复的情况 let addedLayersArr = mapInfo.layers.filter(layer => layer.layerType === 'VECTOR_TILE' && layer.zIndex !== layerInfo.zIndex) .map(addLayer => addLayer.styles && addLayer.styles.layers); if (!addedLayersArr || addedLayersArr && addedLayersArr.length === 0) {return;} addedLayersArr.forEach(layers => { curLayers.forEach(curLayer => { that.renameLayerId(layers, curLayer); }) }) } /** * @private * @function WebMap.prototype.renameLayerId * @description mapboxstyle图层 id重复的layer添加后缀编码 (n)[参考mapstudio] * @param {mapboxgl.Layer[]} layers 已添加到地图的图层组 * @param {mapboxgl.Layer} curLayer 当前图层 */ renameLayerId(layers, curLayer) { if (layers.find((l) => l.id === curLayer.id)) { const result = curLayer.id.match(/(.+)\((\w)\)$/); if (result) { curLayer.id = `${result[1]}(${+result[2] + 1})`; } else { curLayer.id += '(1)'; } if (layers.find((l) => l.id === curLayer.id)) { this.renameLayerId(layers, curLayer); } } } /** * @private * @function mapboxgl.supermap.WebMap.prototype._matchStyleObject * @description 恢复 style 为标准格式。 * @param {Object} style - mapbox 样式。 */ _matchStyleObject(style) { let {sprite, glyphs} = style; if (sprite && typeof sprite === 'object') { style.sprite = Object.values(sprite)[0]; } if (glyphs && typeof glyphs === 'object') { style.glyphs = Object.values(glyphs)[0]; } } /** * @private * @function WebMap.prototype.renameLayerId * @description 判断url是否是iportal的代理地址 * @param {*} serviceUrl */ isIportalProxyServiceUrl(serviceUrl) { if (this.serviceProxy && this.serviceProxy.enable && serviceUrl) { let proxyStr = ''; if (this.serviceProxy.proxyServerRootUrl) { proxyStr = `${this.serviceProxy.proxyServerRootUrl}/`; } else if (this.serviceProxy.rootUrlPostfix) { proxyStr = `${this.serviceProxy.port}/${this.serviceProxy.rootUrlPostfix}/`; } else if (!this.serviceProxy.rootUrlPostfix) { proxyStr = `${this.serviceProxy.port}/`; } if (this.serviceProxy.port !== 80) { return serviceUrl.indexOf(proxyStr) >= 0; } else { // 代理端口为80,url中不一定有端口,满足一种情况即可 return serviceUrl.indexOf(proxyStr) >= 0 || serviceUrl.indexOf(proxyStr.replace(':80', '')) >= 0; } } else { return false } } /** * @private * @function WebMap.prototype.getStyleResolutions * @description 创建图层分辨率 * @param {Object} bounds 图层上下左右范围 * @returns {Array} styleResolutions 样式分辨率 */ getStyleResolutions(bounds, minZoom = 0, maxZoom = 22) { let styleResolutions = []; const TILE_SIZE = 512 let temp = Math.abs(bounds.left - bounds.right) / TILE_SIZE; for (let i = minZoom; i <= maxZoom; i++) { if (i === 0) { styleResolutions[i] = temp; continue; } temp = temp / 2; styleResolutions[i] = temp; } return styleResolutions; } /** * @private * @function WebMap.prototype.createVisibleResolution * @description 创建图层可视分辨率 * @param {Array.} visibleScales 可视比例尺范围 * @param {Array} indexbounds * @param {Object} bounds 图层上下左右范围 * @param {string} coordUnit * @returns {Array} visibleResolution */ createVisibleResolution(visibleScales, indexbounds, bounds, coordUnit) { let visibleResolution = []; // 1 设置了地图visibleScales的情况 if (visibleScales && visibleScales.length > 0) { visibleResolution = visibleScales.map(scale => { let value = 1 / scale; let res = this.getResFromScale(value, coordUnit); return res; }) } else { // 2 地图的bounds let envelope = this.getEnvelope(indexbounds, bounds); visibleResolution = this.getStyleResolutions(envelope); } return visibleResolution } /** * @private * @function WebMap.prototype.createVisibleResolution * @description 图层边界范围 * @param {Array} indexbounds * @param {Object} bounds 图层上下左右范围 * @returns {Object} envelope */ getEnvelope(indexbounds, bounds) { let envelope = {}; if (indexbounds && indexbounds.length === 4) { envelope.left = indexbounds[0]; envelope.bottom = indexbounds[1]; envelope.right = indexbounds[2]; envelope.top = indexbounds[3]; } else { envelope = bounds; } return envelope } /** * @private * @function WebMap.prototype.createMVTLayer * @description 创建矢量瓦片图层 * @param {Object} layerInfo - 图层信息 */ createMVTLayer(layerInfo) { // let that = this; let styles = layerInfo.styles; const indexbounds = styles && styles.metadata && styles.metadata.indexbounds; const visibleResolution = this.createVisibleResolution(layerInfo.visibleScales, indexbounds, layerInfo.bounds, layerInfo.coordUnit); const envelope = this.getEnvelope(indexbounds, layerInfo.bounds); const styleResolutions = this.getStyleResolutions(envelope); // const origin = [envelope.left, envelope.top]; let withCredentials = this.isIportalProxyServiceUrl(styles.sprite); // 创建MapBoxStyle样式 let mapboxStyles = new MapboxStyles({ style: styles, source: styles.name, resolutions: styleResolutions, map: this.map, withCredentials }); return new Promise((resolve) => { mapboxStyles.on('styleloaded', function () { let minResolution = visibleResolution[visibleResolution.length - 1]; let maxResolution = visibleResolution[0]; let layer = new external_ol_layer_namespaceObject.VectorTile({ //设置避让参数 declutter: true, source: new VectorTileSuperMapRest({ style: styles, withCredentials, projection: layerInfo.projection, format: new (external_ol_format_MVT_default())({ featureClass: (external_ol_render_Feature_default()) }), wrapX: false }), style: mapboxStyles.featureStyleFuntion, visible: layerInfo.visible, zIndex: layerInfo.zIndex, opacity: layerInfo.opacity, minResolution, // The maximum resolution (exclusive) below which this layer will be visible. maxResolution: maxResolution > 1 ? Math.ceil(maxResolution) : maxResolution * 1.1 }); resolve(layer); }) }) } /** * @private * @function WebMap.prototype.isSameDomain * @description 判断是否同域名(如果是域名,只判断后门两级域名是否相同,第一级忽略),如果是ip地址则需要完全相同。 * @param {*} url */ isSameDomain(url) { let documentUrlArray = url.split("://"), substring = documentUrlArray[1]; let domainIndex = substring.indexOf("/"), domain = substring.substring(0, domainIndex); let documentUrl = document.location.toString(); let docUrlArray = documentUrl.split("://"), documentSubstring = docUrlArray[1]; let docuDomainIndex = documentSubstring.indexOf("/"), docDomain = documentSubstring.substring(0, docuDomainIndex); if (domain.indexOf(':') > -1 || window.location.port !== "") { //说明用的是ip地址,判断完整域名判断 return domain === docDomain; } else { let domainArray = domain.split('.'), docDomainArray = docDomain.split('.'); return domainArray[1] === docDomainArray[1] && domainArray[2] === docDomainArray[2]; } } /** * @private * @function WebMap.prototype.isSupportWebp * @description 判断是否支持webP * @param {*} url 服务地址 * @param {*} token 服务token * @returns {boolean} */ isSupportWebp(url, token) { // 还需要判断浏览器 let isIE = this.isIE(); if (isIE || (this.isFirefox() && this.getFirefoxVersion() < 65) || (this.isChrome() && this.getChromeVersion() < 32)) { return false; } url = token ? `${url}/tileImage.webp?token=${token}` : `${url}/tileImage.webp`; let isSameDomain = Util.isInTheSameDomain(url), excledeCreditial; if (isSameDomain && !token) { // online上服务域名一直,要用token值 excledeCreditial = false; } else { excledeCreditial = true; } url = this.getRequestUrl(url, excledeCreditial); return FetchRequest.get(url, null, { withCredentials: this.withCredentials, withoutFormatSuffix: true }).then(function (response) { if (response.status !== 200) { throw response.status; } return response; }).then(() => { return true; }).catch(() => { return false; }) } /** * @private * @function WebMap.prototype.isIE * @description 判断当前浏览器是否为IE * @returns {boolean} */ isIE() { if (!!window.ActiveXObject || "ActiveXObject" in window) { return true; } return false; } /** * @private * @function WebMap.prototype.isFirefox * @description 判断当前浏览器是否为 firefox * @returns {boolean} */ isFirefox() { let userAgent = navigator.userAgent; return userAgent.indexOf("Firefox") > -1; } /** * @private * @function WebMap.prototype.isChrome * @description 判断当前浏览器是否为谷歌 * @returns {boolean} */ isChrome() { let userAgent = navigator.userAgent; return userAgent.indexOf("Chrome") > -1; } /** * @private * @function WebMap.prototype.getFirefoxVersion * @description 获取火狐浏览器的版本号 * @returns {number} */ getFirefoxVersion() { let userAgent = navigator.userAgent.toLowerCase(), version = userAgent.match(/firefox\/([\d.]+)/); return +version[1]; } /** * @private * @function WebMap.prototype.getChromeVersion * @description 获取谷歌浏览器版本号 * @returns {number} */ getChromeVersion() { let userAgent = navigator.userAgent.toLowerCase(), version = userAgent.match(/chrome\/([\d.]+)/); return +version[1]; } /** * @private * @function WebMap.prototype.addGraticule * @description 创建经纬网 * @param {Object} mapInfo - 地图信息 */ addGraticule(mapInfo) { if(this.isHaveGraticule) { this.createGraticuleLayer(mapInfo.grid.graticule); this.layerAdded++; const lens = mapInfo.layers ? mapInfo.layers.length : 0; this.sendMapToUser(lens); } } /** * @private * @function WebMap.prototype.createGraticuleLayer * @description 创建经纬网图层 * @param {Object} layerInfo - 图层信息 * @returns {ol.layer.Vector} 矢量图层 */ createGraticuleLayer(layerInfo) { const { strokeColor, strokeWidth, lineDash, extent, visible, interval, lonLabelStyle, latLabelStyle } = layerInfo; const epsgCode = this.baseProjection; // 添加经纬网需要设置extent、worldExtent let projection = new external_ol_proj_namespaceObject.get(epsgCode); projection.setExtent(extent); projection.setWorldExtent(external_ol_proj_namespaceObject.transformExtent(extent, epsgCode, 'EPSG:4326')); let graticuleOptions = { layerID: 'graticule_layer', strokeStyle: new (external_ol_style_Stroke_default())({ color: strokeColor, width: strokeWidth, lineDash }), extent, visible: visible, intervals: interval, showLabels: true, zIndex: 9999, wrapX: false, targetSize: 0 }; lonLabelStyle && (graticuleOptions.lonLabelStyle = new (external_ol_style_Text_default())({ font: `${lonLabelStyle.fontSize} ${lonLabelStyle.fontFamily}`, textBaseline: lonLabelStyle.textBaseline, fill: new (external_ol_style_Fill_default())({ color: lonLabelStyle.fill }), stroke: new (external_ol_style_Stroke_default())({ color: lonLabelStyle.outlineColor, width: lonLabelStyle.outlineWidth }) })) latLabelStyle && (graticuleOptions.latLabelStyle = new (external_ol_style_Text_default())({ font: `${latLabelStyle.fontSize} ${latLabelStyle.fontFamily}`, textBaseline: latLabelStyle.textBaseline, fill: new (external_ol_style_Fill_default())({ color: latLabelStyle.fill }), stroke: new (external_ol_style_Stroke_default())({ color: latLabelStyle.outlineColor, width: latLabelStyle.outlineWidth }) })) const layer = new external_ol_layer_namespaceObject.Graticule(graticuleOptions); this.map.addLayer(layer); } /** * @private * @function WebMap.prototype.getLang * @description 检测当前cookie中的语言或者浏览器所用语言 * @returns {string} 语言名称,如zh-CN */ getLang() { if(this.getCookie('language')) { const cookieLang = this.getCookie('language'); return this.formatCookieLang(cookieLang); } else { const browerLang = navigator.language || navigator.browserLanguage; return browerLang; } } /** * @private * @function WebMap.prototype.getCookie * @description 获取cookie中某个key对应的值 * @returns {string} 某个key对应的值 */ getCookie(key) { key = key.toLowerCase(); let value = null; let cookies = document.cookie.split(';'); cookies.forEach(function (cookie) { const arr = cookie.split('='); if (arr[0].toLowerCase().trim() === key) { value = arr[1].trim(); return; } }); return value; } /** * @private * @function WebMap.prototype.formatCookieLang * @description 将从cookie中获取的lang,转换成全称,如zh=>zh-CN * @returns {string} 转换后的语言名称 */ formatCookieLang(cookieLang) { let lang; switch(cookieLang) { case 'zh': lang = 'zh-CN'; break; case 'ar': lang = 'ar-EG'; break; case 'bg': lang = 'bg-BG'; break; case 'ca': lang = 'ca-ES'; break; case 'cs': lang = 'cs-CZ'; break; case 'da': lang = 'da-DK'; break; case 'de': lang = 'de-DE'; break; case 'el': lang = 'el-GR'; break; case 'es': lang = 'es-ES'; break; case 'et': lang = 'et-EE'; break; case 'fa': lang = 'fa-IR'; break; case 'fl': lang = 'fi-FI'; break; case 'fr': lang = 'fr-FR'; break; case 'he': lang = 'he-IL'; break; case 'hu': lang = 'hu-HU'; break; case 'id': lang = 'id-ID'; break; case 'is': lang = 'is-IS'; break; case 'it': lang = 'it-IT'; break; case 'ja': lang = 'ja-JP'; break; case 'ko': lang = 'ko-KR'; break; case 'ku': lang = 'ku-IQ'; break; case 'mn': lang = 'mn-MN'; break; case 'nb': lang = 'nb-NO'; break; case 'ne': lang = 'ne-NP'; break; case 'nl': lang = 'nl-NL'; break; case 'pl': lang = 'pl-PL'; break; case 'pt': lang = 'pt-PT'; break; case 'ru': lang = 'ru-RU'; break; case 'sk': lang = 'sk-SK'; break; case 'sl': lang = 'sl-SI'; break; case 'sr': lang = 'sr-RS'; break; case 'sv': lang = 'sv-SE'; break; case 'th': lang = 'th-TH'; break; case 'tr': lang = 'tr-TR'; break; case 'uk': lang = 'uk-UA'; break; case 'vi': lang = 'vi-VN'; break; default: lang = 'en-US'; break; } return lang; } isCustomProjection(projection) { if(core_Util_Util.isNumber(projection)){ return [-1000,-1].includes(+projection) } return ['EPSG:-1000','EPSG:-1'].includes(projection); } } ;// CONCATENATED MODULE: ./src/openlayers/mapping/ImageTileSuperMapRest.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /** * @class ImageTileSuperMapRest * @browsernamespace ol.source * @version 10.2.0 * @category iServer Image * @classdesc iServer影像服务图层源。根据指定的请求参数,返回影像数据栅格瓦片并渲染。 * @param {Object} options - 参数。 * @param {string} options.url - 服务地址。例如: http://{ip}:{port}/iserver/{imageservice-imageserviceName}/restjsr/ * @param {string} options.collectionId - 影像集合(Collection)的ID,在一个影像服务中唯一标识影像集合。 * @param {string} [options.sqlFilter] 显示影像的过滤条件。相当于SQL查询中的where子句。支持st_geometry空间函数过滤。11.0版本暂不支持通过ECQL进行过滤。 * @param {ImageRenderingRule} [options.renderingRule] 指定影像显示的风格,包含拉伸显示方式、颜色表、波段组合以及应用栅格函数进行快速处理等。不指定时,使用发布服务时所配置的风格。 * @param {Array.} [options.ids] 返回影像集合中指定ID的影像,该ID为系统维护的一个自增ID,为SuperMap SDX引擎的SmID字段内容。 * @param {Array.} [options.names] 返回影像集合中指定名称影像的瓦片资源。影像名称包含文件后缀,如S-60-45.tif。 * @param {string} [options.format='png'] - 瓦片表述类型,瓦片格式目前支持png、jpg和webp三种格式。 * @param {boolean} [options.transparent=true] - 瓦片是否透明。默认透明。 * @param {boolean} [options.cacheEnabled=true] - 启用缓存。 * @param {string} [options.tileProxy] - 代理地址。 * @param {string} [options.attribution='Map Data © SuperMap iServer'] - 版权信息。 * @extends {ol.source.XYZ} * @usage */ class ImageTileSuperMapRest extends (external_ol_source_XYZ_default()) { constructor(options) { options = options || {}; options.format = options.format || 'png'; options.transparent = options.transparent === undefined ? true : options.transparent === true; options.cacheEnabled = options.cacheEnabled === undefined ? true : options.cacheEnabled === true; var attributions = options.attributions || "Map Data © SuperMap iServer"; var url = _createLayerUrl(options.url, options); var superOptions = { ...options, attributions: attributions, url: url }; //需要代理时走自定义 tileLoadFunction,否则走默认的tileLoadFunction if (!options.tileLoadFunction && options.tileProxy) { superOptions.tileLoadFunction = tileLoadFunction; } super(superOptions); var me = this; this.options = options; if (options.tileProxy) { this.tileProxy = options.tileProxy; } function tileLoadFunction(imageTile, src) { imageTile.getImage().src = me.tileProxy + encodeURIComponent(src); } function _createLayerUrl(url, options) { var layerUrl = Util.urlPathAppend( url, `/collections/${options.collectionId}/tile.${options.format}?x={x}&y={y}&z={z}` ); var requestParams = _getAllRequestParams(options); layerUrl = Util.urlAppend(layerUrl, _getParamString(requestParams)); layerUrl = SecurityManager.appendCredential(layerUrl); if (!options.cacheEnabled) { layerUrl += '&_t=' + new Date().getTime(); } return layerUrl; } function _getAllRequestParams(options) { var params = {}; params['transparent'] = options.transparent; params['cacheEnabled'] = !(options.cacheEnabled === false); if (options.sqlFilter) { params['sqlFilter'] = options.sqlFilter; } if (options.renderingRule) { params['renderingRule'] = JSON.stringify(options.renderingRule); } if (options.ids) { params['ids'] = options.ids.join(','); } if (options.names) { params['names'] = options.names.join(','); } return params; } function _getParamString(obj) { var params = []; for (var i in obj) { params.push(encodeURIComponent(i) + '=' + encodeURIComponent(obj[i])); } return params.join('&'); } } } ;// CONCATENATED MODULE: external "ol.layer.Tile" const external_ol_layer_Tile_namespaceObject = ol.layer.Tile; var external_ol_layer_Tile_default = /*#__PURE__*/__webpack_require__.n(external_ol_layer_Tile_namespaceObject); ;// CONCATENATED MODULE: ./src/openlayers/mapping/InitMap.js window.proj4 = (proj4_src_default()); /** * @function initMap * @description 根据 SuperMap iServer 服务参数,创建地图与图层。目前仅支持SuperMap iServer 地图服务,创建的图层为 ol.Tile。 * @category BaseTypes Util * @version 11.0.1 * @param {number} url - 服务地址,例如: http://{ip}:{port}/iserver/services/map-world/rest/maps/World。 * @param {Object} options - 参数。 * @param {Object} [options.mapOptions] - 地图配置,参数设置参考 {@link https://openlayers.org/en/v6.15.1/apidoc/module-ol_Map-Map.html}。 * @param {Object} [options.viewOptions] - 视图配置,参数设置参考 {@link https://openlayers.org/en/v6.15.1/apidoc/module-ol_View-View.html} ,未设置的情况下,默认使用 SuperMap iServer 服务参数进行设置。 * @param {Object} [options.layerOptions] - 图层配置,参数设置参考 {@link https://openlayers.org/en/v6.15.1/apidoc/module-ol_layer_Tile-TileLayer.html} ,未设置的情况下,默认使用 SuperMap iServer 服务参数进行设置。 * @param {Object} [options.sourceOptions] - 数据源配置,参数设置参考 {@link TileSuperMapRest} ,未设置的情况下,默认使用 SuperMap iServer 服务参数进行设置。 * @returns {Object} 实例对象,对象包括地图实例,图层实例,数据源实例。 * @usage * ``` * // 浏览器 * * * // ES6 Import * import { initMap } from '{npm}'; * * initMap(url, { mapOptions, viewOptions, layerOptions, sourceOptions }) * ``` * */ function initMap(url, options = {}) { const { mapOptions, viewOptions, layerOptions, sourceOptions } = options; return new Promise((resolve, reject) => { new MapService(url).getMapInfo(async function (serviceResult) { if (!serviceResult || !serviceResult.result) { reject('service is not work!'); } let { prjCoordSys, bounds } = serviceResult.result; if (!(0,external_ol_proj_namespaceObject.get)(`EPSG:${prjCoordSys.epsgCode}`) && prjCoordSys.type !== 'PCS_NON_EARTH') { const wkt = await getWkt(url); registerProj(prjCoordSys.epsgCode, wkt, bounds); } let map = createMap(serviceResult.result, mapOptions, viewOptions); let { layer, source } = createLayer(url, serviceResult.result, sourceOptions, layerOptions); map.addLayer(layer); resolve({ map, source, layer }); }); }); } /** * @function viewOptionsFromMapJSON * @category BaseTypes Util * @version 11.0.1 * @description 通过 iServer REST 地图参数构造 ol 视图对象。 * @param {Object} mapJSONObj - 地图 JSON 对象。 * @param {number} [level=22] - 地图最大级别。 * @returns {Object} ol视图参数,包括中心点、投影、级别、分辨率数组。 */ function viewOptionsFromMapJSON(mapJSONObj, level = 22) { let { bounds, dpi, center, visibleScales, scale, coordUnit, prjCoordSys } = mapJSONObj; const mapCenter = center.x && center.y ? [center.x, center.y] : [(bounds.left + bounds.right) / 2, (bounds.bottom + bounds.top) / 2]; const extent = [bounds.left, bounds.bottom, bounds.right, bounds.top]; let projection = core_Util_Util.getProjection(prjCoordSys, extent); var resolutions = core_Util_Util.scalesToResolutions(visibleScales, bounds, dpi, coordUnit, level); const zoom = core_Util_Util.getZoomByResolution(core_Util_Util.scaleToResolution(scale, dpi, coordUnit), resolutions); return { center: mapCenter, projection, zoom, resolutions }; } function createMap(result, mapOptions, viewOptions) { let view = viewOptionsFromMapJSON(result); var map = new (external_ol_Map_default())({ target: 'map', view: new (external_ol_View_default())({ ...view, ...viewOptions }), ...mapOptions }); return map; } function registerProj(epsgCode, wkt, bounds) { const extent = [bounds.left, bounds.bottom, bounds.right, bounds.top]; let epsgCodeStr = `EPSG:${epsgCode}`; !(0,external_ol_proj_namespaceObject.get)(epsgCodeStr) && proj4_src_default().defs(epsgCodeStr, wkt); if (external_ol_proj_proj4_namespaceObject && external_ol_proj_proj4_namespaceObject.register) { external_ol_proj_proj4_namespaceObject.register((proj4_src_default())); var prj = (0,external_ol_proj_namespaceObject.get)(epsgCodeStr); prj.setExtent(extent); } } function createLayer(url, result, sourceOptions, layerOptions) { let options = TileSuperMapRest.optionsFromMapJSON(url, result, true); options = { ...options, ...sourceOptions }; var source = new TileSuperMapRest(options); var layer = new (external_ol_layer_Tile_default())({ source, ...layerOptions }); return { layer, source }; } function getWkt(url) { return new Promise((resolve) => { new MapService(url).getWkt(function (res) { let wkt = res.result.data; resolve(wkt); }); }); } ;// CONCATENATED MODULE: ./src/openlayers/mapping/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/openlayers/index.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ ;// CONCATENATED MODULE: ./src/openlayers/namespace.js /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ /* control */ /* core */ /* mapping */ /* overlay */ /* service */ if (window && window.ol) { let ol = window.ol; ol.supermap = { ...SuperMap, ...ol.supermap }; ol.supermap.control = ol.supermap.control || {}; // control ol.supermap.control.ChangeTileVersion = ChangeTileVersion; ol.supermap.control.Logo = Logo; ol.supermap.control.ScaleLine = ScaleLine; // core ol.supermap.StyleUtils = StyleUtils; ol.supermap.Util = core_Util_Util; // mapping ol.source.BaiduMap = BaiduMap; ol.source.ImageSuperMapRest = ImageSuperMapRest; ol.source.SuperMapCloud = SuperMapCloud; ol.source.ImageTileSuperMapRest = ImageTileSuperMapRest; ol.source.Tianditu = Tianditu; ol.source.TileSuperMapRest = TileSuperMapRest; ol.supermap.WebMap = WebMap; // overlay ol.style.CloverShape = CloverShape; ol.Graphic = Graphic_Graphic; ol.style.HitCloverShape = HitCloverShape; ol.source.GeoFeature = GeoFeature; ol.source.Theme = theme_Theme_Theme; ol.supermap.ThemeFeature = ThemeFeature; ol.supermap.MapboxStyles = MapboxStyles; ol.supermap.VectorTileStyles = VectorTileStyles; ol.source.DataFlow = DataFlow; ol.source.Graph = Graph_Graph; ol.source.Graphic = Graphic; ol.source.HeatMap = HeatMap; ol.source.Label = Label_Label; ol.source.Mapv = Mapv; ol.source.Range = Range; ol.source.RankSymbol = RankSymbol_RankSymbol; ol.source.Turf = Turf; ol.source.FGB = FGB; ol.source.Unique = Unique; ol.source.VectorTileSuperMapRest = VectorTileSuperMapRest; // service ol.supermap.AddressMatchService = AddressMatchService; ol.supermap.ChartService = ChartService; ol.supermap.DataFlowService = DataFlowService; ol.supermap.DatasetService = DatasetService; ol.supermap.DatasourceService = DatasourceService; ol.supermap.FeatureService = FeatureService; ol.supermap.FieldService = FieldService; ol.supermap.GridCellInfosService = GridCellInfosService; ol.supermap.GeoprocessingService = GeoprocessingService; ol.supermap.LayerInfoService = LayerInfoService; ol.supermap.MapService = MapService; ol.supermap.MeasureService = MeasureService; ol.supermap.NetworkAnalyst3DService = NetworkAnalyst3DService; ol.supermap.NetworkAnalystService = NetworkAnalystService; ol.supermap.ProcessingService = ProcessingService; ol.supermap.QueryService = QueryService_QueryService; ol.supermap.ServiceBase = ServiceBase; ol.supermap.SpatialAnalystService = SpatialAnalystService; ol.supermap.ThemeService = ThemeService; ol.supermap.TrafficTransferAnalystService = TrafficTransferAnalystService; ol.supermap.WebPrintingJobService = WebPrintingJobService; ol.supermap.ImageService = ImageService; ol.supermap.ImageCollectionService = ImageCollectionService; ol.supermap.initMap = initMap; ol.supermap.viewOptionsFromMapJSON = viewOptionsFromMapJSON; // 处理命名空间重名问题 ol.supermap.CommonUtil = Util; } })(); // This entry need to be wrapped in an IIFE because it need to be in strict mode. (() => { "use strict"; /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ })(); /******/ })() ;