index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import { randomNum } from '@/utils/util'
  2. const app = getApp()
  3. Page({
  4. data: {
  5. latitude: 23.099994,
  6. longitude: 113.324520,
  7. markers: [],
  8. userInfo: null,
  9. },
  10. wsListener({ data = '' }) {
  11. const { biz_code, data: body } = JSON.parse(data) || {}
  12. if (biz_code === 'ling_xiu_warning') this.addMarkers(body)
  13. },
  14. connectWs() {
  15. const { baseUrl } = app.globalData
  16. const { token } = this.data.userInfo || []
  17. if (token) {
  18. this.socketCli = wx.connectSocket({
  19. url: `wss://${baseUrl}/dockWebsocket?x-auth-token=${encodeURIComponent(token)}&userType=1`,
  20. })
  21. this.socketCli.onMessage(this.wsListener)
  22. }
  23. },
  24. addMarkers(newMarker) {
  25. const { markers } = this.data
  26. const { longitude, latitude } = newMarker
  27. const [lng, lat] = app.coordtransform.wgs84togcj02(longitude, latitude)
  28. newMarker.longitude = lng
  29. newMarker.latitude = lat
  30. if (markers.length >= 10) markers.splice(0, 1)
  31. markers.unshift({
  32. id: randomNum(5),
  33. width: 32,
  34. height: 32,
  35. iconPath: '/static/img/marker_alarm.png',
  36. customCallout: {
  37. anchorY: 0,
  38. anchorX: 0,
  39. display: 'ALWAYS'
  40. },
  41. show: true,
  42. ...newMarker,
  43. longitude: lng,
  44. latitude: lat,
  45. })
  46. this.mapCtx.moveToLocation({
  47. longitude: lng,
  48. latitude: lat,
  49. })
  50. this.setData({
  51. markers
  52. })
  53. },
  54. removeMarkers() {
  55. this.setData({
  56. markers: []
  57. })
  58. },
  59. onMarkerTap(e) {
  60. const { markerId } = e.detail
  61. const item = this.data.markers.find(r => r.id === markerId)
  62. const idx = this.data.markers.findIndex(r => r.id === markerId)
  63. this.setData({
  64. [`markers[${idx}]`]: {
  65. ...item,
  66. show: !item.show
  67. }
  68. })
  69. },
  70. onShow() {
  71. const userInfo = wx.getStorageSync('userInfo')
  72. if (userInfo) {
  73. this.setData({ userInfo })
  74. this.connectWs()
  75. }
  76. },
  77. onLoad: function () {
  78. this.mapCtx = wx.createMapContext('map')
  79. wx.getLocation({
  80. type: 'gcj02',
  81. success: (res) => {
  82. const { longitude, latitude } = res;
  83. this.setData({
  84. longitude, latitude
  85. })
  86. }
  87. })
  88. },
  89. onHide() {
  90. this.socketCli && this.socketCli.close()
  91. }
  92. })