Переглянути джерело

fix 室内地图加载逻辑梳理修改,视图中心增加多逻辑判断并可通过sdk设置

JayXing 1 день тому
батько
коміт
f1c0bd233f
7 змінених файлів з 155 додано та 234 видалено
  1. 2 2
      package-lock.json
  2. 33 78
      src/ctrl/VectorDataManager.js
  3. 16 47
      src/index.js
  4. 13 7
      src/model/AccountAuth.js
  5. 11 41
      src/view/App.js
  6. 56 47
      src/view/Body.js
  7. 24 12
      src/view/Map.js

+ 2 - 2
package-lock.json

@@ -1,11 +1,11 @@
 {
-  "name": "indoor-monitor",
+  "name": "map-indoor",
   "version": "0.1.0",
   "lockfileVersion": 2,
   "requires": true,
   "packages": {
     "": {
-      "name": "indoor-monitor",
+      "name": "map-indoor",
       "version": "0.1.0",
       "license": "ISC",
       "dependencies": {

+ 33 - 78
src/ctrl/VectorDataManager.js

@@ -74,63 +74,45 @@ class VectorDataManager extends HistorizedManager {
 			if (this._cacheBbox && this._cacheBbox.filter(b => b.contains(bbox)).length > 0) {
 				resolve(true);
 			}
-			// if(
-			// 	(this._cacheOsmJson.node && this._cacheOsmJson.node.length > 0)
-			// 	|| (this._cacheOsmJson.way && this._cacheOsmJson.way.length > 0)
-			// 	|| (this._cacheOsmJson.relation && this._cacheOsmJson.relation.length > 0)
-			// ) {
-			// 	this._cacheOsmGeojson = this.getBaseCollection();
-			// }
-			// else {
-			// 	this._cacheOsmGeojson = { type: "FeatureCollection", features: [] };
-			// }
-			let data = JSON.parse(localStorage.getItem("mapData"));
-			// console.log(data);
-			if (data !== null) {
-				this._cacheOsmGeojson = data;
-				this._nextId = this._cacheOsmGeojson.features.length + 1;
-			}
-			else {
+
+			if (this._cacheOsmGeojson == null) {
 				this._cacheOsmGeojson = { type: "FeatureCollection", features: [] };
 			}
 			resolve(true);
-			// const restoreEdits = this._cacheOsmXml !== null;
-
-			// // Accumulate retrieved data
-			// this._osmApi
-			// .fetchMapByBbox(bbox.getWest(), bbox.getSouth(), bbox.getEast(), bbox.getNorth(), "both")
-			// .then(res => {
-			// 	const [mapJson, mapXml] = res;
-			// 	this._appendOsmXml(mapJson, mapXml, bbox);
-
-			// 	if(
-			// 		(this._cacheOsmJson.node && this._cacheOsmJson.node.length > 0)
-			// 		|| (this._cacheOsmJson.way && this._cacheOsmJson.way.length > 0)
-			// 		|| (this._cacheOsmJson.relation && this._cacheOsmJson.relation.length > 0)
-			// 	) {
-			// 		this._cacheOsmGeojson = { type: "FeatureCollection", features: [] };//this.getBaseCollection();
-			// 	}
-			// 	else {
-			// 		this._cacheOsmGeojson = { type: "FeatureCollection", features: [] };
-			// 	}
-
-			// 	// Restore all edits made by user
-			// 	if(restoreEdits) {
-			// 		this._nextId = -1;
-			// 		for(let i=0; i <= this._lastActionId; i++) {
-			// 			this._do(this._actions[i], true);
-			// 		}
-			// 	}
-
-			// 	resolve(true);
-			// })
-			// .catch(e => {
-			// 	console.error("Can't load OSM data", e);
-			// 	reject(e);
-			// });
+
 		});
 	}
 
+
+	updateCenter(center) {
+		// console.log(center);
+		this._cacheOsmGeojson.center = {
+			x: center.lng,
+			y: center.lat,
+		};
+	}
+
+	setGeoJsonData(data) {
+		this._cacheOsmGeojson = data;
+		this._nextId = this._cacheOsmGeojson.features.length + 1;
+	}
+
+
+	getAllReaders() {
+		const readers = new Set();
+		if (this._cacheOsmGeojson) {
+			this._cacheOsmGeojson.features.forEach(feature => {
+				// console.log(feature.properties.tags);
+				if ('device' in feature.properties.tags) {
+					readers.add(feature);
+				}
+			});
+		}
+		return readers;
+	}
+
+
+
 	/**
 	 * Adds new data retrieved from OSM into local cache
 	 * @private
@@ -280,19 +262,6 @@ class VectorDataManager extends HistorizedManager {
 		}
 	}
 
-	getAllReaders() {
-		const readers = new Set();
-		if (this._cacheOsmGeojson) {
-			this._cacheOsmGeojson.features.forEach(feature => {
-				// console.log(feature.properties.tags);
-				if ('device' in feature.properties.tags) {
-					readers.add(feature);
-				}
-			});
-		}
-		return readers;
-	}
-
 	/**
 	 * Check if a feature is overlapping enough a container feature (eg level inside building)
 	 * @param {Object} container The GeoJSON feature which should contain the other one
@@ -1205,20 +1174,6 @@ class VectorDataManager extends HistorizedManager {
 		return this._completeGeoJSON(osmtogeojson(this._cacheOsmXml, { flatProperties: false, uninterestingTags: () => false }));
 	}
 
-	updateCenter(center) {
-		// console.log(center);
-		this._cacheOsmGeojson.center = {
-			x: center.lng,
-			y: center.lat,
-		};
-	}
-
-	setGeoJsonData(data) {
-		this._cacheOsmGeojson = data;
-		this._nextId = this._cacheOsmGeojson.features.length + 1;
-		this._do(new Action(Action.IMPORT, null, arguments));
-	}
-
 	/**
 	 * Creates the diff object for current state of the map
 	 * @return {Object} Object with OSM IDs as keys, diff for element as values

+ 16 - 47
src/index.js

@@ -21,58 +21,27 @@ import connectTestTool from './view/utils/connectTestTool';
 /*
  * Global variables definition
  */
+window.MAP_NAME = "BunnyBlitzMap";
 window.EDITOR_URL = window.location.origin + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + "/";
 window.UNUSABLE_ICONS = new Set();
 
 
-// Dynamically load config file
-// request(window.EDITOR_URL + "/config.json")
-// 	.then(configTxt => {
-// 		console.log(configTxt)
-// 		window.CONFIG = JSON.parse(configTxt);
-// 		window.MAP_NAME = window.CONFIG.map_name;
-
-// 		// Create app
-// 		new App();
-// 	})
-// 	.catch(e => {
-// 		console.error(e);
-// 		alert("Can't load configuration file, please report this issue.");
-// 	});
-
-window.CONFIG = JSON.parse(`{
-	"map_name": "BunnyBlitzMap",
-	"hash": "GIT_HASH",
-	"data_min_zoom": 18,
-	"map_initial_zoom": 18,
-	"map_initial_latlng": [39.8729, 116.5141],
-	"providers": {
-		"bing": "AhsSQakuHuX3ozMBXC60w-hPk0KD_smZZbHLjb7mBFfeIwDKJnJn2_qK3qQfYfPZ"
-	},
-	"osm_api_url": "https://master.apis.dev.openstreetmap.org",
-	"oauth_consumer_key": "sJF3Cp7VSQ-SVgy8UoNdMcVDl85-HW1IOZU6-Ec-ZiE",
-	"oauth_secret": "hiapy7lMj09J7BHs4xjEmHG-JEOUMxpmx_C3QN-nCYQ",
-	"always_authenticated": false
-}`);
-
-window.MAP_NAME = window.CONFIG.map_name;
-
-
-// // Create app
-// let app = new App({ el: 'root', id: 'swa3s5ex', url:"ws://121.42.8.157:19702", origin: [39.62413679, 118.16254283] })
-
-// // new App({ el: 'root' }).init();
-// console.log(app)
-// app.init();
+// Create app
+let initData = {
+	el: 'root', // 渲染地图的 html dom 元素
+	id: 'swa3s5ex', // 地图编辑器保存的地图 mapid
+	url: "ws://121.42.8.157:19702", // 后端接口,用于查询 mapid 对应的 geojson 数据
+	center: { lat: 39.9000, lng: 116.3980 }, // 初始视图中心
+	zoom: 18, // 初始缩放级数
+	minZoom: 8, // 最小缩放数
+	maxZoom: 22, // 最大缩放数
+	maxBounds: null, // 最大视图范围
+	origin: [39.62413679, 118.16254283], // 自定义坐标系原点
+	// forceInit: true, // 重新加载室内地图时,是否强制恢复视图初始状态 默认false
+}
+let map = new App({ ...initData }) // 创建 map 实例
+map.init(); // map 初始化
 
-// console.log('index', app.View)
-// console.log('index', app.View.getZoom())
-// console.log('index', app.View.getCenter())
-// setTimeout(() => {
-// 	// app.View.setCenter({ lat: 39.9087, lng: 116.3975 }) 
-// 	console.log('index', app.View.getZoom())
-// 	console.log('index', app.View.getCenter())
-// }, 3000)
 
 const BunnyBlitz = {
 	MAP: App,

+ 13 - 7
src/model/AccountAuth.js

@@ -5,7 +5,7 @@ import PubSub from 'pubsub-js';
 // const [fooEvents, setFooEvents] = useState([]);
 
 class AccountAuth {
-    constructor(url, id){
+    constructor(url, id) {
         this.url = url;
         this.mapUUID = id
         // const URL = '121.42.8.157:19702'
@@ -24,7 +24,7 @@ class AccountAuth {
         this._socket.on('disconnect', this.onDisconnect);
         this.authed = false;
     }
-    
+
     onConnect = () => {
         setTimeout(() => {
             var sql = `SELECT 
@@ -47,15 +47,21 @@ class AccountAuth {
             };
             this._socket.emit("REPT", msg, (res) => {
                 // console.log(res.data);
-                PubSub.publish('body.map.got', res.data);
-            });  
+                if (res && res.data && res.data.length > 0) {
+                    // console.log(data[0].map_id);
+                    PubSub.publish('body.draw.indoor', { source: "db", data: JSON.parse(res.data[0].map_data) });
+                } else {
+                    console.error(`DB has NO GeoJson Data Where mapid is ${this.mapUUID}`);
+                }
+
+            });
         }, 1000);
     }
-    
+
     onError(e) {
         console.log("error", e);
     }
-    
+
     onTimeout(e) {
         console.log("timeout", e);
     }
@@ -64,7 +70,7 @@ class AccountAuth {
         console.log("disconnected", e);
     }
 
-    authenticated(){
+    authenticated() {
         return this.authed;
     }
 }

+ 11 - 41
src/view/App.js

@@ -3,7 +3,7 @@ import ReactDOM from 'react-dom';
 import PubSub from 'pubsub-js';
 // import request from 'request-promise-native';
 import { LatLng } from 'leaflet';
-import { osmAuth } from 'osm-auth';
+// import { osmAuth } from 'osm-auth';
 import Body from './Body';
 import VectorDataManager from '../ctrl/VectorDataManager';
 import PresetsManager from '../ctrl/PresetsManager';
@@ -29,13 +29,20 @@ export default class App {
 		}
 
 		this.state = {
-			center: params.center || { lat: 39.9087, lng: 116.3975 }, // { lat: 39.9087, lng: 116.3975 } undefined
+			center: params.center || { lat: 39.9087, lng: 116.3974 }, // { lat: 39.9087, lng: 116.3975 } undefined
 			zoom: params.zoom || 18,
 			minZoom: params.minZoom || 8,
 			maxZoom: params.maxZoom || 22,
 			maxBounds: params.maxBounds || null,
+			force: params.forceInit || false,
 		};
-		this.child = React.createRef();
+
+		window.CONFIG = {
+			data_min_zoom: 18,
+			map_initial_zoom: params.zoom || 18,
+			map_initial_latlng: params.center ? [params.center.lat, params.center.lng] : [39.9087, 116.3974],
+		};
+
 	}
 
 	init() {
@@ -83,43 +90,6 @@ export default class App {
 	}
 
 
-	/**
-	 * Launches authentication process
-	 * @private
-	 */
-	_initAuth() {
-		const opts = {
-			apiUrl: window.CONFIG.osm_api_url,
-			url: window.CONFIG.osm_api_url,
-			client_id: window.CONFIG.oauth_consumer_key,
-			redirect_uri: window.EDITOR_URL,
-			scope: "read_prefs write_api",
-			singlepage: true
-		};
-
-		window.editor_user_auth = osmAuth(opts);
-
-		const params = this._readURLParams(window.location.href);
-
-		if (params.code) {
-			window.editor_user_auth.authenticate(() => {
-				localStorage.setItem("oauth_token", params.code);
-				window.history.replaceState({}, "", window.location.href.replace(/\?.*/, ""));
-			});
-		}
-		else if (localStorage.getItem("oauth_token")) {
-			window.editor_user_auth.bootstrapToken(localStorage.getItem("oauth_token"), () => {
-				this._checkAuth();
-			});
-		}
-		else {
-			//Check if we receive auth token
-			this._checkAuth();
-			this.authWait = setInterval(this._checkAuth.bind(this), 100);
-		}
-	}
-
-
 	/**
 	 * Parse URL parameters
 	 * @private
@@ -167,7 +137,7 @@ export default class App {
 			.then(data => {
 				// 处理获取的数据
 				let json = JSON.parse(data);
-				PubSub.publish("body.draw.loaded", json);
+				PubSub.publish("body.draw.indoor", { source: 'local', data: json });
 			})
 			.catch(error => {
 				// 处理错误

+ 56 - 47
src/view/Body.js

@@ -82,7 +82,6 @@ class Body extends Component {
 			changeset: { tags: {} },
 			datalocked: false,
 			lastUsedPresets: [],
-			zoom: 18,
 		};
 
 		// this._usedImageryNames = new Set();
@@ -220,7 +219,7 @@ class Body extends Component {
 				const locator = layers.find(l => l.properties.id === LOCATOR_OVERLAY_ID);
 				if (
 					!this.state.selectedOverlaysImagery && locator
-					&& (!this.state.zoom || !locator.properties.max_zoom || this.state.zoom <= locator.properties.max_zoom)
+					&& (!window.CONFIG.map_initial_zoom || !locator.properties.max_zoom || window.CONFIG.map_initial_zoom <= locator.properties.max_zoom)
 				) {
 					newState.selectedOverlaysImagery = [layers.find(l => l.properties.id === LOCATOR_OVERLAY_ID)];
 				}
@@ -289,10 +288,61 @@ class Body extends Component {
 		// this._timerMarker = setInterval(() => this._updateMarker(), 1000);
 		// setTimeout(() => {this._readers = window.vectorDataManager.getAllReaders()}, 1000);
 
-		PubSub.subscribe("body.data.update", (msg, data) => {
-			// this._refreshMarkers(data);
-			PubSub.publish('body.data.got', data);
-		})
+		PubSub.subscribe("body.draw.indoor", (msg, data) => {
+			// let source = data.source;
+			let geoJsonData = data.data;
+			window.vectorDataManager.setGeoJsonData(geoJsonData);
+
+			PubSub.publish("body.level.set", { level: 0 });
+			// console.log(this.props)
+			if (this.props.force) {
+				PubSub.publish("map.position.set", {
+					coordinates: {
+						lng: window.CONFIG.map_initial_latlng[1],
+						lat: window.CONFIG.map_initial_latlng[0],
+					},
+					zoom: window.CONFIG.map_initial_zoom
+				});
+			} else {
+				// console.log(this.props)
+				if (this.props.center) {
+					PubSub.publish("map.position.set", {
+						coordinates: {
+							lng: this.props.center.lng,
+							lat: this.props.center.lat,
+						},
+					});
+				} else {
+					PubSub.publish("map.position.set", {
+						coordinates: {
+							lng: geoJsonData.center.x,
+							lat: geoJsonData.center.y,
+						},
+					});
+				}
+			}
+			// if (source === 'db') {
+			// 	PubSub.publish("map.position.set", {
+			// 		coordinates: {
+			// 			lng: window.CONFIG.map_initial_latlng[1],
+			// 			lat: window.CONFIG.map_initial_latlng[0],
+			// 		},
+			// 		zoom: window.CONFIG.map_initial_zoom
+			// 	});
+			// }
+			// else if (source === 'local') {
+			// 	PubSub.publish("map.position.set", {
+			// 		coordinates: {
+			// 			lng: geoJsonData.center.x,
+			// 			lat: geoJsonData.center.y,
+			// 		},
+			// 		zoom: window.CONFIG.map_initial_zoom
+			// 	});
+			// }
+			// else {
+			// 	console.error('Unrecognized Indoor GeoJsonData: 未知的室内地图数据')
+			// }
+		});
 
 
 		/**
@@ -453,18 +503,6 @@ class Body extends Component {
 		// 	);
 		// });
 
-		PubSub.subscribe("body.map.got", (msg, data) => {
-			// this.setState({mapDashboardOpen: true});
-			// console.log(123, msg, data)
-			if (data.length > 0) {
-				// console.log(data[0].map_id);
-				PubSub.publish('body.draw.loaded', JSON.parse(data[0].map_data));
-			} else {
-				console.log("body.map.got none");
-			}
-		});
-
-
 		/**
 		 * Event for changing current shown level
 		 * @event body.level.set
@@ -572,20 +610,6 @@ class Body extends Component {
 		// 	}
 		// });
 
-		// PubSub.subscribe("body.right_panel.change", (msg, data) => {
-		// 	if(!window.editor_user){return}
-		// 	if(!this.state.rightPanelOpen){
-		// 		this.setState({ rightPanelOpen: !this.state.rightPanelOpen, rightPanelTab: data.tab });
-		// 	}else{
-		// 		this.setState({ rightPanelTab: data.tab});
-		// 	}
-		// });
-
-		// PubSub.subscribe("body.map.change", (msg, data) => {
-		// 	// console.log("body.map.change",data);
-		// 	PubSub.publish('body.draw.loaded', JSON.parse(data.map_data));
-		// });
-
 		/**
 		 * Event for toggling one of the side panels
 		 * @event body.panel.toggle
@@ -755,21 +779,6 @@ class Body extends Component {
 		// 	}
 		// });
 
-		// PubSub.subscribe("body.draw.loaded", (msg, data) => {
-		// 	// console.log(data);
-		// 	window.vectorDataManager.setGeoJsonData(data);
-		// 	localStorage.setItem("mapData", JSON.stringify(data));
-		// 	PubSub.publish("body.level.set", { level: 0 });
-
-		// 	PubSub.publish("map.position.set", {
-		// 		coordinates: {
-		// 			lng: data.center.x,
-		// 			lat: data.center.y,
-		// 		},
-		// 		zoom: 18
-		// 	});
-		// });
-
 		/**
 		 * Event when user has done drawing the requested feature
 		 * @event body.draw.done

+ 24 - 12
src/view/Map.js

@@ -169,9 +169,8 @@ class MyMap extends Component {
 	 * 修改地图状态
 	 */
 	setView(center, zoom) {
-		let latlng = L.latLng(center)
 		if (this.elem && this.elem.leafletElement) {
-			this.elem.leafletElement.setView(latlng, zoom);
+			this.elem.leafletElement.setView(center, zoom);
 			// this.setState({
 			// 	center: latlng,
 			// 	zoom: zoom
@@ -181,9 +180,8 @@ class MyMap extends Component {
 		}
 	}
 	setCenter(center) {
-		let latlng = L.latLng(center)
 		if (this.elem && this.elem.leafletElement) {
-			this.elem.leafletElement.setView(latlng, this.state.zoom);
+			this.elem.leafletElement.pathTo(center);
 			// this.setState({
 			// 	center: latlng
 			// })
@@ -250,9 +248,9 @@ class MyMap extends Component {
 	/**
 	 * @param {Array} [10, 20] [-20, 10]
 	 */
-	pathTo(offsetPix) {
+	pathTo(center) {
 		if (this.elem && this.elem.leafletElement) {
-			this.elem.leafletElement.pathTo(offsetPix)
+			this.elem.leafletElement.pathTo(center)
 		} else {
 			console.error('pathTo')
 		}
@@ -262,9 +260,8 @@ class MyMap extends Component {
 	 * @param {Number} zoom 18
 	 */
 	flyTo(center, zoom) {
-		let latlng = L.latLng(center)
 		if (this.elem && this.elem.leafletElement) {
-			this.elem.leafletElement.flyTo(latlng, zoom)
+			this.elem.leafletElement.flyTo(center, zoom)
 		} else {
 			console.error('flyTo')
 		}
@@ -325,7 +322,8 @@ class MyMap extends Component {
 	 * @private
 	 */
 	async _loadData(bounds) {
-		if (this.props.datalocked || (window.CONFIG.always_authenticated && !window.editor_user)) {
+		// (this.props.datalocked || (window.CONFIG.always_authenticated && !window.editor_user))
+		if (this.props.datalocked) {
 			return new Promise(resolve => {
 				setTimeout(() => resolve(this._loadData(bounds)), 100);
 			});
@@ -442,7 +440,7 @@ class MyMap extends Component {
 				</div>
 			}
 			<Map
-				center={L.latLng(this.props.center)}
+				center={this.props.center}
 				zoom={this.props.zoom}
 				minZoom={this.props.minZoom}
 				maxZoom={this.props.maxZoom}
@@ -547,7 +545,14 @@ class MyMap extends Component {
 	 */
 	_followMouse(e) {
 		this._mouseCoords = e.latlng;
-		// console.log(this._mouseCoords)
+		// console.log(e.latlng)
+	}
+	/**
+	 * @private
+	 */
+	_MouseClick(e) {
+		this._mouseCoords = e.latlng;
+		// console.log(e.latlng)
 	}
 
 	componentDidMount() {
@@ -596,7 +601,7 @@ class MyMap extends Component {
 				if (zoom < window.CONFIG.data_min_zoom && (!this._lastZoom || this._lastZoom >= window.CONFIG.data_min_zoom)) {
 					this.elem.container.classList.add("app-map-novector");
 					PubSub.publishSync("body.unselect.feature");
-					// 					PubSub.publish("body.mode.set", { mode: Body.MODE_BUILDING });
+					// PubSub.publish("body.mode.set", { mode: Body.MODE_BUILDING });
 				}
 				else if (zoom >= window.CONFIG.data_min_zoom && (!this._lastZoom || this._lastZoom < window.CONFIG.data_min_zoom)) {
 					this.elem.container.classList.remove("app-map-novector");
@@ -608,6 +613,8 @@ class MyMap extends Component {
 
 		// Follow mouse position
 		this.elem.leafletElement.on("mousemove", this._followMouse, this);
+		// Mouse Click position
+		this.elem.leafletElement.on("click", this._MouseClick, this);
 
 		/**
 		 * Event for map zoom changes
@@ -689,6 +696,10 @@ class MyMap extends Component {
 			// });
 		}
 
+		// Mouse Click position
+		this.elem.leafletElement.off("click", this._MouseClick, this);
+		this.elem.leafletElement.on("click", this._MouseClick, this);
+
 		// Follow mouse position
 		this.elem.leafletElement.off("mousemove", this._followMouse, this);
 		this.elem.leafletElement.on("mousemove", this._followMouse, this);
@@ -701,6 +712,7 @@ class MyMap extends Component {
 
 	componentWillUnmount() {
 		PubSub.unsubscribe("map");
+		this.elem.leafletElement.off("click", this._MouseClick, this);
 		this.elem.leafletElement.off("mousemove", this._followMouse, this);
 		this.elem.leafletElement.off("load");
 		this.elem.leafletElement.off("zoomend");