百度地圖--獲取自定義區域JSON資料(下)
阿新 • • 發佈:2018-12-16
基於百度地圖的自定義區域繪圖–繪製區域
- 基於上一篇的尊卑工作後,開始正式繪圖: 第一步:建立react專案(我的目錄結構如圖)
- index.html內容:
<!DOCTYPE html> <html lang="en" style="width:100%; height:100%;"> <head> <style> /*清除logo*/ .BMap_cpyCtrl { display: none; } .anchorBL { display: none; } </style> <meta charset="utf-8"> <link rel="shortcut icon" href="%PUBLIC_URL%/urltitle.ico"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <title>React App</title> <script src="http://api.map.baidu.com/api?v=1.2&ak=kDfrUwYGgSaUbDLwKGXBwlaseKZbI7I9" type="text/javascript"></script> <script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script> <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" /> <!--載入檢索資訊視窗--> <script type="text/javascript" src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script> <link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" /> </head> <body style="width:100%; height:100%;"> <noscript> You need to enable JavaScript to run this app. </noscript> <div id="root" style="width:100%; height:90%;"></div> </body> </html>
- src下的index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './StyleCc/index.css'; import App from './ComCc/App'; import BaiduMap from './ComCc/BaiduMap';//引入我的地圖元件 import * as serviceWorker from './JSCc/serviceWorker'; ReactDOM.render(<BaiduMap />, document.getElementById('root')); //插入到html的id為root的標籤中 serviceWorker.unregister();
- 核心部分BaiduMap.js(程式碼比較多建議直接複製),到第五步見操作步驟
import React, { Component } from 'react'; import $ from 'jquery'; var overlays = []; const { BMap, BMAP_STATUS_SUCCESS,BMAP_NORMAL_MAP,BMAP_HYBRID_MAP ,BMapLib, BMAP_ANCHOR_TOP_RIGHT} = window ; var map ; class BaiduMap extends Component { constructor(props) { super(props); this.state={ isht:false, isdragg: true, } } componentDidMount () { console.log("元件載入結束"); map = new BMap.Map('baidumap'); //建立一個座標 var point =new BMap.Point(104.073015,30.664129); //地圖初始化,設定中心點座標和地圖級別 map.centerAndZoom(point,11);//初始化地圖,設定中心點座標,以及地圖級別 map.addControl(new BMap.MapTypeControl({ mapTypes:[ BMAP_NORMAL_MAP, BMAP_HYBRID_MAP ]})); map.addControl(new BMap.ScaleControl()); //ScaleControl --------比例尺控制元件 map.addControl(new BMap.OverviewMapControl());//OverviewMapControl ----縮圖控制元件 map.addControl(new BMap.NavigationControl());//NavigationControl ------縮放控制元件 map.setCurrentCity("成都"); map.enableScrollWheelZoom(true); //開啟滑鼠滾輪縮放 var fnadd = this.fnAddmarker; map.addEventListener('click', function(e){ //監聽 fnadd(new BMap.Point(e.point.lng,e.point.lat)); }); } fnAddmarker = (point) => { var prepoint = overlays.length>0? overlays[overlays.length-1]:point; overlays.push(point); var polyline = new BMap.Polyline([prepoint,point], {strokeColor:"blue", strokeWeight:4, strokeOpacity:0.6}); map.addOverlay(polyline); var mark = new BMap.Marker(point ); map.addOverlay(mark); // 將標註新增到地圖中 } fnDeleteId = (id) =>{ if (id+1) overlays.splice(id,1);//刪除並重新繪圖 map.clearOverlays();// 清除標註 var f = this.fnEnableDragging; var fndelte = this.fnDeleteId; for(var i = 0;i<overlays.length;i++) { //var mark = new BMap.Marker(overlays[i],{icon:icons}); var mark = new BMap.Marker(overlays[i] ); mark["id"] = i; var label = new BMap.Label(i, { offset: new BMap.Size(2, 3) }); mark.setLabel(label); mark.enableDragging(); mark.addEventListener("dragend", function (e) { //拖拽觸發函式 overlays[this.id] = new BMap.Point(e.point.lng, e.point.lat); f(this.id); }); mark.addEventListener("onmousedown", function (e) { //拖拽觸發函式 if(e.domEvent.button==2) { fndelte( this.id); } else if (e.domEvent.button == 0) { console.log("左鍵") } }); // mark.setLabel(new BMap.Label("我是id="+i,null)); map.addOverlay(mark); } map.addOverlay(new BMap.Polygon(overlays, null)); //增加多邊形 } fnEnableDragging = (chid) => {//可拖拽 const {isht} = this.state; // var icons = new BMap.Icon(" http://localhost:8080/weaver/weaver.file.FileDownload?fileid=12990&requestid=2904961&desrequestid=0&f_weaver_belongto_userid=1&f_weaver_belongto_usertype=0&authStr=dmlld0NoYWluPTI5MDQ5NjF8bWFpbmlkPTI5MDQ5NjF8&authSignatureStr=2121247092f29f46f8b356dbd51f3568", new BMap.Size(15, 15)); //基於web的自定義圖片 // var icons = new BMap.Icon('./xj.jpg', new BMap.Size(50, 50)); map.clearOverlays();// 清除標註 var f = this.fnEnableDragging; var fndelte = this.fnDeleteId; overlays = this.fnAddPoint(chid); for(var i = 0;i<overlays.length;i++) { // var mark = new BMap.Marker(overlays[i],{icon:icons}); var mark = new BMap.Marker(overlays[i] ); mark["id"] = i; var label = new BMap.Label(i, { offset: new BMap.Size(2, 3) }); mark.setLabel(label); mark.enableDragging(); mark.addEventListener("dragend", function (e) { //拖拽觸發函式 overlays[this.id] = new BMap.Point(e.point.lng, e.point.lat); f(this.id); }); mark.addEventListener("onmousedown", function (e) { //拖拽觸發函式 if(e.domEvent.button==2) { fndelte( this.id); } else if (e.domEvent.button == 0) { console.log("左鍵") } }); map.addOverlay(mark); } if(isht) {// 判斷是否已經畫圖過 var polygon = new BMap.Polygon(overlays, null); //建立多邊形 map.addOverlay(polygon); //增加多邊形 } } fnAddPoint = (id) => {//在兩個點之間新增虛擬的觸發點 var os = []; const {isdragg} = this.state; if ((id==-1 )&& isdragg) { this.setState({isdragg:false});//只能實新增一次,即以後的isdragg全是false for(var i=0;i<overlays.length;i++) { os.push(overlays[i]); os.push(new BMap.Point(((overlays[i].lng+overlays[(i+1)%overlays.length].lng)/2).toFixed(6), ((overlays[i].lat+overlays[(i+1)%overlays.length].lat)/2).toFixed(6))); } }else if(id>=0) { os = overlays;//先在id後面新增,再在id前面新增 os.splice(id+1,0,new BMap.Point( ((overlays[id].lng+overlays[(id+1)%overlays.length].lng)/2).toFixed(6), ((overlays[id].lat+overlays[(id+1)%overlays.length].lat)/2).toFixed(6) )); os.splice(id==0?overlays.length:id,0,new BMap.Point( ((overlays[(id==0?overlays.length-1:id-1)%overlays.length].lng+overlays[(id)%overlays.length].lng)/2).toFixed(6), ((overlays[(id==0?overlays.length-1:id-1)%overlays.length].lat+overlays[(id)%overlays.length].lat)/2).toFixed(6) )); } else { os = overlays; } return os; } fnDisableDragging = ()=> {//不可拖拽 const {isht, isdragg} = this.state; map.clearOverlays();// 清除標註 var f = this.fnGetNum; for(var i = 0;i<overlays.length;i++) { var mark = new BMap.Marker(overlays[i]); mark["id"] = i; mark.disableDragging(); map.addOverlay(mark); } if(isht) { var polygon = new BMap.Polygon(overlays, null); //建立多邊形 map.addOverlay(polygon); //增加多邊形 } this.setState({isdragg:false}) } fnHuaTu = () => { map.__listeners.onclick = null; //取消監聽 this.fnAddPoint(); const {isht} = this.state; if(!isht&&overlays.length>2) {//兩個節點是不能形成面的 var polygon = new BMap.Polygon(overlays, null); //建立多邊形 // var polygon = new BMap.Polygon(overlays, {strokeColor:156, strokeWeight:2, strokeOpacity:0.5,fillColor:155}); //建立多邊形樣式 map.addOverlay(polygon); //增加多邊形 this.setState({isht:true}); } } fnColose =() =>{ overlays.length = 0; map.clearOverlays();// 清除標註 this.setState({isht:false}); this.componentDidMount(); } fnGetJsonDatas() { var jsons ={"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"測試"},"geometry":{ "type":"Polygon","coordinates":[ ] }}]}; var s = []; for(var i = 0;i<overlays.length;i++) { s.push([overlays[i].lng,overlays[i].lat]); } s.push([overlays[0].lng,overlays[0].lat]);//形成閉環 jsons.features[0].geometry["coordinates"] = [s]; console.log(JSON.stringify(jsons,null, 4)); } fnTestImg =() => { var img = new BMap.Icon('./xj.jpg', new BMap.Size(50, 50)); for(var i = 0;i<overlays.length;i++) { var mark = new BMap.Marker(overlays[i],{icon:img}); mark["id"] = i; mark.disableDragging(); map.addOverlay(mark); } } render() { return ( <div className="baidumap" style={{width:'100%',height:'100%' }}> <div id="baidumap" style={{width:'100%',height:'100%' }}></div> <div> <input type={"button"} value={"繪圖"} onClick={this.fnHuaTu}/> <input type={"button"} value={"json資料"} onClick={this.fnGetJsonDatas}/> <input type={"button"} value={"清除"} onClick={this.fnColose}/> <input type="button" onClick={this.fnEnableDragging.bind(this,-1)} value="可拖拽" /> <input type="button" onClick={this.fnDisableDragging} value="不可拖拽" /> <input type="button" onClick={this.fnTestImg} value="測試自定義圖示" /> <div>圖片測試<img src="./xj.jpg" width="50" height="50"/></div> </div> </div> ); } } export default BaiduMap;
-
專案搭建步驟、操作步驟(因為這只是一天的內容,沒有做其他詳細的邏輯控制,最好按照我的給定步驟操作,遇到問題可以檢視程式碼,基本上程式碼比較簡單,容易上手) 搭建步驟 a、建立react專案(npm install -g create-react-app)我這裡使用的這個命令(個人感覺這個是建立最快的),詳細搭建方式點選參考react搭建; b、整理資源(主要是圖片資源) c、建立類似我的目錄結構(方便你直接使用); d、建立完成後啟動你的專案(npm start/yarn start);
操作步驟 a、地圖上建議隨機選擇三個以上的點(圖嘛,至少三點成圖),建議選點不在一條直線上。 b、點選下方的【繪圖】(把線變成圖) c、點選【可拖拽】:生成拖拽點,然後你就可以隨意拖拽點生成你想要的區域圖。 d、你可以把滑鼠放在生成選點上,滑鼠右鍵可以刪除當前點(建立在可拖拽的情況下) e、點選【不可拖拽後選點上將不會有序號】; f、點選【清楚】將清空所有資料,重新繪圖; g、點選json資料,將在後臺打印出,你選擇的資料(至於這種JSON的解析JSON.stringify()請參考我的另一篇文章我的JSON問題); h、點選測試自定義圖示,可以修改原生圖示為你自己的圖示;
總結:這個是今天大致寫的demo還有待完善,很多邏輯還沒有處理,但是按照步驟得到資料,以及演示,具體邏輯大家可以自行完善。 請大家多多指教。謝謝