業務場景如下:
1.在地圖上點擊企業位置mark時,地圖不做縮放和移動操作(能點擊mark,說明該位置肯定在可視區域內)。
2.點擊右側企業列表的企業時,如果企業的位置不在當前可視區域內,就需要將地圖平滑的移動到該企業位置,並且需要縮小地圖,先查看到該企業位於哪個區域,再將地圖放大到之前縮放的級別。
實現思路:
高德地圖有幾個關系判斷的API:判斷點是否在線上、點是否在多邊形內、面與面的幾何關系,可看下方鏈接示例
https://lbs.amap.com/api/javascript-api/example/relationship-judgment/is-point-on-segment
暫時沒有看到有API能直接實現判斷點是否在當前地圖可視范圍內,所以就想的使用判斷點是否在多邊形內來實現。
1.要使用判斷點是否在多邊形內來實現,就必須先將當前地圖可視范圍想象為多邊形,獲取其四邊的路徑位置,因為界面是方形的,所以只需要獲取四個點的位置即可。
2.高德地圖提供啦獲取當前可是范圍的bounds API,map.getBounds(),可以獲取到東北角和西南角的坐標位置。
3.通過東北角和西南角的坐標再去獲取到東南角和西北角的坐標位置,就有啦四個點的位置。
4.通過API AMap.GeometryUtil.isPointInRing(point, path)判斷是否在這四個點組成的面內。
注:path里坐標位置的先后順序很重要。
實現方法:
creatEnterpriseDetailMark (markerColor, options) { const bounds = this.Map.getBounds(); const NorthEast = bounds.getNorthEast(); const SouthWest = bounds.getSouthWest(); const SouthEast = [NorthEast.lng, SouthWest.lat]; const NorthWest = [SouthWest.lng, NorthEast.lat]; const path = [[NorthEast.lng, NorthEast.lat], SouthEast, [SouthWest.lng, SouthWest.lat], NorthWest]; // 將地圖可視區域四個角位置按照順序放入path,用於判斷point是否在可視區域 const isPointInRing = AMap.GeometryUtil.isPointInRing(options.position, path); // 判斷point是否在可視區域 let zoom; this.Map.remove(this.areaMarks); const icon = markerColor ? markerColor : '#4fd0f7'; if (!options.position) { return; } // this.Map.setZoom(11); // this.Map.panTo(options.position); const enterpriseMarker = new AMap.CircleMarker({ // 繪制企業位置mark map: this.Map, center: options.position, radius: 8, strokeColor: 'white', strokeWeight: 2, strokeOpacity: 0.5, fillColor: icon, fillOpacity: 1, zIndex: 10, bubble: true, cursor: 'pointer', clickable: true, extData: { id: options.id, name: options.name, position: options.position } }); const changeZoom = () => { this.Map.setZoomAndCenter(zoom, options.position); this.Map.off('zoomend', changeZoom); // 移除zoomend事件綁定 https://lbs.amap.com/api/javascript-api/reference/event }; if (!isPointInRing) { zoom = this.Map.getZoom(); // 保存當前的縮放級別,用於后面恢復 // this.Map.setFitView(); this.Map.setZoom(10); this.Map.on('zoomend', changeZoom); } this.areaMarks.push(enterpriseMarker); }