Commit f6708838 authored by 邹绪超's avatar 邹绪超

fix: 优化esri-loader加载方式

parent d3664828
Pipeline #21068 passed with stages
in 3 minutes 40 seconds
const url = 'https://webapi.amap.com/maps?v=1.4.15&key=e83f64300a2a55a33fa8e4ab9a46bca6';
const url = window.location.protocol + '//webapi.amap.com/maps?';
const key = 'e83f64300a2a55a33fa8e4ab9a46bca6';
const v = '1.4.15';
const plugins = ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.DistrictSearch'];
const amapConfig = { url, plugins };
const amapConfig = { url, plugins, key, v };
export default amapConfig;
export default [
'gis/Map',
'gis/Basemap',
'gis/views/MapView',
'gis/views/SceneView',
'gis/layers/TileLayer',
'gis/layers/MapImageLayer',
'gis/layers/ElevationLayer',
'gis/Ground',
'gis/layers/SceneLayer',
'gis/layers/FeatureLayer',
'gis/layers/GroupLayer',
'gis/layers/VectorTileLayer',
'gis/layers/OpenStreetMapLayer',
'gis/geometry/Extent',
'gis/core/Collection',
'gis/Camera',
'gis/Viewpoint',
'gis/geometry/support/jsonUtils',
'gis/core/watchUtils',
'gis/Graphic',
'gis/symbols/PictureMarkerSymbol',
'gis/widgets/Popup',
'gis/layers/GraphicsLayer',
'dojox/gfx/matrix',
'gis/Color',
'gis/symbols/SimpleFillSymbol',
'gis/symbols/SimpleLineSymbol',
'gis/symbols/TextSymbol',
'gis/geometry/Point',
'dojo/_base/lang',
'gis/core/promiseUtils',
'gis/core/urlUtils',
];
import gisConfig from '../config/gis';
import esriLoader from 'esri-loader';
const loadedModules = {}; //已经加载的模块
const loadMapModules = async (modules) => {
let needLoadModules = isNeedRequest(modules);
if (Object.keys(needLoadModules).length > 0) {
let moduleArr = Object.entries(needLoadModules);
let moduleUrlsArray = moduleArr.map((item) => item[1]);
let requestloadedModules = await esriLoader.loadModules(moduleUrlsArray, gisConfig);
requestloadedModules.map((item, index) => {
loadedModules[moduleArr[index][0]] = item;
});
}
return loadedModules;
};
const isNeedRequest = (modules) => {
let needLoadModules = {};
for (let key in modules) {
if (!loadedModules[key]) needLoadModules[key] = modules[key];
}
return needLoadModules;
};
const getMapModules = () => {
return loadedModules;
};
export { getMapModules, loadMapModules };
function loadScripts(srcs) {
return new Promise((resolve, reject) => {
if (srcs && srcs.length > 0) {
var scriptOrLink;
var _src = srcs.shift();
if (_src) {
var isCSS = _src.lastIndexOf('.css') == _src.length - 4;
if (isCSS) {
scriptOrLink = document.createElement('link');
scriptOrLink.type = 'text/css';
scriptOrLink.rel = 'stylesheet';
scriptOrLink.href = _src;
} else {
scriptOrLink = document.createElement('script');
scriptOrLink.type = 'text/javascript';
scriptOrLink.charset = 'utf-8';
scriptOrLink.src = _src;
}
if (scriptOrLink) {
scriptOrLink.onload = function () {
if (srcs.length > 0) {
loadScripts(srcs).then(resolve, reject);
} else {
resolve();
}
};
scriptOrLink.onerror = reject;
document.getElementsByTagName('head')[0].appendChild(scriptOrLink);
}
}
}
});
}
export default loadScripts;
import { loadMapModules, getMapModules } from './loadMapModules';
const _ = require('lodash');
const querystring = require('querystring');
const modules = {
jsonUtils: 'gis/geometry/support/jsonUtils',
};
const layerOperation = {
isInGroup(lyr, reorderGroups = []) {
let { lyrIndex, groupIndex } = this.getGroup(lyr, reorderGroups);
return _.isNumber(lyrIndex) && groupIndex >= 0;
},
getLayerWeight(lyr, reorderGroups) {
if ('graphics' == lyr.type) {
let { lyrIndex, groupIndex } = this.getGroup(lyr, reorderGroups);
if (this.isInGroup(lyr, reorderGroups)) return (groupIndex + 1) * 100 + lyrIndex;
} else {
return -1;
}
},
registerReorderStrategy: (groupName, reorderGroups = []) => {
var index = reorderGroups.indexOf(groupName);
return index < 0 && reorderGroups.push(groupName);
},
getGroup(lyr, reorderGroups) {
let groupName = lyr.order.split('-')[0],
lyrIndex = Number(lyr.order.split('-')[1]),
groupIndex = reorderGroups.indexOf(groupName);
return { lyrIndex, groupIndex };
},
};
const urlUtils = {
urlToObject: (url) => {
let [path, params] = url.split('?');
let query = querystring.parse(params);
return { path, query };
},
objectToUrl: (url, query) => {},
};
const geomUtils = {
toGeometry(jsonObj, view) {
const { jsonUtils } = getMapModules();
if (jsonObj) {
jsonObj.spatialReference = {
wkid: view.spatialReference.wkid,
};
return jsonUtils.fromJSON(jsonObj);
}
},
};
const loadUtilMapModules = async () => {
await loadMapModules(modules);
};
const mapUtils = {
getNearestScale(extent, view) {
let resolution = extent.width / view.width,
zoom = 0,
nearestScale = -1,
diff = Number.POSITIVE_INFINITY;
if (view.map.basemap && view.map.basemap.baseLayers.length > 0) {
view.map.basemap.baseLayers.getItemAt(0).tileInfo.lods.forEach(
function (item) {
if (item.resolution >= resolution) {
var difftemp = item.resolution - resolution;
if (difftemp < diff) {
diff = difftemp;
nearestScale = item.scale;
zoom = item.level;
}
}
}.bind(this),
);
}
return { scale: nearestScale, zoom };
},
};
export { layerOperation, urlUtils, loadUtilMapModules, geomUtils, mapUtils };
/************************************************************************************************
* Copyright ©, 2018-2020, MapGIS
* @Description: 地图模块加载器
* @Author: Chenzilong
* @History: 1、初始版本 2018-11-19 Chenzilong
* @Usage: 高阶组件的实用 => 通过封装一个高阶组件,先加载地图相对应的模块,加载完成,再来加载地图资源,这样在封装的组件里面就不会有异步过程,并且还使用了全局变量来进行组件缓存组件
*
* //加载模块
* const modules = { Graphic:"esri/Graphic",GraphicsLayer:"esri/layers/GraphicsLayer" }; //需要加载的地图模块定义
* 1、class修饰符方式
* @withModule(modules) //使用修饰符修饰组件
* class SomeComponent extends React.Component{}
* 2、函数调用方式
* const WrappedComponent = withModule(modules)(SomeComponent)
* //使用组件
* <WrappedComponent wrappedComponentRef={ref=>this.ref = ref}/> //获取组件实例引用使用wrappedComponentRef
* //获取模块
* 组件内部通过 const {module:{Graphic,GraphicsLayer}} = this.props 获取被加载模块
*
* withModule会在加载完所有模块后显示组件,并将模块通过props.module注入到组件中
************************************************************************************************/
import React from 'react';
import { loadMapModules, getMapModules } from './loadMapModules';
const withModule = (modules) => {
return function wrapper(Component) {
class Proxy extends React.Component {
state = {
loaded: false,
};
unmounted = false;
componentDidMount() {
if (modules) {
this.loadModules();
} else {
this.setState({ loaded: true });
}
}
componentWillUnmount() {
this.unmounted = true;
}
async loadModules() {
await loadMapModules(modules);
if (!this.unmounted) this.setState({ loaded: true });
}
render() {
const { wrappedComponentRef, ...rest } = this.props;
return this.state.loaded ? (
<Component modules={getMapModules()} {...rest} ref={wrappedComponentRef} />
) : null;
}
}
return Proxy;
};
};
export default withModule;
import mapsettings from '../mapData';
import MapManganer from '../index';
import MapView from '../index';
export default class CreateMap extends React.Component {
constructor(props) {
......@@ -8,17 +8,44 @@ export default class CreateMap extends React.Component {
if (!window._config) {
window._config = {
site: '',
mapsettings: mapsettings,
useCoverMap: true,
};
}
}
state = {
loaded: false,
mapsettings: null,
};
componentDidMount() {
window.mapManager = this.mapManganerRef.current;
let url = location.origin + '/CityInterface/rest/services.svc/GetWebSiteConfig?client=city';
fetch(url)
.then((data) => data.json())
.then((response) => {
let data = response[0]['mapsettings'];
this.setState({
mapsettings: data,
loaded: true,
});
})
.catch(() => {
new Error('请求资源失败');
});
}
render() {
return <MapManganer mapsettings={mapsettings} ref={this.mapManganerRef} />;
const { loaded, mapsettings } = this.state;
return (
<>
{loaded ? (
<MapView mapsettings={mapsettings} ref={this.mapManganerRef} />
) : (
<div>
<h1>加载中.....</h1>
</div>
)}
</>
);
}
}
// All material copyright GIS, All Rights Reserved, unless otherwise specified.
// See https://js.gis.com/4.3/gis/copyright.txt for details.
//>>built
define('require exports gis/core/tsSupport/declareExtendsHelper gis/core/tsSupport/decorateHelper gis/core/Accessor gis/core/accessorSupport/decorators'.split(
' ',
), function (c, k, g, f, h, e) {
c = (function (c) {
function b() {
var a = c.call(this) || this;
a._groups = null;
a._groups = {};
return a;
}
g(b, c);
b.prototype.destroy = function () {
this.removeAll();
this._groups = null;
};
Object.defineProperty(b.prototype, 'size', {
get: function () {
var a = 0,
d = this._groups,
b;
for (b in d) a += d[b].length;
return a;
},
enumerable: !0,
configurable: !0,
});
b.prototype.add = function (a, b) {
if (!this._isPromise(a) && !Array.isArray(a)) return this;
b = this._getOrCreateGroup(b);
if (Array.isArray(a)) for (var d = 0; d < a.length; d++) b.push(a[d]);
else b.push(a);
this.notifyChange('size');
return this;
};
b.prototype.has = function (a) {
a = this._groups[a];
return !!a && 0 < a.length;
};
b.prototype.remove = function (a) {
if (Array.isArray(a)) a.forEach(this.remove.bind(this));
else {
a = this._getGroup(a);
if (!a) return this;
for (var b = 0; b < a.length; b++)
!a[b].isFulfilled() && !a[b].isCanceled() && a[b].cancel();
a.length = 0;
this.notifyChange('size');
}
return this;
};
b.prototype.removeAll = function () {
var a = this._groups,
b;
for (b in a) this.remove(b), delete a[b];
return this;
};
b.prototype._isPromise = function (a) {
return a && !!a.cancel && !!a.isCanceled;
};
b.prototype._getOrCreateGroup = function (a) {
return this._getGroup(a) || (this._groups[this._ensureGroupName(a)] = []);
};
b.prototype._getGroup = function (a) {
return this._groups[this._ensureGroupName(a)];
};
b.prototype._ensureGroupName = function (a) {
return a || '_default_';
};
return b;
})(e.declared(h));
f([e.property({ readOnly: !0 })], c.prototype, 'size', null);
return (c = f([e.subclass()], c));
});
import TilemetaUtils from './support/TilemetaUtils';
console.log('Amap-tilelayer');
export default function (TileLayer, lang, promiseUtils) {
import { getMapModules } from '../../core/loadMapModules';
export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
var dpi = 96, //pixel per inch
level = 99, //地图缩放级数
maxlevel = 18, //地图总级数
......
import TilemetaUtils from './support/TilemetaUtils';
import { getMapModules } from '../../core/loadMapModules';
//百度地图
export default function (TileLayer, promiseUtils) {
export default function ({ TileLayer, promiseUtils } = getMapModules()) {
var dpi = 96, //pixel per inch
level = 99, //地图缩放级数
maxlevel = 20, //地图总级数
......
// 谷歌地图 (由TileLayer扩展)
// create by czl 2017/12/2
import TilemetaUtils from './support/TilemetaUtils';
import { getMapModules } from '../../core/loadMapModules';
export default function (TileLayer, lang, promiseUtils) {
export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
var dpi = 96, //pixel per inch
level = 99, //地图缩放级数
levelStart = 3, // 起始级数
......
// All material copyright GIS, All Rights Reserved, unless otherwise specified.
// See https://js.gis.com/4.3/gis/copyright.txt for details.
//>>built
//streets、light、dark、satellite、streets-satellite、wheatpaste、streets-basic、comic、outdoors、run-bike-hike、pencil、pirates、emerald、high-contrast
define(['gis/config', 'gis/layers/WebTileLayer'], function (a, b) {
import { getMapModules } from '../../core/loadMapModules';
export default function ({ config, WebTileLayer } = getMapModules()) {
let a = config,
b = WebTileLayer;
a.request.corsEnabledServers.push('a.tile.mapbox.org', 'b.tile.mapbox.org', 'c.tile.mapbox.org');
return b.createSubclass({
declaredClass: 'gis.layers.MapBoxLayer',
......@@ -15,4 +15,4 @@ define(['gis/config', 'gis/layers/WebTileLayer'], function (a, b) {
type: { value: 'mapbox', json: { read: !1 } },
},
});
});
}
// 自定义底图 (由TileLayer扩展)
// create by zxc 2020/7/16
define([
'gis/layers/TileLayer',
'dojo/_base/lang',
'gis/core/promiseUtils',
'./support/TilemetaUtils',
'gis/request',
], function (TileLayer, lang, promiseUtils, TilemetaUtils, request) {
import TilemetaUtils from './support/TilemetaUtils';
import { getMapModules } from '../../core/loadMapModules';
export default function ({ TileLayer, lang, promiseUtils, request } = getMapModules()) {
var dpi = 96, //pixel per inch
level = 99, //地图缩放级数
levelStart = 0, // 起始级数
......@@ -103,4 +100,4 @@ define([
);
},
});
});
}
// 天地图 (由TileLayer扩展)
// create by czl 2017/12/2
define([
'gis/layers/TileLayer',
'dojo/_base/lang',
'gis/core/promiseUtils',
'./support/TilemetaUtils',
], function (TileLayer, lang, promiseUtils, TilemetaUtils) {
import TilemetaUtils from './support/TilemetaUtils';
import { getMapModules } from '../../core/loadMapModules';
export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
var dpi = 96, //pixel per inch
level = 20, //地图总级数
levelStart = 3, // 起始级数
......@@ -165,4 +163,4 @@ define([
});
},
});
});
}
// 自定义底图 (由TileLayer扩展)
// create by ysq 2019/5/8
define([
'gis/layers/TileLayer',
'dojo/_base/lang',
'gis/core/promiseUtils',
'./support/TilemetaUtils',
'gis/request',
], function (TileLayer, lang, promiseUtils, TilemetaUtils, request) {
import TilemetaUtils from './support/TilemetaUtils';
import { getMapModules } from '../../core/loadMapModules';
export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
var dpi = 96, //pixel per inch
level = 99, //地图缩放级数
levelStart = 0, // 起始级数
......@@ -97,4 +94,4 @@ define([
});
},
});
});
}
// create by ysq 2018/11/7
define([
'gis/layers/TileLayer',
'dojo/_base/lang',
'gis/core/promiseUtils',
'./support/TilemetaUtils',
], function (TileLayer, lang, promiseUtils, TilemetaUtils) {
import TilemetaUtils from './support/TilemetaUtils';
import { getMapModules } from '../../core/loadMapModules';
export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
var dpi = 96, //pixel per inch
level = 19, //地图总级数
levelStart = 9, // 起始级数
......@@ -51,12 +49,4 @@ define([
});
},
});
});
import gisConfig from '../../config/gis';
const modules = [
'gis/layers/TileLayer',
'dojo/_base/lang',
'gis/core/promiseUtils',
'./support/TilemetaUtils',
];
}
import { loadMapModules } from '../../core/loadMapModules';
import AMapTileLayer from './AMapTileLayer';
import BaiduTileLayer from './BaiduTileLayer';
import GoogleTileLayer from './GoogleTileLayer';
import MapBoxLayer from './MapBoxLayer';
import PipenetTileLayer from './PipenetTileLayer';
import TiandituTileLayer from './TiandituTileLayer';
import UserTileLayer from './UserTileLayer';
import WMTSTileLayer from './WMTSTileLayer';
const modules = {
TileLayer: 'gis/layers/TileLayer',
lang: 'dojo/_base/lang',
promiseUtils: 'gis/core/promiseUtils',
config: 'gis/config',
WebTileLayer: 'gis/layers/WebTileLayer',
request: 'gis/request',
};
const loadMapLayerModules = async () => {
await loadMapModules(modules);
};
export {
loadMapLayerModules,
AMapTileLayer,
BaiduTileLayer,
GoogleTileLayer,
MapBoxLayer,
PipenetTileLayer,
TiandituTileLayer,
UserTileLayer,
WMTSTileLayer,
};
This source diff could not be displayed because it is too large. You can view the blob instead.
import React from 'react';
import PropTypes from 'prop-types';
import amapConfig from './config/amap';
import gisModules from './config/module';
import AMapTileLayer from './extensions/layers/AMapTileLayer';
import GoogleTileLayer from './extensions/layers/GoogleTileLayer';
import * as Utils from './utils/Utils';
import * as GeomUtils from './utils/GeometryTool';
import { layerOperation, loadUtilMapModules, geomUtils, mapUtils } from './core/utils';
import { Spin } from 'antd';
import {
loadMapLayerModules,
AMapTileLayer,
BaiduTileLayer,
GoogleTileLayer,
MapBoxLayer,
PipenetTileLayer,
TiandituTileLayer,
UserTileLayer,
WMTSTileLayer,
} from './extensions/layers/index';
import withModule from './core/withModule';
import loadScripts from './core/loadScripts';
const _ = require('lodash');
const modules = {
Map: 'gis/Map',
Basemap: 'gis/Basemap',
MapView: 'gis/views/MapView',
SceneView: 'gis/views/SceneView',
TileLayer: 'gis/layers/TileLayer',
MapImageLayer: 'gis/layers/MapImageLayer',
ElevationLayer: 'gis/layers/ElevationLayer',
Ground: 'gis/Ground',
SceneLayer: 'gis/layers/SceneLayer',
FeatureLayer: 'gis/layers/FeatureLayer',
GroupLayer: 'gis/layers/GroupLayer',
VectorTileLayer: 'gis/layers/VectorTileLayer',
OpenStreetMapLayer: 'gis/layers/OpenStreetMapLayer',
Extent: 'gis/geometry/Extent',
Collection: 'gis/core/Collection',
Camera: 'gis/Camera',
Viewpoint: 'gis/Viewpoint',
jsonUtils: 'gis/geometry/support/jsonUtils',
watchUtils: 'gis/core/watchUtils',
Graphic: 'gis/Graphic',
PictureMarkerSymbol: 'gis/symbols/PictureMarkerSymbol',
Popup: 'gis/widgets/Popup',
GraphicsLayer: 'gis/layers/GraphicsLayer',
matrix: 'dojox/gfx/matrix',
Color: 'gis/Color',
SimpleFillSymbol: 'gis/symbols/SimpleFillSymbol',
SimpleLineSymbol: 'gis/symbols/SimpleLineSymbol',
TextSymbol: 'gis/symbols/TextSymbol',
Point: 'gis/geometry/Point',
};
export default class MapManager extends React.Component {
@withModule(modules)
export default class Map extends React.Component {
static defaultProps = {
id: '#jsmap',
width: '100%',
height: '420px',
style: {
width: '100%',
height: '420px',
},
mapsettings: {},
modules: gisModules,
viewRef: React.createRef(),
};
state = {
viewReady: true, //视图准备的条件 : 1.has map 2. has container 3. extent
loaded: true, //显示地图 create view
};
constructor(props) {
super(props);
this.mapRef = React.createRef();
this.initializeVariables();
}
async initializeVariables() {
initializeVariables = () => {
this.view = null;
this.map = null;
this.basemap = null;
this.tipManager = null;
this.AreaLayerSum = null;
this.reorderGroups = [];
this.hidetipHandler = null;
this.showtipHandler = null;
this.renderMenu = true;
this.reorderGroups = [];
this.basemaps = [];
this.mapsettings = this.props.mapsettings;
}
this.setInitialViewpoint = this.setInitialViewpoint.bind(this);
this.layerAddedHandler = this.layerAddedHandler.bind(this);
this.matrixLayerViewCreated = this.matrixLayerViewCreated.bind(this);
this.matrixLayerMoveStart = this.matrixLayerMoveStart.bind(this);
this.matrixLayerViewChange = this.matrixLayerViewChange.bind(this);
this.matrixLayerMoveEnd = this.matrixLayerMoveEnd.bind(this);
};
getStyle() {
return {
width: this.props.width,
height: this.props.height,
};
}
loadAMapScript = () => {
let amapUrl = `${amapConfig.url}v=${amapConfig.v}&key=${
amapConfig.key
}&plugin=${amapConfig.plugins.join(',')}`;
return loadScripts([amapUrl]);
};
async componentDidMount() {
let moduleArr = await Utils.asyncLoadModules(this.props.modules);
await GeomUtils.loadAllDependencies();
this.getModules(moduleArr);
this.createMapLayers();
componentDidMount = async () => {
await loadMapLayerModules();
await loadUtilMapModules();
this.renderView();
this.loadAMap();
}
loadAMap() {
console.log('load AMap');
let url = 'https://webapi.amap.com/maps?v=1.4.15&key=e83f64300a2a55a33fa8e4ab9a46bca6';
fetch(url).then((params) => {
console.log(params);
console.log(window);
// let plugins = ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.DistrictSearch']
// AMap.plugins(plugins, () => {
// })
let UIurl = '//webapi.amap.com/ui/1.1/main.js';
fetch(UIurl, () => {});
});
}
getModules(moduleArr) {
this.loadedModules = {
Map: moduleArr[0],
BaseMap: moduleArr[1],
MapView: moduleArr[2],
SceneView: moduleArr[3],
TileLayer: moduleArr[4],
MapImageLayer: moduleArr[5],
ElevationLayer: moduleArr[6],
Ground: moduleArr[7],
SceneLayer: moduleArr[8],
FeatureLayer: moduleArr[9],
GroupLayer: moduleArr[10],
VectorTileLayer: moduleArr[11],
OpenStreetMapLayer: moduleArr[12],
Extent: moduleArr[13],
Collection: moduleArr[14],
Camera: moduleArr[15],
Viewpoint: moduleArr[16],
jsonUtils: moduleArr[17],
watchUtils: moduleArr[18],
Graphic: moduleArr[19],
PictureMarkerSymbol: moduleArr[20],
Popup: moduleArr[21],
GraphicsLayer: moduleArr[22],
matrix: moduleArr[23],
Color: moduleArr[24],
SimpleFillSymbol: moduleArr[25],
SimpleLineSymbol: moduleArr[26],
TextSymbol: moduleArr[27],
Point: moduleArr[28],
lang: moduleArr[29],
promiseUtils: moduleArr[30],
urlUtils: moduleArr[31],
};
Utils.bindUrlUtils(this.loadedModules.urlUtils);
}
createMapLayers() {
this.loadedModules.AMapTileLayer = AMapTileLayer(
this.loadedModules.TileLayer,
this.loadedModules.lang,
this.loadedModules.promiseUtils,
);
this.loadedModules.GoogleTileLayer = GoogleTileLayer(
this.loadedModules.TileLayer,
this.loadedModules.lang,
this.loadedModules.promiseUtils,
);
}
};
renderView() {
renderView = () => {
this.addLayerProxy();
this.addMap();
this.addBasemaps();
this.addLayerReorder();
this.addLayers();
if ('2d' == this.mapsettings.type.toLowerCase()) {
this.addMatrixLayer(); //加入空的GraphicsLayer,用于获取地图的moveStart,viewChange,moveEnd事件
}
this.addMatrixLayer();
this.addTipManager();
if (this.renderMenu && this.view && this.view.type == '2d') {
this.loadedModules.watchUtils.whenTrue(
this.view,
'ready',
this.renderRightClickMenu.bind(this),
);
this.loadedModules.watchUtils.whenTrueOnce(this.view, 'ready', this.renderRoamte.bind(this));
// edit by zhangyao on 2018/11/1
this.hidetipHandler = this.loadedModules.watchUtils.whenTrue(
this.view,
'stationary',
function (e) {
console.log('地图禁止');
// this.tipManager.$el.show();
// this.$el.find(".gis-view-surface div.gis-display-object").show();
if (this.updateLayerView) this.updateLayerView();
}.bind(this),
);
this.showtipHandler = this.loadedModules.watchUtils.whenFalse(
this.view,
'stationary',
function (e) {
if (this.view.animation) {
// 判断地图是否在缩放
// this.tipManager.$el.hide();
// this.$el.find(".gis-view-surface div.gis-display-object").hide();
console.log('地图移动');
}
}.bind(this),
);
}
}
this.bindViewEvents();
};
addLayerProxy = () => {};
addLayerProxy() {}
changeState = (key, value) => {
this.setState({ key, value });
};
addMap() {
const mapsettings = this.mapsettings;
this.map = new this.loadedModules.Map();
if (this.mapsettings.ground) {
if ('string' == typeof this.mapsettings.ground) {
this.map.ground = this.mapsettings.ground;
addMap = () => {
const { Map, Collection, MapView, Ground, SceneView } = this.props.modules;
const {
type,
ground,
resizeAlign,
viewingMode,
environment,
clippingArea,
extent,
qualityProfile,
constraints,
} = this.mapsettings;
const viewRef = this.props.viewRef;
this.map = new Map();
this.addGround({ ground, Ground, Collection });
switch (type.toLowerCase()) {
case '2d':
this.createMapView({ MapView, viewRef, resizeAlign });
break;
case '3d':
this.createMapSceneView({
SceneView,
viewRef,
viewingMode,
environment,
clippingArea,
extent,
qualityProfile,
});
break;
default:
break;
}
if (constraints) this.view.constraints = constraints;
this.viewpoint = this.mapsettings.viewpoint;
this.view.then(this.setInitialViewpoint);
this.changeState('loaded', true);
};
addGround = ({ ground, Ground, Collection }) => {
if (ground) {
if ('string' == typeof ground) {
this.map.ground = ground;
} else {
var layers = mapsettings.ground.layers,
layer,
groundlayers = new this.loadedModules.Collection();
layers.forEach(
function (layerconfig) {
this.createLayer(layerconfig, groundlayers, false, '');
}.bind(this),
);
let layers = ground.layers,
groundLayers = new Collection();
layers.map((layerConfig) => {
this.createLayer(layerConfig, groundLayers, false, '');
});
this.map.ground = new Ground({
layers: groundlayers,
layers: groundLayers,
});
}
}
if ('2d' == mapsettings.type.toLowerCase()) {
this.view = new this.loadedModules.MapView({
map: this.map,
container: this.mapRef.current,
manager: this,
resizeAlign: mapsettings.resizeAlign || 'top-left',
});
} else if ('3d' == mapsettings.type.toLowerCase()) {
this.view = new this.loadedModules.SceneView({
map: this.map,
manager: this,
qualityProfile: mapsettings.qualityProfile || 'high',
container: this.mapRef.current,
});
if (mapsettings.viewingMode) {
this.view.viewingMode = mapsettings.viewingMode;
}
if (mapsettings.environment) {
this.view.environment = mapsettings.environment;
}
if (mapsettings.clippingArea) {
this.view.clippingArea = new Extent(mapsettings.clippingArea);
}
if (mapsettings.extent) {
this.view.extent = new Extent(mapsettings.extent);
}
}
//设置View初始范围
this.viewpoint = mapsettings.viewpoint;
this.setInitialViewpoint = this.setInitialViewpoint.bind(this);
this.view.then(this.setInitialViewpoint);
}
};
setInitialViewpoint() {
window.view = this.view;
createMapView = ({ MapView, viewRef, resizeAlign }) => {
this.view = new MapView({
map: this.map,
container: viewRef.current,
manager: this,
resizeAlign: resizeAlign || 'top-left',
});
};
createMapSceneView = ({
SceneView,
viewRef,
viewingMode,
environment,
clippingArea,
extent,
qualityProfile,
}) => {
this.view = new SceneView({
map: this.map,
manager: this,
qualityProfile: qualityProfile || 'high',
container: viewRef.current,
});
if (viewingMode) this.view.viewingMode = viewingMode;
if (environment) this.view.environment = environment;
if (clippingArea) this.view.clippingArea = clippingArea;
if (extent) this.view.extent = extent;
};
setInitialViewpoint = () => {
const { Viewpoint, Camera } = this.props.modules;
if (this.viewpoint) {
this.initialViewpoint = new this.loadedModules.Viewpoint();
if (this.viewpoint.camera) {
this.initialViewpoint.camera = new this.loadedModules.Camera(this.viewpoint.camera);
this.viewpoint.targetGeometry &&
(this.initialViewpoint.targetGeometry = GeomUtils.toGeometry(
this.viewpoint.targetGeometry,
));
this.viewpoint.scale && (this.initialViewpoint.scale = this.viewpoint.scale);
this.viewpoint.rotation && (this.initialViewpoint.rotation = this.viewpoint.rotation);
}
var geom = this.initialViewpoint.targetGeometry;
this.initialViewpoint = new Viewpoint();
this.viewpoint.camera && (this.initialViewpoint.camera = new Camera(this.viewpoint.camera));
this.viewpoint.targetGeometry &&
(this.initialViewpoint.targetGeometry = geomUtils.toGeometry(
this.viewpoint.targetGeometry,
this.view,
));
this.viewpoint.scale && (this.initialViewpoint.scale = this.viewpoint.scale);
this.viewpoint.rotation && (this.initialViewpoint.rotation = this.viewpoint.rotation);
let geom = this.initialViewpoint.targetGeometry;
if (geom && !(geom.xmin == 0 && geom.ymin == 0 && geom.xmax == 0 && geom.ymax == 0)) {
if (geom.type == 'extent') {
var scale = this.getNearestScale(geom.clone());
let { zoom, scale } = mapUtils.getNearestScale(geom.clone(), this.view);
if (!this.mapsettings.scale) {
this.mapsettings.scale = scale;
this.mapsettings.zoom = zoom;
}
if (scale != -1) {
this.initialViewpoint.scale = scale;
}
......@@ -250,7 +241,6 @@ export default class MapManager extends React.Component {
} else {
this.initialViewpoint = this.view.viewpoint;
}
if (
this.mapsettings.areasettings &&
this.mapsettings.areasettings.areaName.toLowerCase().indexOf('offlinearea') > -1 &&
......@@ -261,170 +251,135 @@ export default class MapManager extends React.Component {
this.areaLayerInit = true;
return;
}
if (!this.areaLayerInit) {
this.mapsettings.useCoverMap = _.isUndefined(this.mapsettings.useCoverMap)
? true
: !!this.mapsettings.useCoverMap;
if (this.mapsettings.useCoverMap && !this.areaLayerInit) {
this.loadAreaLayer();
} else {
this.showPipeNetLayer();
}
}
};
addBasemaps() {
addBasemaps = () => {
let basemapconfigs = this.mapsettings.basemaps;
this.basemaps = [];
if (basemapconfigs) {
basemapconfigs.forEach(
function (basemapconfig) {
this.basemaps.push(this.createBasemap(basemapconfig));
}.bind(this),
);
basemapconfigs.map((basemapconfig) => {
this.basemaps.push(this.createBasemap(basemapconfig));
});
} else {
this.basemaps.push(this.createDefaultBasemap());
}
if (this.basemaps.length) this.map.basemap = this.basemaps[0];
};
if (this.basemaps.length) {
this.map.basemap = this.basemaps[0];
}
}
createDefaultBasemap = () => {};
createBasemap(basemap) {
var bm;
createBasemap = (basemap) => {
const { Collection, Basemap } = this.props.modules;
let bm;
if (basemap) {
if ('string' == typeof basemap) {
bm = basemap;
} else {
// var layer,
var bls = new this.loadedModules.Collection(),
let bls = new Collection(),
id = basemap.id,
title = basemap.title,
thumbnailUrl = basemap.thumbnailUrl,
baseLayers = basemap.baseLayers;
baseLayers.forEach(
function (layerconfig) {
this.createLayer(layerconfig, bls, false, 'baseMap');
}.bind(this),
);
bm = new this.loadedModules.BaseMap({
id: id,
title: title,
thumbnailUrl: thumbnailUrl,
baseLayers.map((layerconfig) => {
this.createLayer(layerconfig, bls, false, 'baseMap');
});
bm = new Basemap({
id,
title,
thumbnailUrl,
baseLayers: bls,
});
}
}
return bm;
}
createDefaultBasemap() {}
};
addLayerReorder() {
this.layerAddedHandler = this.layerAddedHandler.bind(this);
addLayerReorder = () => {
this.map.layers.on('after-add', this.layerAddedHandler);
}
};
layerAddedHandler(event) {
var lyr = event.item;
if ('graphics' === lyr.type) {
if (this.isInGroup(lyr)) {
var layer = this.map.layers.find(
function (l) {
return this.getLayerWeight(l) > this.getLayerWeight(lyr);
}.bind(this),
);
layerAddedHandler = (event) => {
let lyr = event.item;
let reorderGroups = this.reorderGroups;
if ('graphics' == lyr.type) {
if (layerOperation.isInGroup(lyr, reorderGroups)) {
let layer = this.map.layers.find((layer) => {
return (
layerOperation.getLayerWeight(layer, reorderGroups) >
layerOperation.getLayerWeight(lyr, reorderGroups)
);
});
if (layer) {
this.map.layers.reorder(lyr, this.map.layers.indexOf(layer) - 1);
}
}
}
}
isInGroup(lyr) {
var groupName = lyr.order.split('-')[0],
lyrIndex = Number(lyr.order.split('-')[1]),
groupIndex = this.reorderGroups.indexOf(groupName);
return _.isNumber(lyrIndex) && groupIndex >= 0;
}
getLayerWeight() {
if ('graphics' === lyr.type) {
var groupName = lyr.order.split('-')[0],
lyrIndex = Number(lyr.order.split('-')[1]),
groupIndex = this.reorderGroups.indexOf(groupName);
if (_.isNumber(lyrIndex) && groupIndex >= 0) {
return (groupIndex + 1) * 100 + lyrIndex;
} else {
return 0;
}
} else {
return -1;
}
}
registerReorderStrategy(groupName) {
var index = this.reorderGroups.indexOf(groupName);
index < 0 && this.reorderGroups.push(groupName);
}
};
addLayers() {
let layerconfigs = this.mapsettings.layers;
addLayers = () => {
let layerconfigs = this.props.mapsettings.layers;
if (layerconfigs) {
var layer;
layerconfigs.forEach(
function (layerconfig) {
if (!layerconfig.id) return;
this.createLayer(layerconfig, this.map, false, 'pipeLayer');
}.bind(this),
);
layerconfigs.map((layerconfig) => {
if (!layerconfig.id) return;
this.createLayer(layerconfig, this.map, false, 'pipeLayer');
});
}
}
};
addMatrixLayer() {
this._matrixLayer = new this.loadedModules.GraphicsLayer();
addMatrixLayer = () => {
if (this.view.type != '2d') return;
let { GraphicsLayer } = this.props.modules;
this._matrixLayer = new GraphicsLayer();
this.view.map.add(this._matrixLayer);
this.matrixLayerViewCreated = this.matrixLayerViewCreated.bind(this);
this.matrixLayerMoveStart = this.matrixLayerMoveStart.bind(this);
this.matrixLayerViewChange = this.matrixLayerViewChange.bind(this);
this.matrixLayerMoveEnd = this.matrixLayerMoveEnd.bind(this);
this.view.whenLayerView(this._matrixLayer).then(this.matrixLayerViewCreated);
}
};
matrixLayerViewCreated(lyrView) {
matrixLayerViewCreated = (lyrView) => {
if (lyrView) {
lyrView.on('moveStart', this.matrixLayerMoveStart);
lyrView.on('viewChange', this.matrixLayerViewChange);
lyrView.on('moveEnd', this.matrixLayerMoveEnd);
}
}
};
matrixLayerMoveStart(lyrView) {
var m = this.getLayerViewMatrix(lyrView);
matrixLayerMoveStart = (lyrView) => {
let m = this.getLayerViewMatrix(lyrView);
this.view.emit('moveStart', {
layerView: lyrView,
matrix: m,
matrixString: this.toMatrixString(m),
});
}
};
matrixLayerViewChange(lyrView) {
var m = this.getLayerViewMatrix(lyrView);
matrixLayerViewChange = (lyrView) => {
let m = this.getLayerViewMatrix(lyrView);
this.view.emit('viewChange', {
layerView: lyrView,
matrix: m,
zooming: m.xx != 1,
matrixString: this.toMatrixString(m),
});
}
};
matrixLayerMoveEnd(lyrView) {
var m = this.getLayerViewMatrix(lyrView);
matrixLayerMoveEnd = (lyrView) => {
let m = this.getLayerViewMatrix(lyrView);
this.view.emit('moveEnd', {
layerView: lyrView,
matrix: m,
matrixString: this.toMatrixString(m),
});
}
};
getLayerViewMatrix(lyrView) {
let matrix = this.loadedModules.matrix;
var m = matrix.clone(matrix.identify);
getLayerViewMatrix = (lyrView) => {
const { matrix } = this.props.modules;
let m = matrix.clone(matrix.identify);
if (
lyrView.graphicsView &&
lyrView.graphicsView._frontGroup &&
......@@ -446,9 +401,9 @@ export default class MapManager extends React.Component {
m = matrix.clone(targetMatrix);
}
return m;
}
};
toMatrixString(m) {
toMatrixString = (m) => {
return (
'matrix(' +
[
......@@ -461,65 +416,94 @@ export default class MapManager extends React.Component {
].join() +
')'
);
}
addTipManager() {
this.openedPopups = [];
//后期做tipMananger
// this.tipManager = new TipManager({
// view: this.view,
// container: this.$el.find(".gis-view-surface")
// });
// this.tipManager.render();
}
};
renderRightClickMenu() {}
addTipManager = () => {};
renderRoamte() {}
bindViewEvents = () => {};
createLayer(config, collection, returnLayer, layerType) {
var layer;
var layers = [];
if (config.url) {
config.url = this.loadedModules.urlUtils.getUrl(config.url);
loadAreaLayer = () => {
let url = amapConfig.url;
this.areaLayerInit = true;
this.extent = {
spatialReference: {
wkid: 4526,
},
xmin: 0,
ymin: 0,
xmax: 0,
ymax: 0,
};
let areasettings = this.mapsettings.areasettings;
if (!areasettings) return;
let area = areasettings.areaName.split(',');
if (window.navigator.onLine == true && area.length == 1) {
this.loadAMapScript()
.then(() => {
this.getAreaLayer();
})
.catch(() => new Error('加载高德地图资源失败'));
} else {
}
switch (config.layerType.toLowerCase()) {
};
getAreaLayer = () => {};
createLayer = (config, collection, returnLayer, mapType) => {
let layer,
layers = [];
let proxyUrl, configString, configv, configva, configi, configia;
let layerType = config.layerType.toLowerCase();
const {
TileLayer,
MapImageLayer,
ElevationLayer,
SceneLayer,
FeatureLayer,
GroupLayer,
OpenStreetMapLayer,
} = this.props.modules;
config.url = this.getLayerUrl(config.url);
switch (layerType) {
case 'tilelayer':
layer = new this.loadedModules.TileLayer(config);
layer = new TileLayer(config);
break;
case 'pipenetlayer':
case 'mapimagelayer':
layer = new this.loadedModules.MapImageLayer(
Utils._.extend({}, config, {
token: _config.token,
layer = new MapImageLayer(
_.extend({}, config, {
token: _config && _config.token,
client: 'webgis',
visible: false,
}),
);
layer.then(
function () {
layer.visible = true;
if (layer.hasAnnotation) {
// layer.annotationLayer = this.addAnnotationLayer(layer.title, layer.url, config.visible);
layer.annotationLayer = this.addAnnotationLayer(
layer.title,
layer.url,
config.visible,
);
}
}.bind(this),
);
break;
case 'elevationlayer':
layer = new this.loadedModules.ElevationLayer(config);
layer = new ElevationLayer(config);
break;
case 'scenelayer':
layer = new this.loadedModules.SceneLayer(config);
layer = new SceneLayer(config);
break;
case 'featurelayer':
layer = new this.loadedModules.FeatureLayer(config);
layer = new FeatureLayer(config);
break;
case 'grouplayer':
var layers = config.layers.map(function (c) {
layers = config.layers.map(function (c) {
return this.createLayer(c, [], true, '');
}, this);
layer = new this.loadedModules.GroupLayer(
Utils._.extend({}, config, {
layer = new GroupLayer(
_.extend({}, config, {
layers: layers,
}),
);
......@@ -528,25 +512,24 @@ export default class MapManager extends React.Component {
case 'google-i':
case 'google-i-a':
case 'google-ia':
layer = new this.loadedModules.GoogleTileLayer(
Utils._.extend(config, {
layer = new GoogleTileLayer()(
_.extend(config, {
url: 'http://fack.com',
}),
);
break;
case 'google-user':
var proxyUrl = config.proxyUrl ? config.proxyUrl : config.wmtsUrl ? config.wmtsUrl : null;
layer = new this.loadedModules.UserTileLayer(
Utils._.extend(config, {
proxyUrl = config.proxyUrl ? config.proxyUrl : config.wmtsUrl ? config.wmtsUrl : null;
layer = new UserTileLayer()(
_.extend(config, {
url: proxyUrl,
}),
);
layer.then((res) => console.log(res));
break;
case 'pipenet-tile':
var proxyUrl = config.proxyUrl ? config.proxyUrl : config.wmtsUrl ? config.wmtsUrl : null;
layer = new this.loadedModules.PipenetTileLayer(
Utils._.extend(config, {
proxyUrl = config.proxyUrl ? config.proxyUrl : config.wmtsUrl ? config.wmtsUrl : null;
layer = new PipenetTileLayer()(
_.extend(config, {
url: proxyUrl,
}),
);
......@@ -554,8 +537,8 @@ export default class MapManager extends React.Component {
case 'baidu-v':
case 'baidu-i':
case 'baidu-ia':
layer = new this.loadedModules.BaiduTileLayer(
Utils._.extend(config, {
layer = new BaiduTileLayer()(
_.extend(config, {
url: 'http://fack.com',
}),
);
......@@ -566,8 +549,8 @@ export default class MapManager extends React.Component {
case 'amap-v2':
case 'amap-i2':
case 'amap-ia2':
layer = new this.loadedModules.AMapTileLayer(
Utils._.extend(config, {
layer = new AMapTileLayer()(
_.extend(config, {
url: 'http://fack.com',
}),
);
......@@ -584,59 +567,57 @@ export default class MapManager extends React.Component {
case 'tianditu-ll-ia':
case 'tianditu-ll-t':
case 'tianditu-ll-ta':
layer = new this.loadedModules.TiandituTileLayer(
Utils._.extend(config, {
layer = new TiandituTileLayer()(
_.extend(config, {
url: 'http://fack.com',
}),
);
break;
case 'tianditu-v-va':
//深拷贝config
var configString = JSON.stringify(config);
configString = JSON.stringify(config);
//天地图矢量
var configv = Utils._.extend(JSON.parse(configString), {
configv = _.extend(JSON.parse(configString), {
layerType: 'tianditu-v',
});
this.createLayer(configv, collection, false, layerType);
//天地图注记
var configva = Utils._.extend(JSON.parse(configString), {
configva = _.extend(JSON.parse(configString), {
layerType: 'tianditu-va',
});
this.createLayer(configva, collection, false, layerType);
break;
case 'tianditu-i-ia':
//深拷贝config
var configString = JSON.stringify(config);
configString = JSON.stringify(config);
//天地图矢量
var configi = Utils._.extend(JSON.parse(configString), {
configi = _.extend(JSON.parse(configString), {
layerType: 'tianditu-i',
});
this.createLayer(configi, collection, false, layerType);
//天地图注记
var configia = Utils._.extend(JSON.parse(configString), {
configia = _.extend(JSON.parse(configString), {
layerType: 'tianditu-ia',
});
this.createLayer(configia, collection, false, layerType);
break;
case 'osm':
layer = new this.loadedModules.OpenStreetMapLayer(
Utils._.extend(config, {
layer = new OpenStreetMapLayer(
_.extend(config, {
url: 'http://fack.com',
}),
);
break;
case 'wmts-v':
layer = new this.loadedModules.WMTSTileLayer(Utils._.extend(config, {}));
layer = new WMTSTileLayer()(_.extend(config, {}));
break;
case 'arcgis-streetpurplishblue':
case 'arcgis-streetwarm':
case 'arcgis-community':
case 'arcgis-streetgray':
layer = new this.loadedModules.TileLayer(
Utils._.extend(config, {
layer = new TileLayer(
_.extend(config, {
url:
'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnline' +
config.layerType.replace('arcgis-', '') +
......@@ -645,18 +626,18 @@ export default class MapManager extends React.Component {
);
break;
case 'arcgis-tilelayer':
if (_config.ip.indexOf('222.92') > -1)
if (_config.ip && _config.ip.indexOf('222.92') > -1)
config.url = config.url.replace(/\d+\.\d+\.\d+\.\d+/, window.location.hostname);
layer = new this.loadedModules.TileLayer({
layer = new TileLayer({
url: config.url,
title: config.title,
// id: _.uniqueId('arcgis-tilelayer_')
id: _.uniqueId('arcgis-tilelayer_'),
});
break;
default:
if (config.layerType.toLowerCase().indexOf('tianditu-') > -1) {
layer = new this.loadedModules.TiandituTileLayer(
Utils._.extend(config, {
if (layerType.indexOf('tianditu-') > -1) {
layer = new TiandituTileLayer(
_.extend(config, {
url: 'http://fack.com',
}),
);
......@@ -664,19 +645,14 @@ export default class MapManager extends React.Component {
}
break;
}
//returnLayer 是否需要返回layer
if (returnLayer) return layer;
//layer未给值
if (_.isUndefined(layer)) return this._layerCreateErrorLog(config);
//layerType
switch (layerType) {
switch (mapType) {
case 'baseMap':
layer.visible = true;
break;
case 'pipeLayer':
Utils._.extend(layer, {
_.extend(layer, {
preload: true,
});
break;
......@@ -684,102 +660,63 @@ export default class MapManager extends React.Component {
break;
}
collection.add(layer);
}
};
loadAreaLayer() {
var url = window.location.protocol + '//webapi.amap.com/maps?';
this.areaLayerInit = true;
this.extent = {
spatialReference: {
wkid: 4526,
},
xmin: 0,
ymin: 0,
xmax: 0,
ymax: 0,
};
if (!this.mapsettings.areasettings) return null;
// if (this.basemaps && this.basemaps[0] && this.basemaps[0]['id'] == '自定义底图') return this.setExtent()
var area = this.mapsettings.areasettings.areaName.split(',');
if (window.navigator.onLine == true && area.length == 1) {
let timer = setInterval(
function () {
if (window.AMap && window.AMap.DistrictSearch) {
clearInterval(timer);
this.getAreaLayer();
}
}.bind(this),
500,
);
} else {
// if (this.getPipenetLayer()) var url = this.getPipenetLayer().url;
// if (url && _config.mapsettings.areasettings.areaName) {
// request(url + "/GetMapArea", {
// query: {
// areaName: _config.mapsettings.areasettings.areaName.split(',')[0],
// outSR: webgisPandaTool.getCurrentMapWkid(),
// },
// cacheBust: true
// }).then(function (r) {
// if (r.data && r.data.length > 0) {
// this.polygon = [], this.edge = [], this.area = [], this.bound = null;
// r.data.forEach(function (point) {
// this.polygon.push([point.x, point.y]);
// }.bind(this))
// this.edge.push(this.polygon);
// _config.useCoverMap && this.area.push(this.polygon);
// this._setAreaLayer();
// } else {
// console.log("行政区图层无数据");
// }
// }.bind(this), function (error) {
// console.log("未查询到行政区图层数据!");
// }.bind(this))
// }
}
}
_layerCreateErrorLog = (layerconfig) => {
var error =
"mapView - can't createlayer (title:" +
layerconfig.title +
',type:' +
layerconfig.layerType +
',url:' +
layerconfig.url +
')';
console.log(error);
};
getAreaLayer() {}
setExtent() {}
showPipeNetLayer() {}
getNearestScale(extent) {
var resolution = extent.width / this.view.width,
zoom = 0,
nearestScale = -1,
diff = Number.POSITIVE_INFINITY;
if (this.view.map.basemap && this.view.map.basemap.baseLayers.length > 0) {
this.view.map.basemap.baseLayers.getItemAt(0).tileInfo.lods.forEach(
function (item) {
if (item.resolution >= resolution) {
var difftemp = item.resolution - resolution;
if (difftemp < diff) {
diff = difftemp;
nearestScale = item.scale;
zoom = item.level;
}
}
}.bind(this),
);
}
if (!this.mapsettings.scale) {
this.mapsettings.scale = nearestScale;
this.mapsettings.zoom = zoom;
getLayerUrl = (url) => {
if (!url) return '';
let protocol = location.protocol;
let host = location.host;
return `${protocol}${host}/${url}`;
};
addAnnotationLayer = (title, url, visible) => {
let query = url.split('?')[1];
const { MapImageLayer } = this.props.modules;
url += query ? '&annotation=true' : 'annotation=true';
let annotationLayer = new MapImageLayer({
title: title + '(注记)',
url: annotationLayerUrl,
visible: visible,
token: _config && _config.token,
client: 'webgis',
});
_.extend(annotationLayer, {
preload: true,
});
this.view.map.add(annotationLayer);
return annotationLayer;
};
showPipeNetLayer = () => {
var layers = this.map && this.map.layers;
if (layers && layers.items) {
layers.items.forEach(function (lyr) {
if ('pipenetlayer' === lyr.layerType.toLowerCase()) {
lyr.visible = true;
}
});
}
return nearestScale;
}
};
render() {
return <div ref={this.mapRef} id={this.props.id} style={this.getStyle()}></div>;
}
render = () => {
const { id, viewRef, style } = this.props;
const { viewReady } = this.state;
return (
<div id={id} ref={viewRef} style={style}>
{viewReady ? '' : <Spin tip="正在加载底图中..." />}
</div>
);
};
}
MapManager.propTypes = {
id: PropTypes.string,
width: PropTypes.string,
height: PropTypes.string,
mapsettings: PropTypes.object,
modules: PropTypes.array,
};
import gisConfig from '../config/gis';
import esriLoader from 'esri-loader';
console.log('test---geometry');
export function toGeometry(jsonObj, mapMng) {
var geometry,
mm = mapMng || mapManager;
if (jsonObj) {
jsonObj.spatialReference = {
wkid: mm.view.spatialReference.wkid,
};
geometry = AllDependenciesLoadedModules['jsonUtils'].fromJSON(jsonObj);
}
return geometry;
}
const toGeometryDependenciesModules = {
jsonUtils: 'gis/geometry/support/jsonUtils',
};
const getDefaultSymbolDependenciesModules = {
SimpleMarkerSymbol: 'gis/symbols/SimpleMarkerSymbol',
SimpleLineSymbol: 'gis/symbols/SimpleLineSymbol',
SimpleFillSymbol: 'gis/symbols/SimpleFillSymbol',
Color: 'gis/Color',
};
const ALLDependenciesModules = Object.assign(
{},
toGeometryDependenciesModules,
getDefaultSymbolDependenciesModules,
);
const AllDependenciesLoadedModules = {};
export async function loadAllDependencies() {
isRequestLoadModules(ALLDependenciesModules, AllDependenciesLoadedModules)
? await loadCommonModules(ALLDependenciesModules, AllDependenciesLoadedModules)
: '';
}
export async function loadToGeometryDependencies() {
isRequestLoadModules(toGeometryDependenciesModules, AllDependenciesLoadedModules)
? await loadCommonModules(toGeometryDependenciesModules, AllDependenciesLoadedModules)
: '';
}
export async function loadGetDefaultSymbolDependencies() {
isRequestLoadModules(getDefaultSymbolDependenciesModules, AllDependenciesLoadedModules)
? await loadCommonModules(getDefaultSymbolDependenciesModules, AllDependenciesLoadedModules)
: '';
}
async function loadCommonModules(modulesUrlsObject, loadedModuleObject) {
let moduleArr = Object.entries(modulesUrlsObject);
let moduleUrlsArray = moduleArr.map((item) => item[1]);
let modules = await esriLoader.loadModules(moduleUrlsArray, gisConfig);
modules.map(
function (module, index) {
loadedModuleObject[moduleArr[index][0]] = module;
}.bind(this),
);
}
function isRequestLoadModules(originModules, targetModule) {
let flag = false;
for (let key in originModules) {
if (!flag && !targetModule[key]) flag = true;
}
return flag;
}
import gisConfig from '../config/gis';
import esriLoader from 'esri-loader';
export const _ = require('lodash');
export function loadModules(modules = [], mapSettings = {}) {
let mergeMapSettings = Object.assign(gisConfig, mapSettings);
return new Promise(
function (resolve, reject) {
esriLoader.loadModules(modules, mergeMapSettings).then(
function (array) {
resolve(array);
}.bind(this),
);
}.bind(this),
);
}
export async function asyncLoadModules(modules = [], mapSettings = {}) {
let mergeMapSettings = Object.assign(gisConfig, mapSettings);
let results = await esriLoader.loadModules(modules, mergeMapSettings);
return results;
}
export function bindUrlUtils(urlUtils) {
if (!urlUtils.getUrl) {
urlUtils.getUrl = urlUtilsGetUrl;
}
}
function urlUtilsGetUrl(template, _module) {
var urlArr = [];
urlArr.push(location.protocol + '/');
urlArr.push(location.host);
if (_config.prefix) {
urlArr.push(_config.prefix);
}
if (_module && _module.length) {
// url服务接口 模块配置路径采用绝对路径
var _urlModuleTempl = {
CaseManageREST: 'CityInterface/Services/CityServer_CaseManage/REST/CaseManageREST.svc',
EditREST: 'CityInterface/Services/CityServer_Edit/REST/EditREST.svc',
MapREST: 'CityInterface/rest/services/MapServer.svc',
MapRESTOld: 'CityInterface/Services/CityServer_Map/REST/MapREST.svc',
WorkFlowREST: 'CityInterface/Services/CityServer_WorkFlow/REST/WorkFlowREST.svc',
AuditREST: 'CityInterface/Services/CityServer_Audit/REST/AuditREST.svc',
LocatorREST: 'CityInterface/Services/CityServer_Locator/REST/LocatorREST.svc',
NewNotificationREST:
'CityInterface/Services/CityServer_NewNotification/REST/NewNotificationREST.svc',
OfficeTemplateREST:
'Cityinterface/Services/CityServer_OfficeTemplate/REST/OfficeTemplate.svc',
OfflineTaskEditREST:
'CityInterface/Services/CityServer_OfflineTaskEdit/REST/OfflineTaskEditREST.svc',
PatrolStandardRest: 'CityInterface/rest/services/PatrolStandard.svc',
PatrolStandardRestOld:
'CityInterface/Services/CityServer_Patrol_Standard/REST/PatrolStandardRest.svc',
NewPatrolREST: 'CityInterface/rest/services/NewPatrol.svc',
OldPatrolREST: 'CityInterface/Services/CityServer_NewPatrol/REST/Newpatrolrest.svc',
MobileBusinessBaseREST: 'CityInterface/Services/CityServer_MobileBusiness/REST/BaseREST.svc',
HZGSProjectBoxREST:
'CityInterface/Services/CityServer_HZGSProjectBox/REST/HZGSProjectBoxREST.svc',
ZS_ProjectManageREST:
'CityInterface/Services/CityServer_ProjectManage_ZS/REST/ProjectManageREST.svc',
};
var _templ = _urlModuleTempl[_module] ? _urlModuleTempl[_module] : '';
urlArr.push(_templ);
return urlArr.join('/');
} else {
if (
['{host}', '{protocol}', '{prefix}', '{ip}'].some(function (str) {
return template.toLowerCase().indexOf(str) >= 0;
})
) {
return template
.replace(/\{host\}/gi, urlArr.join('/'))
.replace(/\{protocol\}/gi, _config.protocol + '//')
.replace(/\{prefix\}/gi, _config.prefix || '')
.replace(/\{ip\}/gi, _config.ip);
} else if (template.indexOf('http://') == 0 || template.indexOf('https://') == 0) {
return template;
} else {
urlArr.push(template);
return urlArr.join('/');
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment