/*!
*
* iclient-mapboxgl.(https://iclient.supermap.io)
* Copyright© 2000 - 2020 SuperMap Software Co.Ltd
* license: Apache-2.0
* version: v10.1.0
*
*/
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 11);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = mapboxgl;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = function(){try{return mapv}catch(e){return {}}}();
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = function(){try{return THREE}catch(e){return {}}}();
/***/ }),
/* 3 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
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;
});
/***/ }),
/* 5 */
/***/ (function(module, exports) {
module.exports = function(){try{return XLSX}catch(e){return {}}}();
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = function(){try{return convert}catch(e){return {}}}();
/***/ }),
/* 7 */
/***/ (function(module, exports) {
module.exports = function(){try{return elasticsearch}catch(e){return {}}}();
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/**
* 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 global == 'object' && global && global.Object === Object && global;
/** 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;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
/***/ }),
/* 9 */
/***/ (function(module, exports) {
module.exports = function(){try{return echarts}catch(e){return {}}}();
/***/ }),
/* 10 */
/***/ (function(module, exports) {
module.exports = function(){try{return canvg}catch(e){return {}}}();
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(18);
module.exports = __webpack_require__(17);
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(setImmediate, global) {(function (global, factory) {
true ? factory() :
undefined;
}(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);
});
}
);
}
// 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.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 global !== 'undefined') {
return global;
}
throw new Error('unable to locate global object');
})();
if (!('Promise' in globalNS)) {
globalNS['Promise'] = Promise;
} else if (!globalNS.Promise.prototype['finally']) {
globalNS.Promise.prototype['finally'] = finallyConstructor;
}
})));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(13).setImmediate, __webpack_require__(3)))
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
(typeof self !== "undefined" && self) ||
window;
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(scope, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(14);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function(handle) {
process.nextTick(function () { runIfPresent(handle); });
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function(event) {
if (event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function(handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function(handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function(handle) {
// Create a `
* ``
*
* @param {number} id - iPortal|Online 地图 ID。
* @param {Object} options - 参数。
* @param {string} [options.target='map'] - 地图容器 ID。
* @param {string} [options.server="https://www.supermapol.com"] - 地图的地址。
* @param {string} [options.credentialKey] - 凭证密钥。
* @param {string} [options.credentialValue] - 凭证值。
* @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。
* @param {boolean} [options.excludePortalProxyUrl] - server 传递过来的 URL 是否带有代理。
* @fires mapboxgl.supermap.WebMap#getmapfailed
* @fires mapboxgl.supermap.WebMap#getwmtsfailed
* @fires mapboxgl.supermap.WebMap#getlayersfailed
* @fires mapboxgl.supermap.WebMap#getfeaturesfailed
* @fires mapboxgl.supermap.WebMap#addlayerssucceeded
* @extends {mapboxgl.Evented}
*/
class WebMap_WebMap extends external_mapboxgl_default.a.Evented {
/**
* @constructs
* @version 9.1.2
*/
constructor(id, options) {
super();
this.mapId = id;
options = options || {};
this.server = options.server || 'https://www.supermapol.com';
this.credentialKey = options.credentialKey;
this.credentialValue = options.credentialValue;
this.withCredentials = options.withCredentials || false;
this.target = options.target || 'map';
this._createWebMap();
}
/**
* @function mapboxgl.supermap.WebMap.prototype.resize
* @description map resize。
* @version 9.1.2
*/
resize() {
this.map.resize();
}
/**
* @function mapboxgl.supermap.WebMap.prototype.setMapId
* @param {string} mapId - webMap 地图 ID。
* @description 设置 WebMap ID。
* @version 9.1.2
*/
setMapId(mapId) {
this.mapId = mapId;
this._createWebMap();
}
/**
* @function mapboxgl.supermap.WebMap.prototype.setWebMapOptions
* @param {Object} webMapOptions - webMap 参数。
* @description 设置 webMap 参数。
* @version 9.1.2
*/
setWebMapOptions(webMapOptions) {
this.server = webMapOptions.server;
this._createWebMap();
}
/**
* @function mapboxgl.supermap.WebMap.prototype.setMapOptions
* @param {Object} mapOptions - map 参数。
* @description 设置 map 参数。
* @version 9.1.2
*/
setMapOptions(mapOptions) {
let { center, zoom, maxBounds, minZoom, maxZoom, isWorldCopy, bearing, pitch } = mapOptions;
center && center.length && this.map.setCenter(center);
zoom && this.map.setZoom(zoom);
maxBounds && this.map.setMaxBounds(maxBounds);
minZoom && this.map.setMinZoom(minZoom);
maxZoom && this.map.setMaxZoom(maxZoom);
isWorldCopy && this.map.setRenderWorldCopies(isWorldCopy);
bearing && this.map.setBearing(bearing);
pitch && this.map.setPitch(pitch);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createWebMap
* @description 登陆窗口后添加地图图层。
*/
_createWebMap() {
let urlArr = this.server.split('');
if (urlArr[urlArr.length - 1] !== '/') {
this.server += '/';
}
let mapUrl = this.server + 'web/maps/' + this.mapId + '/map';
if (this.credentialValue && this.credentialKey) {
mapUrl += '?' + this.credentialKey + '=' + this.credentialValue;
}
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 mapboxgl.supermap.WebMap.prototype._createMap
* @description 创建地图。
*/
_createMap(mapInfo) {
// 获取字体样式
let fonts = [];
let layers = mapInfo.layers;
// 获取 label 图层字体类型
if (layers && layers.length > 0) {
layers.forEach(layer => {
layer.labelStyle && fonts.push(layer.labelStyle.fontFamily);
}, this);
}
fonts.push("'supermapol-icons'");
let fontFamilys = fonts.join(',');
// zoom center
let oldcenter = mapInfo.center,
zoom = mapInfo.level || 0,
center,
zoomBase = 0;
// zoom = zoom === 0 ? 0 : zoom - 1;
if (mapInfo.minScale && mapInfo.maxScale) {
zoomBase = this._transformScaleToZoom(mapInfo.minScale, external_mapboxgl_default.a.CRS ? external_mapboxgl_default.a.CRS.get(this.baseProjection):'EPSG:3857');
} else {
zoomBase = +Math.log2(
this._getResolution(external_mapboxgl_default.a.CRS ? external_mapboxgl_default.a.CRS.get(this.baseProjection).getExtent():[-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892]) / this._getResolution(mapInfo.extent)
).toFixed(2);
}
zoom += zoomBase;
center = oldcenter ? this._unproject([oldcenter.x, oldcenter.y]) : new external_mapboxgl_default.a.LngLat(0, 0);
// 初始化 map
this.map = new external_mapboxgl_default.a.Map({
container: this.target,
center: center,
zoom: zoom,
style: {
version: 8,
sources: {},
// "glyphs": 'https://iclient.supermap.io/iserver/services/map-beijing/rest/maps/beijingMap/tileFeature/sdffonts/{fontstack}/{range}.pbf',
layers: []
},
crs: this.baseProjection,
localIdeographFontFamily: fontFamilys || ''
});
this.fire('mapinitialized');
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._getMapInfo
* @description 获取地图的 JSON 信息。
* @param {string} url - 请求地图的 url。
*/
_getMapInfo(url) {
let mapUrl = url.indexOf('.json') === -1 ? `${url}.json` : url;
FetchRequest.get(mapUrl, null, { withCredentials: this.withCredentials })
.then(response => {
return response.json();
})
.then(mapInfo => {
this.baseProjection = mapInfo.projection;
//存储地图的名称以及描述等信息,返回给用户
this.mapParams = {
title: mapInfo.title,
description: mapInfo.description
};
const projectionMap = {
'EPSG:4490': 'EPSG:4490',
'EPSG:4214': 'EPSG:4214',
'EPSG:4610': 'EPSG:4610',
'EPSG:3857': 'EPSG:3857',
'EPSG:4326': 'EPSG:4326'
}; // 坐标系异常处理
if (this.baseProjection in projectionMap) {
this._createMap(mapInfo, this.mapSetting);
let layers = mapInfo.layers;
this.map.on('load', () => {
this._addBaseMap(mapInfo);
if (!layers || layers.length === 0) {
this._sendMapToUser(0, 0);
} else {
this._addLayers(layers);
}
});
} else {
throw Error(Lang.i18n('msg_crsunsupport'));
}
})
.catch(error => {
/**
* @event mapboxgl.supermap.WebMap#getmapfailed
* @description 获取地图信息失败。
* @property {Object} error - 失败原因。
*/
this.fire('getmapfailed', { error: error });
});
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._addBaseMap
* @description 添加底图。
* @param {Object} mapInfo - map 信息。
*/
_addBaseMap(mapInfo) {
this._createBaseLayer(mapInfo);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createBaseLayer
* @description 创建底图。
* @param {Object} mapInfo - map 信息。
*/
_createBaseLayer(mapInfo) {
let layerInfo = mapInfo.baseLayer || mapInfo;
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);
}
let mapUrls = {
CLOUD: 'http://t2.dituhui.com/FileService/image?map=quanguo&type=web&x={x}&y={y}&z={z}',
CLOUD_BLACK: 'http://t3.dituhui.com/MapService/getGdp?x={x}&y={y}&z={z}',
OSM: 'http://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png',
GOOGLE:
'https://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i380072576!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0',
GOOGLE_CN: 'https://mt{0-3}.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}',
JAPAN_STD: 'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png',
JAPAN_PALE: 'https://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png',
JAPAN_RELIEF: 'https://cyberjapandata.gsi.go.jp/xyz/relief/{z}/{x}/{y}.png',
JAPAN_ORT: 'https://cyberjapandata.gsi.go.jp/xyz/ort/{z}/{x}/{y}.jpg'
},
url;
switch (layerType) {
case 'TIANDITU_VEC':
case 'TIANDITU_IMG':
case 'TIANDITU_TER':
this._createTiandituLayer(mapInfo);
break;
case 'BING':
this._createBingLayer(layerInfo.name);
break;
case 'WMS':
this._createWMSLayer(layerInfo);
break;
case 'WMTS':
this._createWMTSLayer(layerInfo);
break;
case 'TILE':
case 'SUPERMAP_REST':
this._createDynamicTiledLayer(layerInfo);
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':
url = mapUrls[layerType];
this._createXYZLayer(layerInfo, url);
break;
case 'MAPBOXSTYLE':
this._createMapboxStyle(layerInfo);
break;
default:
break;
}
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createMapboxStyle
* @description 创建 Mapbox 样式。
* @param {Object} mapInfo - map 信息。
*/
_createMapboxStyle(mapInfo) {
let _this = this,
{ dataSource = {} } = mapInfo,
{ serverId, url } = dataSource,
styleUrl;
styleUrl = serverId !== undefined ? `${this.server}web/datas/${serverId}/download` : url;
FetchRequest.get(styleUrl, null, {
withCredentials: this.withCredentials,
withoutFormatSuffix: true,
headers: {
'Content-Type': 'application/json;chartset=uft-8'
}
}).then(response => {
return response.json();
}).then(style => {
_this._matchStyleObject(style);
_this.map.setStyle(style);
})
}
/**
* @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 mapboxgl.supermap.WebMap.prototype._createTiandituLayer
* @description 创建天地图底图。
* @param {Object} mapInfo - map 信息。
*/
_createTiandituLayer(mapInfo) {
let tiandituUrls = this._getTiandituUrl(mapInfo);
let layerType = mapInfo.baseLayer.layerType;
let isLabel = Boolean(mapInfo.baseLayer.labelLayerVisible);
let labelUrl = tiandituUrls['labelUrl'];
let tiandituUrl = tiandituUrls['tiandituUrl'];
this._addBaselayer(tiandituUrl, 'tianditu-layers-' + layerType);
isLabel && this._addBaselayer(labelUrl, 'tianditu-label-layers-' + layerType);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createWMTSLayer
* @description 创建 WMTS 底图。
* @param {Object} mapInfo - map 信息。
*/
_createWMTSLayer(layerInfo) {
let wmtsUrl = this._getWMTSUrl(layerInfo);
this._filterWMTSIsMatched(layerInfo, (isMatched, matchMaxZoom) => {
isMatched && this._addBaselayer([wmtsUrl], 'wmts-layers' + layerInfo.name, 0, matchMaxZoom);
});
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._filterWMTSIsMatched
* @description 过滤能够跟mapboxgl匹配的wmts服务。
* @param {Object} mapInfo - map 信息。
* @callback matchedCallback
*/
_filterWMTSIsMatched(mapInfo, matchedCallback) {
let isMatched = false,
matchMaxZoom = 22,
url = mapInfo.url;
let options = {
withCredentials: false,
withoutFormatSuffix: true
};
FetchRequest.get(url, null, options)
.then(response => {
return response.text();
})
.then(capabilitiesText => {
let converts = external_function_try_return_convert_catch_e_return_default.a ? external_function_try_return_convert_catch_e_return_default.a : window.convert;
let tileMatrixSet = JSON.parse(converts.xml2json(capabilitiesText, { compact: true, spaces: 4 }))
.Capabilities.Contents.TileMatrixSet;
if (!Array.isArray(tileMatrixSet)) {
tileMatrixSet = [tileMatrixSet];
}
for (let i = 0; i < tileMatrixSet.length; i++) {
if (
tileMatrixSet[i]['ows:Identifier'] &&
tileMatrixSet[i]['ows:Identifier']['_text'] === mapInfo.tileMatrixSet
) {
if (DEFAULT_WELLKNOWNSCALESET.indexOf(tileMatrixSet[i]['WellKnownScaleSet']['_text']) > -1) {
isMatched = true;
} else if (
tileMatrixSet[i]['WellKnownScaleSet'] &&
tileMatrixSet[i]['WellKnownScaleSet']['_text'] === 'Custom'
) {
let matchedScaleDenominator = [];
//坐标系判断
let defaultCRSScaleDenominators =
this.map.crs === 'EPSG:3857' ? MB_SCALEDENOMINATOR_3857 : MB_SCALEDENOMINATOR_4326;
for (let j = 0, len = defaultCRSScaleDenominators.length; j < len; j++) {
if (!tileMatrixSet[i].TileMatrix[j]) {
break;
}
if (
defaultCRSScaleDenominators[j] !==
tileMatrixSet[i].TileMatrix[j]['ScaleDenominator']['_text']
) {
break;
}
matchedScaleDenominator.push(defaultCRSScaleDenominators[j]);
}
matchMaxZoom = matchedScaleDenominator.length - 1;
if (matchedScaleDenominator.length !== 0) {
isMatched = true;
} else {
throw Error(Lang.i18n('msg_tilematrixsetunsupport'));
}
} else {
throw Error(Lang.i18n('msg_tilematrixsetunsupport'));
}
}
}
matchedCallback(isMatched, matchMaxZoom);
})
.catch(error => {
/**
* @event mapboxgl.supermap.WebMap#getwmtsfailed
* @description 获取 WMTS 图层信息失败。
* @property {Object} error - 失败原因。
* @property {mapboxgl.Map} map - MapBoxGL Map 对象。
*/
this.fire('getwmtsfailed', { error: error, map: this.map });
});
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createBingLayer
* @description 创建 Bing 图层。
*/
_createBingLayer(layerName) {
let bingUrl =
'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';
this.addLayer([bingUrl], 'bing-layers-' + layerName);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createXYZLayer
* @description 创建 XYZ 底图。
* @param {String} url - url 地址。
*/
_createXYZLayer(layerInfo, url) {
let urlArr = [];
if (layerInfo.layerType === 'OSM') {
let res = url.match(/\w\-\w/g)[0];
let start = res[0];
let end = res[2];
let alphabet = '';
for (let i = 97; i < 123; i++) {
alphabet += String.fromCharCode(i);
}
let alphabetArr = alphabet.split('');
let startIndex = alphabetArr.indexOf(start);
let endIndex = alphabetArr.indexOf(end);
let res3 = alphabetArr.slice(startIndex, endIndex + 1);
for (let i = 0; i < res3.length; i++) {
let replaceRes = url.replace(/{\w\-\w}/g, res3[i]);
urlArr.push(replaceRes);
}
} else if (layerInfo.layerType === 'GOOGLE_CN') {
let res = url.match(/\d\-\d/g)[0];
let start = res[0];
let end = res[2];
for (let i = start; i <= end; i++) {
let replaceRes = url.replace(/{\d\-\d}/g, i);
urlArr.push(replaceRes);
}
} else {
urlArr = [url];
}
this._addBaselayer(urlArr, 'XYZ-layers-' + layerInfo.name);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createDynamicTiledLayer
* @description 创建 iserver 底图。
* @param {Object} layerInfo - 图层信息。
*/
_createDynamicTiledLayer(layerInfo) {
let url = layerInfo.url;
const layerId = layerInfo.layerID || layerInfo.name;
const { minzoom, maxzoom } = layerInfo;
this._addBaselayer([url], layerId, minzoom, maxzoom, true);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createWMSLayer
* @description 创建 WMS 图层。
* @param {Object} mapInfo - map 信息。
*/
_createWMSLayer(layerInfo) {
let WMSUrl = this._getWMSUrl(layerInfo);
this._addBaselayer([WMSUrl], 'WMS-layers-' + layerInfo.name);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createVectorLayer
* @description 创建 Vector 图层。
* @param {Object} layerInfo - map 信息。
* @param {Array} features - 属性 信息。
*/
_createVectorLayer(layerInfo, features) {
let style = layerInfo.style;
let type = layerInfo.featureType;
let layerID = layerInfo.layerID;
let visible = layerInfo.visible;
let layerStyle = {};
layerStyle.style = this._transformStyleToMapBoxGl(style, type);
layerStyle.layout = { visibility: visible };
let source = {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: features
}
};
this._addOverlayToMap(type, source, layerID, layerStyle);
// 如果面有边框
type === 'POLYGON' &&
style.strokeColor &&
this._addStrokeLineForPoly(style, source, layerID + '-strokeLine', visible);
}
/**
* @function mapboxgl.supermap.WebMap.prototype._getTiandituUrl
* @private
* @description 创建天地图url;
* @param {Object} mapInfo - map 信息。
*/
_getTiandituUrl(mapInfo) {
let re = /t0/gi;
let tiandituUrls = {};
let layerType = mapInfo.baseLayer.layerType.split('_')[1].toLowerCase();
let isLabel = Boolean(mapInfo.baseLayer.labelLayerVisible);
// let isLabel = true;
let url = 'https://t0.tianditu.gov.cn/{layer}_{proj}/wmts?';
let labelUrl = url;
let layerLabelMap = {
vec: 'cva',
ter: 'cta',
img: 'cia'
};
let tilematrixSet = this.baseProjection === 'EPSG:4326' ? 'c' : 'w';
let options = {
service: 'WMTS',
request: 'GetTile',
style: 'default',
version: '1.0.0',
layer: layerType,
tilematrixSet: tilematrixSet,
format: 'tiles',
width: 256,
height: 256
};
url += this._getParamString(options, url) + '&tilematrix={z}&tilerow={y}&tilecol={x}';
let tiandituUrl = url.replace('{layer}', layerType).replace('{proj}', tilematrixSet);
let tiandituUrlArr = [];
for (let i = 0; i < 8; i++) {
tiandituUrlArr.push(tiandituUrl.replace(re, `t${i}`));
}
tiandituUrls['tiandituUrl'] = tiandituUrlArr;
// 如果有 label 图层
if (isLabel) {
let labelLayer = layerLabelMap[layerType];
options.layer = labelLayer;
labelUrl += this._getParamString(options, labelUrl) + '&tilematrix={z}&tilerow={y}&tilecol={x}';
labelUrl = labelUrl.replace('{layer}', labelLayer).replace('{proj}', tilematrixSet);
let labelUrlArr = [];
for (let i = 0; i < 8; i++) {
labelUrlArr.push(labelUrl.replace(re, `t${i}`));
}
tiandituUrls['labelUrl'] = labelUrlArr;
}
return tiandituUrls;
}
/**
* @function mapboxgl.supermap.WebMap.prototype._getWMSUrl
* @private
* @description 创建 WMS url;
* @param {Object} mapInfo - map 信息。
*/
_getWMSUrl(mapInfo) {
let url = mapInfo.url;
url = url.split('?')[0];
let strArr = url.split('/');
let options = {
service: 'WMS',
request: 'GetMap',
layers: strArr[strArr.length - 1],
styles: '',
format: 'image/png',
transparent: 'true',
version: '1.1.1',
width: 256,
height: 256,
srs: this.baseProjection
};
let bbox = this.baseProjection === 'EPSG:4326' ? '{bbox-epsg-4326}' : '{bbox-epsg-3857}';
url += this._getParamString(options, url) + `&bbox=${bbox}`;
return url;
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._addLayers
* @description 添加叠加图层。
* @param {Object} mapInfo - 图层信息。
*/
_addLayers(layers) {
//存储地图上所有的图层对象
this.layers = layers;
let features,
layerAdded = 0,
len = layers.length;
layers.forEach((layer, index) => {
if ((layer.dataSource && layer.dataSource.serverId) || layer.layerType === 'MARKER') {
// 获取 serverID
let serverId = layer.dataSource ? layer.dataSource.serverId : layer.serverId;
let url = `${this.server}web/datas/${serverId}/content.json?pageSize=9999999¤tPage=1`;
// 获取图层数据
serverId &&
FetchRequest.get(url, null, { withCredentials: this.withCredentials })
.then(response => {
return response.json();
})
.then(data => {
if (data.succeed === false) {
//请求失败
layerAdded++;
this._sendMapToUser(layerAdded, len);
/**
* @event mapboxgl.supermap.WebMap#getlayersfailed
* @description 获取图层信息失败。
* @property {Object} error - 失败原因。
* @property {mapboxgl.Map} map - MapBoxGL Map 对象。
*/
this.fire('getlayersfailed', { error: data.error, map: this.map });
return;
}
if (data.type) {
if (data.type === 'JSON' || data.type === 'GEOJSON') {
data.content = JSON.parse(data.content.trim());
features = this._formatGeoJSON(data.content, layer);
} else if (data.type === 'EXCEL' || data.type === 'CSV') {
features = this._excelData2Feature(data.content, layer);
}
this._addLayer(layer, features, index);
layerAdded++;
this._sendMapToUser(layerAdded, len);
}
})
.catch(error => {
layerAdded++;
this._sendMapToUser(layerAdded, len);
this.fire('getlayersfailed', { error: error, map: this.map });
});
} else if (
layer.layerType === 'SUPERMAP_REST' ||
layer.layerType === 'TILE' ||
layer.layerType === 'WMS' ||
layer.layerType === 'WMTS'
) {
this._createBaseLayer(layer);
layerAdded++;
this._sendMapToUser(layerAdded, len);
} else if (layer.dataSource && layer.dataSource.type === 'REST_DATA') {
let dataSource = layer.dataSource;
//从restData获取数据
this._getFeatureBySQL(
dataSource.url,
[dataSource.dataSourseName || layer.name],
result => {
features = this._parseGeoJsonData2Feature({
allDatas: { features: result.result.features.features },
fileCode: layer.projection,
featureProjection: this.baseProjection
});
this._addLayer(layer, features, index);
layerAdded++;
this._sendMapToUser(layerAdded, len);
},
err => {
layerAdded++;
this._sendMapToUser(layerAdded, len);
/**
* @event mapboxgl.supermap.WebMap#getfeaturesfailed
* @description 获取图层要素失败。
* @property {Object} error - 失败原因。
*/
this.fire('getfeaturesfailed', { error: err });
}
);
} else if (layer.dataSource && layer.dataSource.type === 'REST_MAP' && layer.dataSource.url) {
this._queryFeatureBySQL(
layer.dataSource.url,
layer.dataSource.layerName,
'smid=1',
null,
null,
result => {
let recordsets = result && result.result.recordsets;
let recordset = recordsets && recordsets[0];
let attributes = recordset.fields;
if (recordset && attributes) {
let fileterAttrs = [];
for (let i in attributes) {
let value = attributes[i];
if (value.indexOf('Sm') !== 0 || value === 'SmID') {
fileterAttrs.push(value);
}
}
this._getFeatures(
fileterAttrs,
layer,
features => {
this._addLayer(layer, features, index);
layerAdded++;
this._sendMapToUser(layerAdded, len);
},
err => {
layerAdded++;
this.fire('getfeaturesfailed', { error: err, map: this.map });
}
);
}
},
err => {
this.fire('getlayersfailed', { error: err, map: this.map });
}
);
}
}, this);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._getFeatures
* @description 将单个图层添加到地图上。
* @param layerInfo 某个图层的图层信息
* @param {Array.} features - feature。
*/
_getFeatures(fields, layerInfo, resolve, reject) {
let source = layerInfo.dataSource;
//示例数据
let fileCode = layerInfo.projection;
this._queryFeatureBySQL(
source.url,
source.layerName,
null,
fields,
null,
result => {
let recordsets = result.result.recordsets[0];
let features = recordsets.features.features;
let featuresObj = this._parseGeoJsonData2Feature(
{
allDatas: { features },
fileCode: fileCode,
featureProjection: this.baseProjection
},
'JSON'
);
resolve(featuresObj);
},
err => {
reject(err);
}
);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._addLayer
* @description 将单个图层添加到地图上。
* @param layerInfo 某个图层的图层信息
* @param {Array.} features - feature。
*/
_addLayer(layerInfo, features, index) {
let layerType = layerInfo.layerType;
layerInfo.layerID = layerType + '-' + layerInfo.name + '-' + index;
layerInfo.visible = layerInfo.visible ? 'visible' : 'none';
// mbgl 目前不能处理 geojson 复杂面情况
// mbgl isssue https://github.com/mapbox/mapbox-gl-js/issues/7023
if (features[0] && features[0].geometry.type === 'Polygon') {
features = this._handleMultyPolygon(features);
}
if (layerInfo.style && layerInfo.filterCondition) {
//将 feature 根据过滤条件进行过滤, 分段专题图和单值专题图因为要计算 styleGroup 所以暂时不过滤
if (layerType !== 'RANGE' && layerType !== 'UNIQUE') {
features = this._getFiterFeatures(layerInfo.filterCondition, features);
}
}
if (layerType === 'VECTOR') {
if (layerInfo.featureType === 'POINT') {
if (layerInfo.style.type === 'SYMBOL_POINT') {
this._createSymbolLayer(layerInfo, features);
} else {
this._createGraphicLayer(layerInfo, features);
}
} else {
//线和面
this._createVectorLayer(layerInfo, features);
}
} else if (layerType === 'UNIQUE') {
this._createUniqueLayer(layerInfo, features);
} else if (layerType === 'RANGE') {
this._createRangeLayer(layerInfo, features);
} else if (layerType === 'HEAT') {
this._createHeatLayer(layerInfo, features);
} else if (layerType === 'MARKER') {
this._createMarkerLayer(layerInfo, features);
}
if (layerInfo.labelStyle && layerInfo.labelStyle.labelField) {
// 存在标签专题图
this._addLabelLayer(layerInfo, features);
}
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._addLabelLayer
* @description 添加标签图层。
* @param layerInfo 某个图层的图层信息。
* @param {Array.} features - feature。
*/
_addLabelLayer(layerInfo, features) {
let labelStyle = layerInfo.labelStyle;
this.map.addLayer({
id: layerInfo.layerID + 'label',
type: 'symbol',
source: {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: features
}
},
paint: {
'text-color': labelStyle.fill
},
layout: {
'text-field': `{${labelStyle.labelField}}`,
'text-size': parseFloat(labelStyle.fontSize) || 12,
'text-offset': labelStyle.offsetX
? [labelStyle.offsetX / 10 || 0, labelStyle.offsetY / 10 || 0]
: [0, -1.5],
'text-font': ['DIN Offc Pro Italic', 'Arial Unicode MS Regular'],
visibility: layerInfo.visible
}
});
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createSymbolLayer
* @description 添加 symbol 图层。
* @param layerInfo 某个图层的图层信息。
* @param {Array.} features - feature。
*/
_createSymbolLayer(layerInfo, features) {
//用来请求symbol_point字体文件
let target = document.getElementById(`${this.target}`);
target.classList.add('supermapol-icons-map');
let style = layerInfo.style;
let unicode = layerInfo.style.unicode;
let text = String.fromCharCode(parseInt(unicode.replace(/^/, ''), 16));
let layerID = layerInfo.layerID;
this.map.addSource(layerID + '-source', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: []
}
});
this.map.addLayer({
id: layerID,
type: 'symbol',
source: layerID + '-source',
paint: {
'text-color': style.fillColor
},
layout: {
'text-field': text,
'text-font': ['DIN Offc Pro Italic', 'Arial Unicode MS Regular'],
visibility: layerInfo.visible
}
});
this.map.getSource(layerID + '-source').setData({
type: 'FeatureCollection',
features: features
});
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createGraphicLayer
* @description 创建 Graphic 图层。
* @param {Object} layerInfo - map 信息。
* @param {Array} features - 属性 信息。
*/
_createGraphicLayer(layerInfo, features) {
let style = layerInfo.style;
let layerStyle = {};
let layerID = layerInfo.layerID;
let source = {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: features
}
};
if (style.type === 'IMAGE_POINT') {
let imageInfo = style.imageInfo;
let imgDom = imageInfo.img;
if (!imgDom || !imgDom.src) {
//要组装成完整的url
imageInfo.url = this.server + imageInfo.url;
}
this.map.loadImage(imageInfo.url || imgDom.src, (error, image) => {
if (error) {
console.log(error);
}
let iconSize = Number.parseFloat((style.radius / image.height).toFixed(2)) * 2;
this.map.addImage('imageIcon', image);
this.map.addLayer({
id: layerID,
type: 'symbol',
source: source,
layout: {
'icon-image': 'imageIcon',
'icon-size': iconSize,
visibility: layerInfo.visible
}
});
});
} else if (style.type === 'SVG_POINT') {
let svg_url = style.url;
if (!this.svgDiv) {
this.svgDiv = document.createElement('div');
document.body.appendChild(this.svgDiv);
}
this._getCanvasFromSVG(svg_url, this.svgDiv, canvas => {
let imgUrl = canvas.toDataURL('img/png');
imgUrl &&
this.map.loadImage(
imgUrl,
(error, image) => {
if (error) {
console.log(error);
}
let iconSize = Number.parseFloat((style.radius / canvas.width).toFixed(2));
this.map.addImage('imageIcon', image);
this.map.addLayer({
id: layerID,
type: 'symbol',
source: source,
layout: {
'icon-image': 'imageIcon',
'icon-size': iconSize,
visibility: layerInfo.visible
}
});
},
this
);
});
} else {
layerStyle.style = this._transformStyleToMapBoxGl(style, layerInfo.featureType);
layerStyle.layout = { visibility: layerInfo.visible };
this._addOverlayToMap('POINT', source, layerID, layerStyle);
}
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createUniqueLayer
* @description 创建单值图层。
* @param layerInfo 某个图层的图层信息
* @param features 图层上的 feature
*/
_createUniqueLayer(layerInfo, features) {
let styleGroup = this._getUniqueStyleGroup(layerInfo, features);
features = this._getFiterFeatures(layerInfo.filterCondition, features);
let style = layerInfo.style;
let layerStyle = {};
let themeField = layerInfo.themeSetting.themeField;
let type = layerInfo.featureType;
let expression = ['match', ['get', 'index']];
let layerID = layerInfo.layerID;
features.forEach(row => {
styleGroup.forEach(item => {
if (item.value === row.properties[themeField]) {
expression.push(row.properties['index'], item.color);
}
});
});
expression.push('#ffffff');
layerStyle.style = this._transformStyleToMapBoxGl(style, type, expression);
let visible = layerInfo.visible;
layerStyle.layout = { visibility: visible };
let source = {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: features
}
};
this._addOverlayToMap(type, source, layerID, layerStyle);
type === 'POLYGON' &&
style.strokeColor &&
this._addStrokeLineForPoly(style, source, layerID + '-strokeLine', visible);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._getUniqueStyleGroup
* @description 获取单值的目标字段与颜色的对应数组。
* @param layerInfo 某个图层的图层信息
* @param features 图层上的 feature
*/
_getUniqueStyleGroup(parameters, features) {
// 找出所有的单值
let featureType = parameters.featureType,
style = parameters.style,
themeSetting = parameters.themeSetting;
let fieldName = themeSetting.themeField,
colors = themeSetting.colors;
let names = [],
customSettings = themeSetting.customSettings;
for (let i in features) {
let properties = features[i].properties;
let name = properties[fieldName];
let isSaved = false;
for (let j in names) {
if (names[j] === name) {
isSaved = true;
break;
}
}
if (!isSaved) {
names.push(name);
}
}
//获取一定量的颜色
let curentColors = colors || this.defaultParameters.colors;
curentColors = ColorsPickerUtil.getGradientColors(curentColors, names.length);
//生成styleGroup
let styleGroup = [];
names.forEach((name, index) => {
let color = curentColors[index];
if (name in customSettings) {
color = customSettings[name];
}
if (featureType === 'LINE') {
style.strokeColor = color;
} else {
style.fillColor = color;
}
styleGroup.push({ color: color, value: name });
}, this);
return styleGroup;
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._getWMTSUrl
* @description 根据传入的配置信息拼接wmts url。
* @param options 配置对象
*/
_getWMTSUrl(options) {
let obj = {
service: 'WMTS',
request: 'GetTile',
version: '1.0.0',
style: 'default',
layer: options.layer,
tilematrixSet: options.tileMatrixSet,
format: 'image/png'
};
let url = options.url;
url += this._getParamString(obj, url) + '&tilematrix={z}&tilerow={y}&tilecol={x}';
return url;
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createMarkerLayer
* @description 添加标记图层。
* @param {Array.} features - feature。
*/
_createMarkerLayer(layerInfo, features) {
features &&
features.forEach(feature => {
let geomType = feature.geometry.type.toUpperCase();
let defaultStyle = feature.dv_v5_markerStyle;
if (geomType === 'POINT' && defaultStyle.text) {
//说明是文字的feature类型
geomType = 'TEXT';
}
let featureInfo = this.setFeatureInfo(feature);
feature.properties['useStyle'] = defaultStyle;
feature.properties['featureInfo'] = featureInfo;
if (
geomType === 'POINT' &&
defaultStyle.src &&
(defaultStyle.src.indexOf('http://') === -1 && defaultStyle.src.indexOf('https://') === -1)
) {
//说明地址不完整
defaultStyle.src = this.server + defaultStyle.src;
}
let source = {
type: 'geojson',
data: feature
};
let index = feature.properties.index;
let layerID = geomType + '-' + index;
// image-marker
geomType === 'POINT' &&
defaultStyle.src &&
defaultStyle.src.indexOf('svg') <= -1 &&
this.map.loadImage(
defaultStyle.src,
(error, image) => {
if (error) {
console.log(error);
}
this.map.addImage(index + '', image);
this.map.addLayer({
id: layerID,
type: 'symbol',
source: source,
layout: {
'icon-image': index + '',
'icon-size': defaultStyle.scale,
visibility: layerInfo.visible
}
});
},
this
);
// svg-marker
if (geomType === 'POINT' && defaultStyle.src && defaultStyle.src.indexOf('svg') > -1) {
if (!this.svgDiv) {
this.svgDiv = document.createElement('div');
document.body.appendChild(this.svgDiv);
}
this._getCanvasFromSVG(defaultStyle.src, this.svgDiv, canvas => {
let imgUrl = canvas.toDataURL('img/png');
imgUrl &&
this.map.loadImage(
imgUrl,
(error, image) => {
if (error) {
console.log(error);
}
this.map.addImage(index + '', image);
this.map.addLayer({
id: layerID,
type: 'symbol',
source: source,
layout: {
'icon-image': index + '',
'icon-size': defaultStyle.scale,
visibility: layerInfo.visible
}
});
},
this
);
});
}
// point-line-polygon-marker
if (!defaultStyle.src) {
let layeStyle = { layout: {} };
if (geomType === 'LINESTRING' && defaultStyle.lineCap) {
geomType = 'LINE';
layeStyle.layout = { 'line-cap': defaultStyle.lineCap };
}
let visible = layerInfo.visible;
layeStyle.layout.visibility = visible;
// get style
layeStyle.style = this._transformStyleToMapBoxGl(defaultStyle, geomType);
this._addOverlayToMap(geomType, source, layerID, layeStyle);
// 若面有边框
geomType === 'POLYGON' &&
defaultStyle.strokeColor &&
this._addStrokeLineForPoly(defaultStyle, source, layerID + '-strokeLine', visible);
}
}, this);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype.setFeatureInfo
* @description 设置 feature 信息。
* @param {Array.} features - feature。
*/
setFeatureInfo(feature) {
let featureInfo;
let info = feature.dv_v5_markerInfo;
if (info && info.dataViz_title) {
//有featureInfo信息就不需要再添加
featureInfo = info;
} else {
// featureInfo = this.getDefaultAttribute();
return info;
}
let properties = feature.properties;
for (let key in featureInfo) {
if (properties[key]) {
featureInfo[key] = properties[key];
delete properties[key];
}
}
return featureInfo;
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createHeatLayer
* @description 添加热力图。
* @param {Array.} features - feature。
*/
_createHeatLayer(layerInfo, features) {
let style = layerInfo.themeSetting;
let layerOption = {};
layerOption.gradient = style.colors.slice();
layerOption.radius = parseInt(style.radius);
//自定义颜色
let customSettings = style.customSettings;
for (let i in customSettings) {
layerOption.gradient[i] = customSettings[i];
}
// 权重字段恢复
if (style.weight) {
this._changeWeight(features, style.weight);
}
let color = ['interpolate', ['linear'], ['heatmap-density']];
let length = layerOption.gradient.length;
let step = (1 / length).toFixed(2);
layerOption.gradient.forEach((item, index) => {
color.push(index * step);
if (index === 0) {
item = core_Util_Util.hexToRgba(item, 0);
}
color.push(item);
});
let paint = {
'heatmap-color': color,
'heatmap-radius': style.radius + 15,
'heatmap-intensity': { base: 1, stops: [[0, 0.8], [22, 1]] }
};
if (features[0].weight && features.length >= 4) {
let weight = [];
features.forEach(item => {
weight.push(item.weight);
});
let max = ArrayStatistic.getMax(weight);
let min = ArrayStatistic.getMin(weight);
paint['heatmap-weight'] = ['interpolate', ['linear'], ['get', 'weight'], min, 0, max, 1];
}
this.map.addLayer({
id: layerInfo.layerID,
type: 'heatmap',
source: {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: features
}
},
paint: paint
});
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._changeWeight
* @description 改变当前权重字段
* @param {Array.} features - feature。
* @param {String} weightFeild - 权重字段
*/
_changeWeight(features, weightFeild) {
this.fieldMaxValue = {};
this._getMaxValue(features, weightFeild);
let maxValue = this.fieldMaxValue[weightFeild];
features.forEach(feature => {
let attributes = feature.properties;
let value = attributes[weightFeild];
feature['weight'] = value / maxValue;
});
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._getMaxValue
* @description 获取当前字段对应的最大值,用于计算权重。
* @param {Array.} features - feature。
* @param {String} weightFeild - 权重字段
*/
_getMaxValue(features, weightField) {
let values = [],
attributes;
let field = weightField;
if (this.fieldMaxValue[field]) {
return;
}
features.forEach(feature => {
//收集当前权重字段对应的所有值
attributes = feature.properties;
attributes && parseFloat(attributes[field]) && values.push(parseFloat(attributes[field]));
});
this.fieldMaxValue[field] = ArrayStatistic.getArrayStatistic(values, 'Maximum');
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._createRangeLayer
* @description 添加分段专题图。
* @param {Array.} features - feature。
*/
_createRangeLayer(layerInfo, features) {
let fieldName = layerInfo.themeSetting.themeField;
let style = layerInfo.style;
let featureType = layerInfo.featureType;
let styleGroups = this._getRangeStyleGroup(layerInfo, features);
features = this._getFiterFeatures(layerInfo.filterCondition, features);
let source = {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: features
}
};
// 获取 expression
let expression = ['match', ['get', 'index']];
features.forEach(row => {
let tartget = parseFloat(row.properties[fieldName]);
for (let i = 0; i < styleGroups.length; i++) {
if (styleGroups[i].start <= tartget && tartget < styleGroups[i].end) {
expression.push(row.properties['index'], styleGroups[i].color);
// return;
}
}
!tartget && expression.push(row.properties['index'], 'rgba(0, 0, 0, 0)');
}, this);
expression.push('rgba(0, 0, 0, 0)');
// 获取样式
let layerStyle = { layout: {} };
if (featureType === 'LINE' && style.lineCap) {
layerStyle.layout = { 'line-cap': style.lineCap };
}
let visible = layerInfo.visible;
layerStyle.layout.visibility = visible;
layerStyle.style = this._transformStyleToMapBoxGl(style, featureType, expression);
// 添加图层
let layerID = layerInfo.layerID;
this._addOverlayToMap(featureType, source, layerID, layerStyle);
// 如果面有边框
featureType === 'POLYGON' &&
style.strokeColor &&
this._addStrokeLineForPoly(style, source, layerID + '-strokeline', visible);
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._getFiterFeatures
* @description 通过过滤条件查询满足的 feature。
* @param {String} filterCondition - 过滤条件。
* @param {array} allFeatures - 图层上的 feature 集合
*/
_getFiterFeatures(filterCondition, allFeatures) {
if (!filterCondition) {
return allFeatures;
}
let condition = this._replaceFilterCharacter(filterCondition);
let sql = 'select * from json where (' + condition + ')';
let filterFeatures = [];
for (let i = 0; i < allFeatures.length; i++) {
let feature = allFeatures[i];
let filterResult = false;
try {
filterResult = window.jsonsql.query(sql, {
properties: feature.properties
});
} catch (err) {
//必须把要过滤得内容封装成一个对象,主要是处理jsonsql(line : 62)中由于with语句遍历对象造成的问题
continue;
}
if (filterResult && filterResult.length > 0) {
//afterFilterFeatureIdx.push(i);
filterFeatures.push(feature);
}
}
return filterFeatures;
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._replaceFilterCharacter
* @description 获取过滤字符串。
* @param {String} filterString - 过滤条件。
*/
_replaceFilterCharacter(filterString) {
filterString = filterString
.replace(/=/g, '==')
.replace(/AND|and/g, '&&')
.replace(/or|OR/g, '||')
.replace(/<==/g, '<=')
.replace(/>==/g, '>=');
return filterString;
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._getRangeStyleGroup
* @description 获取分段样式。
* @param {Array.} features - feature。
*/
_getRangeStyleGroup(layerInfo, features) {
// 找出分段值
let featureType = layerInfo.featureType;
let style = layerInfo.style;
let values = [],
attributes;
let themeSetting = layerInfo.themeSetting;
let customSettings = themeSetting.customSettings;
let fieldName = themeSetting.themeField;
let segmentCount = themeSetting.segmentCount;
features.forEach(feature => {
attributes = feature.properties || feature.get('Properties');
if (attributes) {
//过滤掉非数值的数据
attributes[fieldName] &&
core_Util_Util.isNumber(attributes[fieldName]) &&
values.push(parseFloat(attributes[fieldName]));
} else if (feature.get(fieldName) && core_Util_Util.isNumber(feature.get(fieldName))) {
feature.get(fieldName) && values.push(parseFloat(feature.get(fieldName)));
}
}, this);
let segements = ArrayStatistic.getArraySegments(values, themeSetting.segmentMethod, segmentCount);
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];
value = key == 0 ? Math.floor(value * 100) / 100 : Math.ceil(value * 100) / 100 + 0.1; // 加0.1 解决最大值没有样式问题
segements[key] = Number(value.toFixed(2));
}
//获取一定量的颜色
let curentColors = themeSetting.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;
}
let start = segements[i];
let end = segements[i + 1];
let styleObj = JSON.parse(JSON.stringify(style));
styleGroups.push({ style: styleObj, color: color, start: start, end: end });
}
return styleGroups;
}
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._formatGeoJSON
* @description 格式 GeoJSON。
* @param {GeoJSON} data - GeoJSON 数据。
*/
_formatGeoJSON(data) {
let features = data.features;
features.forEach((row, index) => {
row.properties['index'] = index;
// TODO 待优化 坐标转换
// if (fileCode !== 'EPSG:4326') {
// if(row.geometry.coordinates[0] instanceof Array){
// row.geometry.coordinates.forEach((coords, index) => {
// let lnglat = this._unproject(coords);
// row.geometry.coordinates[index] = [lnglat.lng, lnglat.lat];
// }, this)
// return;
// }
// let lnglat = this._unproject(row.geometry.coordinates);
// row.geometry.coordinates = [lnglat.lng, lnglat.lat];
// }
});
return features;
}
/**
* @private
* @function mapboxgl.supermap.WebMap.prototype._excelData2Feature将
* @description csv 和 xls 文件内容转换成 geojson
* @param content 文件内容
* @param layerInfo 图层信息
* @returns {Array} feature的数组集合
*/
_excelData2Feature(dataContent) {
let fieldCaptions = dataContent.colTitles;
// let fileCode = layerInfo.projection;
//位置属性处理
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];
let x = Number(row[xfieldIndex]),
y = Number(row[yfieldIndex]);
// let coordinates = [x, y];
// TODO 待优化 坐标转换
// if (fileCode !== 'EPSG:4326') {
// if(row.geometry.coordinates[0] instanceof Array){
// row.geometry.coordinates.forEach((coords, index) => {
// let lnglat = this._unproject(coords);
// row.geometry.coordinates[index] = [lnglat.lng, lnglat.lat];
// }, this)
// return;
// }
// let lnglat = this._unproject(row.geometry.coordinates);
// row.geometry.coordinates = [lnglat.lng, lnglat.lat];
// }
//属性信息
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
* @function mapboxgl.supermap.WebMap.prototype._sendMapToUser
* @description 返回最终的 map 对象给用户,供他们操作使用。
* @param count
* @param layersLen
*/
_sendMapToUser(count, layersLen) {
if (count === layersLen) {
/**
* @event mapboxgl.supermap.WebMap#addlayerssucceeded
* @description 添加图层成功。
* @property {mapboxgl.Map} map - MapBoxGL Map 对象。
* @property {Object} mapparams - 地图信息。
* @property {string} mapParams.title - 地图标题。
* @property {string} mapParams.description - 地图描述。
* @property {Array.