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 plugins = ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.DistrictSearch'];
const amapConfig = { url, plugins }; const amapConfig = { url, plugins, key, v };
export default amapConfig; 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 mapsettings from '../mapData';
import MapManganer from '../index'; import MapView from '../index';
export default class CreateMap extends React.Component { export default class CreateMap extends React.Component {
constructor(props) { constructor(props) {
...@@ -8,17 +8,44 @@ export default class CreateMap extends React.Component { ...@@ -8,17 +8,44 @@ export default class CreateMap extends React.Component {
if (!window._config) { if (!window._config) {
window._config = { window._config = {
site: '', site: '',
mapsettings: mapsettings,
useCoverMap: true, useCoverMap: true,
}; };
} }
} }
state = {
loaded: false,
mapsettings: null,
};
componentDidMount() { 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() { 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'; import TilemetaUtils from './support/TilemetaUtils';
console.log('Amap-tilelayer'); import { getMapModules } from '../../core/loadMapModules';
export default function (TileLayer, lang, promiseUtils) {
export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
var dpi = 96, //pixel per inch var dpi = 96, //pixel per inch
level = 99, //地图缩放级数 level = 99, //地图缩放级数
maxlevel = 18, //地图总级数 maxlevel = 18, //地图总级数
......
import TilemetaUtils from './support/TilemetaUtils'; 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 var dpi = 96, //pixel per inch
level = 99, //地图缩放级数 level = 99, //地图缩放级数
maxlevel = 20, //地图总级数 maxlevel = 20, //地图总级数
......
// 谷歌地图 (由TileLayer扩展) // 谷歌地图 (由TileLayer扩展)
// create by czl 2017/12/2 // create by czl 2017/12/2
import TilemetaUtils from './support/TilemetaUtils'; 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 var dpi = 96, //pixel per inch
level = 99, //地图缩放级数 level = 99, //地图缩放级数
levelStart = 3, // 起始级数 levelStart = 3, // 起始级数
......
// All material copyright GIS, All Rights Reserved, unless otherwise specified. import { getMapModules } from '../../core/loadMapModules';
// See https://js.gis.com/4.3/gis/copyright.txt for details.
//>>built export default function ({ config, WebTileLayer } = getMapModules()) {
//streets、light、dark、satellite、streets-satellite、wheatpaste、streets-basic、comic、outdoors、run-bike-hike、pencil、pirates、emerald、high-contrast let a = config,
define(['gis/config', 'gis/layers/WebTileLayer'], function (a, b) { b = WebTileLayer;
a.request.corsEnabledServers.push('a.tile.mapbox.org', 'b.tile.mapbox.org', 'c.tile.mapbox.org'); a.request.corsEnabledServers.push('a.tile.mapbox.org', 'b.tile.mapbox.org', 'c.tile.mapbox.org');
return b.createSubclass({ return b.createSubclass({
declaredClass: 'gis.layers.MapBoxLayer', declaredClass: 'gis.layers.MapBoxLayer',
...@@ -15,4 +15,4 @@ define(['gis/config', 'gis/layers/WebTileLayer'], function (a, b) { ...@@ -15,4 +15,4 @@ define(['gis/config', 'gis/layers/WebTileLayer'], function (a, b) {
type: { value: 'mapbox', json: { read: !1 } }, type: { value: 'mapbox', json: { read: !1 } },
}, },
}); });
}); }
// 自定义底图 (由TileLayer扩展) // 自定义底图 (由TileLayer扩展)
// create by zxc 2020/7/16 // create by zxc 2020/7/16
define([ import TilemetaUtils from './support/TilemetaUtils';
'gis/layers/TileLayer', import { getMapModules } from '../../core/loadMapModules';
'dojo/_base/lang',
'gis/core/promiseUtils', export default function ({ TileLayer, lang, promiseUtils, request } = getMapModules()) {
'./support/TilemetaUtils',
'gis/request',
], function (TileLayer, lang, promiseUtils, TilemetaUtils, request) {
var dpi = 96, //pixel per inch var dpi = 96, //pixel per inch
level = 99, //地图缩放级数 level = 99, //地图缩放级数
levelStart = 0, // 起始级数 levelStart = 0, // 起始级数
...@@ -103,4 +100,4 @@ define([ ...@@ -103,4 +100,4 @@ define([
); );
}, },
}); });
}); }
// 天地图 (由TileLayer扩展) // 天地图 (由TileLayer扩展)
// create by czl 2017/12/2 // create by czl 2017/12/2
define([ import TilemetaUtils from './support/TilemetaUtils';
'gis/layers/TileLayer', import { getMapModules } from '../../core/loadMapModules';
'dojo/_base/lang',
'gis/core/promiseUtils', export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
'./support/TilemetaUtils',
], function (TileLayer, lang, promiseUtils, TilemetaUtils) {
var dpi = 96, //pixel per inch var dpi = 96, //pixel per inch
level = 20, //地图总级数 level = 20, //地图总级数
levelStart = 3, // 起始级数 levelStart = 3, // 起始级数
...@@ -165,4 +163,4 @@ define([ ...@@ -165,4 +163,4 @@ define([
}); });
}, },
}); });
}); }
// 自定义底图 (由TileLayer扩展) // 自定义底图 (由TileLayer扩展)
// create by ysq 2019/5/8 // create by ysq 2019/5/8
define([ import TilemetaUtils from './support/TilemetaUtils';
'gis/layers/TileLayer', import { getMapModules } from '../../core/loadMapModules';
'dojo/_base/lang',
'gis/core/promiseUtils', export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
'./support/TilemetaUtils',
'gis/request',
], function (TileLayer, lang, promiseUtils, TilemetaUtils, request) {
var dpi = 96, //pixel per inch var dpi = 96, //pixel per inch
level = 99, //地图缩放级数 level = 99, //地图缩放级数
levelStart = 0, // 起始级数 levelStart = 0, // 起始级数
...@@ -97,4 +94,4 @@ define([ ...@@ -97,4 +94,4 @@ define([
}); });
}, },
}); });
}); }
// create by ysq 2018/11/7 // create by ysq 2018/11/7
define([ import TilemetaUtils from './support/TilemetaUtils';
'gis/layers/TileLayer', import { getMapModules } from '../../core/loadMapModules';
'dojo/_base/lang',
'gis/core/promiseUtils', export default function ({ TileLayer, lang, promiseUtils } = getMapModules()) {
'./support/TilemetaUtils',
], function (TileLayer, lang, promiseUtils, TilemetaUtils) {
var dpi = 96, //pixel per inch var dpi = 96, //pixel per inch
level = 19, //地图总级数 level = 19, //地图总级数
levelStart = 9, // 起始级数 levelStart = 9, // 起始级数
...@@ -51,12 +49,4 @@ define([ ...@@ -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 React from 'react';
import PropTypes from 'prop-types';
import amapConfig from './config/amap'; import amapConfig from './config/amap';
import gisModules from './config/module'; import { layerOperation, loadUtilMapModules, geomUtils, mapUtils } from './core/utils';
import { Spin } from 'antd';
import AMapTileLayer from './extensions/layers/AMapTileLayer'; import {
import GoogleTileLayer from './extensions/layers/GoogleTileLayer'; loadMapLayerModules,
AMapTileLayer,
import * as Utils from './utils/Utils'; BaiduTileLayer,
GoogleTileLayer,
import * as GeomUtils from './utils/GeometryTool'; 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 = { static defaultProps = {
id: '#jsmap', id: '#jsmap',
width: '100%', style: {
height: '420px', width: '100%',
height: '420px',
},
mapsettings: {}, mapsettings: {},
modules: gisModules, viewRef: React.createRef(),
};
state = {
viewReady: true, //视图准备的条件 : 1.has map 2. has container 3. extent
loaded: true, //显示地图 create view
}; };
constructor(props) { constructor(props) {
super(props); super(props);
this.mapRef = React.createRef();
this.initializeVariables(); this.initializeVariables();
} }
async initializeVariables() { initializeVariables = () => {
this.view = null; this.view = null;
this.map = null; this.map = null;
this.basemap = null; this.basemap = null;
this.tipManager = null; this.tipManager = null;
this.AreaLayerSum = null; this.AreaLayerSum = null;
this.reorderGroups = [];
this.hidetipHandler = null; this.hidetipHandler = null;
this.showtipHandler = null; this.showtipHandler = null;
this.renderMenu = true; this.reorderGroups = [];
this.basemaps = [];
this.mapsettings = this.props.mapsettings; 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() { loadAMapScript = () => {
return { let amapUrl = `${amapConfig.url}v=${amapConfig.v}&key=${
width: this.props.width, amapConfig.key
height: this.props.height, }&plugin=${amapConfig.plugins.join(',')}`;
}; return loadScripts([amapUrl]);
} };
async componentDidMount() { componentDidMount = async () => {
let moduleArr = await Utils.asyncLoadModules(this.props.modules); await loadMapLayerModules();
await GeomUtils.loadAllDependencies(); await loadUtilMapModules();
this.getModules(moduleArr);
this.createMapLayers();
this.renderView(); 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.addLayerProxy();
this.addMap(); this.addMap();
this.addBasemaps(); this.addBasemaps();
this.addLayerReorder(); this.addLayerReorder();
this.addLayers(); this.addLayers();
if ('2d' == this.mapsettings.type.toLowerCase()) { this.addMatrixLayer();
this.addMatrixLayer(); //加入空的GraphicsLayer,用于获取地图的moveStart,viewChange,moveEnd事件
}
this.addTipManager(); this.addTipManager();
if (this.renderMenu && this.view && this.view.type == '2d') { this.bindViewEvents();
this.loadedModules.watchUtils.whenTrue( };
this.view,
'ready', addLayerProxy = () => {};
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),
);
}
}
addLayerProxy() {} changeState = (key, value) => {
this.setState({ key, value });
};
addMap() { addMap = () => {
const mapsettings = this.mapsettings; const { Map, Collection, MapView, Ground, SceneView } = this.props.modules;
this.map = new this.loadedModules.Map(); const {
if (this.mapsettings.ground) { type,
if ('string' == typeof this.mapsettings.ground) { ground,
this.map.ground = this.mapsettings.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 { } else {
var layers = mapsettings.ground.layers, let layers = ground.layers,
layer, groundLayers = new Collection();
groundlayers = new this.loadedModules.Collection(); layers.map((layerConfig) => {
layers.forEach( this.createLayer(layerConfig, groundLayers, false, '');
function (layerconfig) { });
this.createLayer(layerconfig, groundlayers, false, '');
}.bind(this),
);
this.map.ground = new Ground({ 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() { createMapView = ({ MapView, viewRef, resizeAlign }) => {
window.view = this.view; 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) { if (this.viewpoint) {
this.initialViewpoint = new this.loadedModules.Viewpoint(); this.initialViewpoint = new Viewpoint();
if (this.viewpoint.camera) { this.viewpoint.camera && (this.initialViewpoint.camera = new Camera(this.viewpoint.camera));
this.initialViewpoint.camera = new this.loadedModules.Camera(this.viewpoint.camera); this.viewpoint.targetGeometry &&
this.viewpoint.targetGeometry && (this.initialViewpoint.targetGeometry = geomUtils.toGeometry(
(this.initialViewpoint.targetGeometry = GeomUtils.toGeometry( this.viewpoint.targetGeometry,
this.viewpoint.targetGeometry, this.view,
)); ));
this.viewpoint.scale && (this.initialViewpoint.scale = this.viewpoint.scale); this.viewpoint.scale && (this.initialViewpoint.scale = this.viewpoint.scale);
this.viewpoint.rotation && (this.initialViewpoint.rotation = this.viewpoint.rotation); this.viewpoint.rotation && (this.initialViewpoint.rotation = this.viewpoint.rotation);
} let geom = this.initialViewpoint.targetGeometry;
var geom = this.initialViewpoint.targetGeometry;
if (geom && !(geom.xmin == 0 && geom.ymin == 0 && geom.xmax == 0 && geom.ymax == 0)) { if (geom && !(geom.xmin == 0 && geom.ymin == 0 && geom.xmax == 0 && geom.ymax == 0)) {
if (geom.type == 'extent') { 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) { if (scale != -1) {
this.initialViewpoint.scale = scale; this.initialViewpoint.scale = scale;
} }
...@@ -250,7 +241,6 @@ export default class MapManager extends React.Component { ...@@ -250,7 +241,6 @@ export default class MapManager extends React.Component {
} else { } else {
this.initialViewpoint = this.view.viewpoint; this.initialViewpoint = this.view.viewpoint;
} }
if ( if (
this.mapsettings.areasettings && this.mapsettings.areasettings &&
this.mapsettings.areasettings.areaName.toLowerCase().indexOf('offlinearea') > -1 && this.mapsettings.areasettings.areaName.toLowerCase().indexOf('offlinearea') > -1 &&
...@@ -261,170 +251,135 @@ export default class MapManager extends React.Component { ...@@ -261,170 +251,135 @@ export default class MapManager extends React.Component {
this.areaLayerInit = true; this.areaLayerInit = true;
return; return;
} }
this.mapsettings.useCoverMap = _.isUndefined(this.mapsettings.useCoverMap)
if (!this.areaLayerInit) { ? true
: !!this.mapsettings.useCoverMap;
if (this.mapsettings.useCoverMap && !this.areaLayerInit) {
this.loadAreaLayer(); this.loadAreaLayer();
} else {
this.showPipeNetLayer();
} }
} };
addBasemaps() { addBasemaps = () => {
let basemapconfigs = this.mapsettings.basemaps; let basemapconfigs = this.mapsettings.basemaps;
this.basemaps = [];
if (basemapconfigs) { if (basemapconfigs) {
basemapconfigs.forEach( basemapconfigs.map((basemapconfig) => {
function (basemapconfig) { this.basemaps.push(this.createBasemap(basemapconfig));
this.basemaps.push(this.createBasemap(basemapconfig)); });
}.bind(this),
);
} else { } else {
this.basemaps.push(this.createDefaultBasemap()); this.basemaps.push(this.createDefaultBasemap());
} }
if (this.basemaps.length) this.map.basemap = this.basemaps[0];
};
if (this.basemaps.length) { createDefaultBasemap = () => {};
this.map.basemap = this.basemaps[0];
}
}
createBasemap(basemap) { createBasemap = (basemap) => {
var bm; const { Collection, Basemap } = this.props.modules;
let bm;
if (basemap) { if (basemap) {
if ('string' == typeof basemap) { if ('string' == typeof basemap) {
bm = basemap; bm = basemap;
} else { } else {
// var layer, let bls = new Collection(),
var bls = new this.loadedModules.Collection(),
id = basemap.id, id = basemap.id,
title = basemap.title, title = basemap.title,
thumbnailUrl = basemap.thumbnailUrl, thumbnailUrl = basemap.thumbnailUrl,
baseLayers = basemap.baseLayers; baseLayers = basemap.baseLayers;
baseLayers.forEach( baseLayers.map((layerconfig) => {
function (layerconfig) { this.createLayer(layerconfig, bls, false, 'baseMap');
this.createLayer(layerconfig, bls, false, 'baseMap'); });
}.bind(this), bm = new Basemap({
); id,
bm = new this.loadedModules.BaseMap({ title,
id: id, thumbnailUrl,
title: title,
thumbnailUrl: thumbnailUrl,
baseLayers: bls, baseLayers: bls,
}); });
} }
} }
return bm; return bm;
} };
createDefaultBasemap() {}
addLayerReorder() { addLayerReorder = () => {
this.layerAddedHandler = this.layerAddedHandler.bind(this);
this.map.layers.on('after-add', this.layerAddedHandler); this.map.layers.on('after-add', this.layerAddedHandler);
} };
layerAddedHandler(event) { layerAddedHandler = (event) => {
var lyr = event.item; let lyr = event.item;
if ('graphics' === lyr.type) { let reorderGroups = this.reorderGroups;
if (this.isInGroup(lyr)) { if ('graphics' == lyr.type) {
var layer = this.map.layers.find( if (layerOperation.isInGroup(lyr, reorderGroups)) {
function (l) { let layer = this.map.layers.find((layer) => {
return this.getLayerWeight(l) > this.getLayerWeight(lyr); return (
}.bind(this), layerOperation.getLayerWeight(layer, reorderGroups) >
); layerOperation.getLayerWeight(lyr, reorderGroups)
);
});
if (layer) { if (layer) {
this.map.layers.reorder(lyr, this.map.layers.indexOf(layer) - 1); 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() { addLayers = () => {
let layerconfigs = this.mapsettings.layers; let layerconfigs = this.props.mapsettings.layers;
if (layerconfigs) { if (layerconfigs) {
var layer; layerconfigs.map((layerconfig) => {
layerconfigs.forEach( if (!layerconfig.id) return;
function (layerconfig) { this.createLayer(layerconfig, this.map, false, 'pipeLayer');
if (!layerconfig.id) return; });
this.createLayer(layerconfig, this.map, false, 'pipeLayer');
}.bind(this),
);
} }
} };
addMatrixLayer() { addMatrixLayer = () => {
this._matrixLayer = new this.loadedModules.GraphicsLayer(); if (this.view.type != '2d') return;
let { GraphicsLayer } = this.props.modules;
this._matrixLayer = new GraphicsLayer();
this.view.map.add(this._matrixLayer); 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); this.view.whenLayerView(this._matrixLayer).then(this.matrixLayerViewCreated);
} };
matrixLayerViewCreated(lyrView) { matrixLayerViewCreated = (lyrView) => {
if (lyrView) { if (lyrView) {
lyrView.on('moveStart', this.matrixLayerMoveStart); lyrView.on('moveStart', this.matrixLayerMoveStart);
lyrView.on('viewChange', this.matrixLayerViewChange); lyrView.on('viewChange', this.matrixLayerViewChange);
lyrView.on('moveEnd', this.matrixLayerMoveEnd); lyrView.on('moveEnd', this.matrixLayerMoveEnd);
} }
} };
matrixLayerMoveStart(lyrView) { matrixLayerMoveStart = (lyrView) => {
var m = this.getLayerViewMatrix(lyrView); let m = this.getLayerViewMatrix(lyrView);
this.view.emit('moveStart', { this.view.emit('moveStart', {
layerView: lyrView, layerView: lyrView,
matrix: m, matrix: m,
matrixString: this.toMatrixString(m), matrixString: this.toMatrixString(m),
}); });
} };
matrixLayerViewChange(lyrView) { matrixLayerViewChange = (lyrView) => {
var m = this.getLayerViewMatrix(lyrView); let m = this.getLayerViewMatrix(lyrView);
this.view.emit('viewChange', { this.view.emit('viewChange', {
layerView: lyrView, layerView: lyrView,
matrix: m, matrix: m,
zooming: m.xx != 1, zooming: m.xx != 1,
matrixString: this.toMatrixString(m), matrixString: this.toMatrixString(m),
}); });
} };
matrixLayerMoveEnd(lyrView) { matrixLayerMoveEnd = (lyrView) => {
var m = this.getLayerViewMatrix(lyrView); let m = this.getLayerViewMatrix(lyrView);
this.view.emit('moveEnd', { this.view.emit('moveEnd', {
layerView: lyrView, layerView: lyrView,
matrix: m, matrix: m,
matrixString: this.toMatrixString(m), matrixString: this.toMatrixString(m),
}); });
} };
getLayerViewMatrix(lyrView) { getLayerViewMatrix = (lyrView) => {
let matrix = this.loadedModules.matrix; const { matrix } = this.props.modules;
var m = matrix.clone(matrix.identify); let m = matrix.clone(matrix.identify);
if ( if (
lyrView.graphicsView && lyrView.graphicsView &&
lyrView.graphicsView._frontGroup && lyrView.graphicsView._frontGroup &&
...@@ -446,9 +401,9 @@ export default class MapManager extends React.Component { ...@@ -446,9 +401,9 @@ export default class MapManager extends React.Component {
m = matrix.clone(targetMatrix); m = matrix.clone(targetMatrix);
} }
return m; return m;
} };
toMatrixString(m) { toMatrixString = (m) => {
return ( return (
'matrix(' + 'matrix(' +
[ [
...@@ -461,65 +416,94 @@ export default class MapManager extends React.Component { ...@@ -461,65 +416,94 @@ export default class MapManager extends React.Component {
].join() + ].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) { loadAreaLayer = () => {
var layer; let url = amapConfig.url;
var layers = []; this.areaLayerInit = true;
if (config.url) { this.extent = {
config.url = this.loadedModules.urlUtils.getUrl(config.url); 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': case 'tilelayer':
layer = new this.loadedModules.TileLayer(config); layer = new TileLayer(config);
break; break;
case 'pipenetlayer': case 'pipenetlayer':
case 'mapimagelayer': case 'mapimagelayer':
layer = new this.loadedModules.MapImageLayer( layer = new MapImageLayer(
Utils._.extend({}, config, { _.extend({}, config, {
token: _config.token, token: _config && _config.token,
client: 'webgis', client: 'webgis',
visible: false, visible: false,
}), }),
); );
layer.then( layer.then(
function () { function () {
layer.visible = true;
if (layer.hasAnnotation) { 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), }.bind(this),
); );
break; break;
case 'elevationlayer': case 'elevationlayer':
layer = new this.loadedModules.ElevationLayer(config); layer = new ElevationLayer(config);
break; break;
case 'scenelayer': case 'scenelayer':
layer = new this.loadedModules.SceneLayer(config); layer = new SceneLayer(config);
break; break;
case 'featurelayer': case 'featurelayer':
layer = new this.loadedModules.FeatureLayer(config); layer = new FeatureLayer(config);
break; break;
case 'grouplayer': case 'grouplayer':
var layers = config.layers.map(function (c) { layers = config.layers.map(function (c) {
return this.createLayer(c, [], true, ''); return this.createLayer(c, [], true, '');
}, this); }, this);
layer = new this.loadedModules.GroupLayer( layer = new GroupLayer(
Utils._.extend({}, config, { _.extend({}, config, {
layers: layers, layers: layers,
}), }),
); );
...@@ -528,25 +512,24 @@ export default class MapManager extends React.Component { ...@@ -528,25 +512,24 @@ export default class MapManager extends React.Component {
case 'google-i': case 'google-i':
case 'google-i-a': case 'google-i-a':
case 'google-ia': case 'google-ia':
layer = new this.loadedModules.GoogleTileLayer( layer = new GoogleTileLayer()(
Utils._.extend(config, { _.extend(config, {
url: 'http://fack.com', url: 'http://fack.com',
}), }),
); );
break; break;
case 'google-user': case 'google-user':
var proxyUrl = config.proxyUrl ? config.proxyUrl : config.wmtsUrl ? config.wmtsUrl : null; proxyUrl = config.proxyUrl ? config.proxyUrl : config.wmtsUrl ? config.wmtsUrl : null;
layer = new this.loadedModules.UserTileLayer( layer = new UserTileLayer()(
Utils._.extend(config, { _.extend(config, {
url: proxyUrl, url: proxyUrl,
}), }),
); );
layer.then((res) => console.log(res));
break; break;
case 'pipenet-tile': case 'pipenet-tile':
var proxyUrl = config.proxyUrl ? config.proxyUrl : config.wmtsUrl ? config.wmtsUrl : null; proxyUrl = config.proxyUrl ? config.proxyUrl : config.wmtsUrl ? config.wmtsUrl : null;
layer = new this.loadedModules.PipenetTileLayer( layer = new PipenetTileLayer()(
Utils._.extend(config, { _.extend(config, {
url: proxyUrl, url: proxyUrl,
}), }),
); );
...@@ -554,8 +537,8 @@ export default class MapManager extends React.Component { ...@@ -554,8 +537,8 @@ export default class MapManager extends React.Component {
case 'baidu-v': case 'baidu-v':
case 'baidu-i': case 'baidu-i':
case 'baidu-ia': case 'baidu-ia':
layer = new this.loadedModules.BaiduTileLayer( layer = new BaiduTileLayer()(
Utils._.extend(config, { _.extend(config, {
url: 'http://fack.com', url: 'http://fack.com',
}), }),
); );
...@@ -566,8 +549,8 @@ export default class MapManager extends React.Component { ...@@ -566,8 +549,8 @@ export default class MapManager extends React.Component {
case 'amap-v2': case 'amap-v2':
case 'amap-i2': case 'amap-i2':
case 'amap-ia2': case 'amap-ia2':
layer = new this.loadedModules.AMapTileLayer( layer = new AMapTileLayer()(
Utils._.extend(config, { _.extend(config, {
url: 'http://fack.com', url: 'http://fack.com',
}), }),
); );
...@@ -584,59 +567,57 @@ export default class MapManager extends React.Component { ...@@ -584,59 +567,57 @@ export default class MapManager extends React.Component {
case 'tianditu-ll-ia': case 'tianditu-ll-ia':
case 'tianditu-ll-t': case 'tianditu-ll-t':
case 'tianditu-ll-ta': case 'tianditu-ll-ta':
layer = new this.loadedModules.TiandituTileLayer( layer = new TiandituTileLayer()(
Utils._.extend(config, { _.extend(config, {
url: 'http://fack.com', url: 'http://fack.com',
}), }),
); );
break; break;
case 'tianditu-v-va': case 'tianditu-v-va':
//深拷贝config //深拷贝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', layerType: 'tianditu-v',
}); });
this.createLayer(configv, collection, false, layerType); this.createLayer(configv, collection, false, layerType);
//天地图注记 //天地图注记
var configva = Utils._.extend(JSON.parse(configString), { configva = _.extend(JSON.parse(configString), {
layerType: 'tianditu-va', layerType: 'tianditu-va',
}); });
this.createLayer(configva, collection, false, layerType); this.createLayer(configva, collection, false, layerType);
break; break;
case 'tianditu-i-ia': case 'tianditu-i-ia':
//深拷贝config //深拷贝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', layerType: 'tianditu-i',
}); });
this.createLayer(configi, collection, false, layerType); this.createLayer(configi, collection, false, layerType);
//天地图注记 //天地图注记
var configia = Utils._.extend(JSON.parse(configString), { configia = _.extend(JSON.parse(configString), {
layerType: 'tianditu-ia', layerType: 'tianditu-ia',
}); });
this.createLayer(configia, collection, false, layerType); this.createLayer(configia, collection, false, layerType);
break; break;
case 'osm': case 'osm':
layer = new this.loadedModules.OpenStreetMapLayer( layer = new OpenStreetMapLayer(
Utils._.extend(config, { _.extend(config, {
url: 'http://fack.com', url: 'http://fack.com',
}), }),
); );
break; break;
case 'wmts-v': case 'wmts-v':
layer = new this.loadedModules.WMTSTileLayer(Utils._.extend(config, {})); layer = new WMTSTileLayer()(_.extend(config, {}));
break; break;
case 'arcgis-streetpurplishblue': case 'arcgis-streetpurplishblue':
case 'arcgis-streetwarm': case 'arcgis-streetwarm':
case 'arcgis-community': case 'arcgis-community':
case 'arcgis-streetgray': case 'arcgis-streetgray':
layer = new this.loadedModules.TileLayer( layer = new TileLayer(
Utils._.extend(config, { _.extend(config, {
url: url:
'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnline' + 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnline' +
config.layerType.replace('arcgis-', '') + config.layerType.replace('arcgis-', '') +
...@@ -645,18 +626,18 @@ export default class MapManager extends React.Component { ...@@ -645,18 +626,18 @@ export default class MapManager extends React.Component {
); );
break; break;
case 'arcgis-tilelayer': 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); config.url = config.url.replace(/\d+\.\d+\.\d+\.\d+/, window.location.hostname);
layer = new this.loadedModules.TileLayer({ layer = new TileLayer({
url: config.url, url: config.url,
title: config.title, title: config.title,
// id: _.uniqueId('arcgis-tilelayer_') id: _.uniqueId('arcgis-tilelayer_'),
}); });
break; break;
default: default:
if (config.layerType.toLowerCase().indexOf('tianditu-') > -1) { if (layerType.indexOf('tianditu-') > -1) {
layer = new this.loadedModules.TiandituTileLayer( layer = new TiandituTileLayer(
Utils._.extend(config, { _.extend(config, {
url: 'http://fack.com', url: 'http://fack.com',
}), }),
); );
...@@ -664,19 +645,14 @@ export default class MapManager extends React.Component { ...@@ -664,19 +645,14 @@ export default class MapManager extends React.Component {
} }
break; break;
} }
//returnLayer 是否需要返回layer
if (returnLayer) return layer; if (returnLayer) return layer;
//layer未给值
if (_.isUndefined(layer)) return this._layerCreateErrorLog(config); if (_.isUndefined(layer)) return this._layerCreateErrorLog(config);
switch (mapType) {
//layerType
switch (layerType) {
case 'baseMap': case 'baseMap':
layer.visible = true; layer.visible = true;
break; break;
case 'pipeLayer': case 'pipeLayer':
Utils._.extend(layer, { _.extend(layer, {
preload: true, preload: true,
}); });
break; break;
...@@ -684,102 +660,63 @@ export default class MapManager extends React.Component { ...@@ -684,102 +660,63 @@ export default class MapManager extends React.Component {
break; break;
} }
collection.add(layer); collection.add(layer);
} };
loadAreaLayer() { _layerCreateErrorLog = (layerconfig) => {
var url = window.location.protocol + '//webapi.amap.com/maps?'; var error =
this.areaLayerInit = true; "mapView - can't createlayer (title:" +
this.extent = { layerconfig.title +
spatialReference: { ',type:' +
wkid: 4526, layerconfig.layerType +
}, ',url:' +
xmin: 0, layerconfig.url +
ymin: 0, ')';
xmax: 0, console.log(error);
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))
// }
}
}
getAreaLayer() {} getLayerUrl = (url) => {
if (!url) return '';
setExtent() {} let protocol = location.protocol;
let host = location.host;
showPipeNetLayer() {} return `${protocol}${host}/${url}`;
};
getNearestScale(extent) {
var resolution = extent.width / this.view.width, addAnnotationLayer = (title, url, visible) => {
zoom = 0, let query = url.split('?')[1];
nearestScale = -1, const { MapImageLayer } = this.props.modules;
diff = Number.POSITIVE_INFINITY; url += query ? '&annotation=true' : 'annotation=true';
if (this.view.map.basemap && this.view.map.basemap.baseLayers.length > 0) { let annotationLayer = new MapImageLayer({
this.view.map.basemap.baseLayers.getItemAt(0).tileInfo.lods.forEach( title: title + '(注记)',
function (item) { url: annotationLayerUrl,
if (item.resolution >= resolution) { visible: visible,
var difftemp = item.resolution - resolution; token: _config && _config.token,
if (difftemp < diff) { client: 'webgis',
diff = difftemp; });
nearestScale = item.scale; _.extend(annotationLayer, {
zoom = item.level; preload: true,
} });
} this.view.map.add(annotationLayer);
}.bind(this), return annotationLayer;
); };
}
if (!this.mapsettings.scale) { showPipeNetLayer = () => {
this.mapsettings.scale = nearestScale; var layers = this.map && this.map.layers;
this.mapsettings.zoom = zoom; if (layers && layers.items) {
layers.items.forEach(function (lyr) {
if ('pipenetlayer' === lyr.layerType.toLowerCase()) {
lyr.visible = true;
}
});
} }
return nearestScale; };
}
render() { render = () => {
return <div ref={this.mapRef} id={this.props.id} style={this.getStyle()}></div>; 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