MapMarker.tsx 16.4 KB
Newer Older
1
import { onUnmounted, inject, watch } from 'vue'
2
import { isFunction } from '@vue/shared'
Q
qiang 已提交
3
import { getRealPath } from '@dcloudio/uni-platform'
4
import { defineSystemComponent, useCustomEvent } from '@dcloudio/uni-components'
Q
qiang 已提交
5
import { Maps, Map, LatLng, Callout, CalloutOptions } from './maps'
6
import { MapType, getMapInfo, getIsAMap } from '../../../helpers/location'
Q
qiang 已提交
7 8 9 10 11
import {
  LatLng as GLatLng,
  Marker as GMarker,
  Label as GLabel,
  Icon,
12
  GoogleMaps,
Q
qiang 已提交
13 14 15 16 17 18 19
} from './maps/google/types'
import {
  Map as QMap,
  LatLng as QLatLng,
  Marker as QMarker,
  Label as QLabel,
  MarkerImage,
20
  QQMaps,
Q
qiang 已提交
21
} from './maps/qq/types'
Q
qiang 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

const props = {
  id: {
    type: [Number, String],
    default: '',
  },
  latitude: {
    type: [Number, String],
    require: true,
  },
  longitude: {
    type: [Number, String],
    require: true,
  },
  title: {
    type: String,
    default: '',
  },
  iconPath: {
    type: String,
    require: true,
  },
  rotate: {
    type: [Number, String],
    default: 0,
  },
  alpha: {
    type: [Number, String],
    default: 1,
  },
  width: {
    type: [Number, String],
    default: '',
  },
  height: {
    type: [Number, String],
    default: '',
  },
  callout: {
    type: Object,
    default: null,
  },
  label: {
    type: Object,
    default: null,
  },
  anchor: {
    type: Object,
    default: null,
  },
  clusterId: {
    type: [Number, String],
    default: '',
  },
  customCallout: {
    type: Object,
    default: null,
  },
  ariaLabel: {
    type: String,
    default: '',
  },
}
interface Point {
  latitude: number
  longitude: number
}
export type Props = Partial<Record<keyof typeof props, any>>
type CustomEventTrigger = ReturnType<typeof useCustomEvent>
type OnMapReadyCallback = (
  map: Map,
Q
qiang 已提交
93
  maps: Maps,
Q
qiang 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  trigger: CustomEventTrigger
) => void
type OnMapReady = (callback: OnMapReadyCallback) => void
export interface TranslateMarkerOptions {
  destination: Point
  autoRotate?: Boolean
  rotate?: number
  duration?: number
  animationEnd?: Function
}
export interface Context {
  id: string
  translate: (options: TranslateMarkerOptions) => void
}
type AddMapChidlContext = (context: Context) => void
type RemoveMapChidlContext = (context: Context) => void

Q
qiang 已提交
111 112
type Label = GLabel | QLabel
interface MarkerExt {
Q
qiang 已提交
113 114 115 116
  callout?: InstanceType<Callout>
  label?: Label
  lastPosition?: LatLng
}
Q
qiang 已提交
117 118
interface GMarkerExt extends GMarker, MarkerExt {}
interface QMarkerExt extends QMarker, MarkerExt {}
119 120
interface AMarkerExt extends AMap.Marker, MarkerExt {}
type Marker = GMarkerExt | QMarkerExt | AMarkerExt
Q
qiang 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
type MarkerLabelStyle = Partial<
  Pick<
    CSSStyleDeclaration,
    | 'position'
    | 'top'
    | 'borderStyle'
    | 'borderColor'
    | 'borderWidth'
    | 'padding'
    | 'borderRadius'
    | 'backgroundColor'
    | 'color'
    | 'fontSize'
    | 'lineHeight'
    | 'marginLeft'
    | 'marginTop'
  >
>

function useMarkerLabelStyle(id: string) {
  const className = 'uni-map-marker-label-' + id
  const styleEl = document.createElement('style')
  styleEl.id = className
  document.head.appendChild(styleEl)
  onUnmounted(() => {
    styleEl.remove()
  })
  return function updateMarkerLabelStyle(style: MarkerLabelStyle) {
    const newStyle: MarkerLabelStyle = Object.assign({}, style, {
      position: 'absolute',
      top: '70px',
      borderStyle: 'solid',
    })
    const div = document.createElement('div')
    Object.keys(newStyle).forEach((key) => {
      div.style[key as keyof MarkerLabelStyle] =
        newStyle[key as keyof MarkerLabelStyle] || ''
    })
    styleEl.innerText = `.${className}{${div.getAttribute('style')}}`
    return className
  }
}
Q
qiang 已提交
163

164
export default /*#__PURE__*/ defineSystemComponent({
Q
qiang 已提交
165 166 167
  name: 'MapMarker',
  props,
  setup(props) {
fxy060608's avatar
fxy060608 已提交
168
    const id = String(!isNaN(Number(props.id)) ? props.id : '')
Q
qiang 已提交
169
    const onMapReady: OnMapReady = inject('onMapReady') as OnMapReady
Q
qiang 已提交
170
    const updateMarkerLabelStyle = useMarkerLabelStyle(id)
Q
qiang 已提交
171
    let marker: Marker
Q
qiang 已提交
172 173
    function removeMarker() {
      if (marker) {
Q
qiang 已提交
174
        if (marker.label && 'setMap' in marker.label) {
Q
qiang 已提交
175
          ;(marker.label as QLabel).setMap(null)
Q
qiang 已提交
176 177
        }
        if (marker.callout) {
178
          removeMarkerCallout(marker.callout)
Q
qiang 已提交
179 180 181 182
        }
        marker.setMap(null)
      }
    }
183 184 185 186 187 188 189
    function removeMarkerCallout(callout: Marker['callout']) {
      if (getIsAMap()) {
        callout!.removeAMapText()
      } else {
        callout!.setMap(null)
      }
    }
Q
qiang 已提交
190 191 192
    onMapReady((map, maps, trigger) => {
      function updateMarker(option: Props) {
        const title = option.title
193 194 195 196 197 198 199 200 201
        const position = getIsAMap()
          ? new (maps as AMap.NameSpace).LngLat(
              option.longitude,
              option.latitude
            )
          : new (maps as QQMaps | GoogleMaps).LatLng(
              option.latitude,
              option.longitude
            )
Q
qiang 已提交
202 203 204
        const img = new Image()
        img.onload = () => {
          const anchor = option.anchor || {}
Q
qiang 已提交
205
          let icon: MarkerImage | Icon
Q
qiang 已提交
206 207 208
          let w
          let h
          let top
Q
qiang 已提交
209 210
          let x = typeof anchor.x === 'number' ? anchor.x : 0.5
          let y = typeof anchor.y === 'number' ? anchor.y : 1
Q
qiang 已提交
211 212 213 214 215 216 217
          if (option.iconPath && (option.width || option.height)) {
            w = option.width || (img.width / img.height) * option.height
            h = option.height || (img.height / img.width) * option.width
          } else {
            w = img.width / 2
            h = img.height / 2
          }
Q
qiang 已提交
218
          top = h - (h - y * h)
Q
qiang 已提交
219 220 221 222 223
          if ('MarkerImage' in maps) {
            icon = new maps.MarkerImage(
              img.src,
              null,
              null,
224 225
              new (maps as QQMaps).Point(x * w, y * h),
              new (maps as QQMaps).Size(w, h)
Q
qiang 已提交
226
            )
227 228 229 230 231 232 233 234
          } else if ('Icon' in maps) {
            // 高德
            icon = new (maps as AMap.NameSpace).Icon({
              image: img.src,
              size: new (maps as AMap.NameSpace).Size(w, h),
              imageSize: new (maps as AMap.NameSpace).Size(w, h),
              imageOffset: new (maps as AMap.NameSpace).Pixel(x * w, y * h),
            })
Q
qiang 已提交
235 236 237
          } else {
            icon = {
              url: img.src,
238 239
              anchor: new (maps as GoogleMaps).Point(x, y),
              size: new (maps as GoogleMaps).Size(w, h),
Q
qiang 已提交
240 241 242 243 244 245 246
            }
          }
          marker.setPosition(position as any)
          marker.setIcon(icon as any)
          if ('setRotation' in marker) {
            marker.setRotation(option.rotate || 0)
          }
Q
qiang 已提交
247
          const labelOpt = option.label || {}
Q
qiang 已提交
248 249
          if ('label' in marker) {
            ;(marker.label as QLabel).setMap(null)
Q
qiang 已提交
250 251 252 253
            delete marker.label
          }
          let label
          if (labelOpt.content) {
Q
qiang 已提交
254 255 256 257 258 259 260 261 262
            const labelStyle = {
              borderColor: labelOpt.borderColor,
              borderWidth: (Number(labelOpt.borderWidth) || 0) + 'px',
              padding: (Number(labelOpt.padding) || 0) + 'px',
              borderRadius: (Number(labelOpt.borderRadius) || 0) + 'px',
              backgroundColor: labelOpt.bgColor,
              color: labelOpt.color,
              fontSize: (labelOpt.fontSize || 14) + 'px',
              lineHeight: (labelOpt.fontSize || 14) + 'px',
Q
qiang 已提交
263 264
              marginLeft: (Number(labelOpt.anchorX || labelOpt.x) || 0) + 'px',
              marginTop: (Number(labelOpt.anchorY || labelOpt.y) || 0) + 'px',
Q
qiang 已提交
265
            }
Q
qiang 已提交
266 267 268 269 270 271
            if ('Label' in maps) {
              label = new maps.Label({
                position: position as QLatLng,
                map: map as QMap,
                clickable: false,
                content: labelOpt.content,
Q
qiang 已提交
272
                style: labelStyle,
Q
qiang 已提交
273 274 275
              })
              marker.label = label
            } else if ('setLabel' in marker) {
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
              if (getIsAMap()) {
                const content = `<div style="
                  margin-left:${labelStyle.marginLeft};
                  margin-top:${labelStyle.marginTop};
                  padding:${labelStyle.padding};
                  background-color:${labelStyle.backgroundColor};
                  border-radius:${labelStyle.borderRadius};
                  line-height:${labelStyle.lineHeight};
                  color:${labelStyle.color};
                  font-size:${labelStyle.fontSize};

                  ">
                  ${labelOpt.content}
                <div>`
                marker.setLabel({
                  content,
                  direction: 'bottom-right',
                } as any)
              } else {
                const className = updateMarkerLabelStyle(labelStyle)
                ;(marker as GMarker).setLabel({
                  text: labelOpt.content,
                  color: labelStyle.color,
                  fontSize: labelStyle.fontSize,
                  className,
                })
              }
Q
qiang 已提交
303
            }
Q
qiang 已提交
304 305 306 307 308
          }
          const calloutOpt = option.callout || {}
          let callout = marker.callout
          let calloutStyle: CalloutOptions
          if (calloutOpt.content || title) {
Q
qiang 已提交
309
            const boxShadow = '0px 0px 3px 1px rgba(0,0,0,0.5)'
Q
qiang 已提交
310 311 312 313 314
            calloutStyle = calloutOpt.content
              ? {
                  position,
                  map,
                  top,
315 316
                  // handle AMap callout offset
                  offsetY: -option.height / 2,
Q
qiang 已提交
317 318 319 320 321 322
                  content: calloutOpt.content,
                  color: calloutOpt.color,
                  fontSize: calloutOpt.fontSize,
                  borderRadius: calloutOpt.borderRadius,
                  bgColor: calloutOpt.bgColor,
                  padding: calloutOpt.padding,
Q
qiang 已提交
323
                  boxShadow: calloutOpt.boxShadow || boxShadow,
Q
qiang 已提交
324 325 326 327 328 329
                  display: calloutOpt.display,
                }
              : {
                  position,
                  map,
                  top,
330 331
                  // handle AMap callout offset
                  offsetY: -option.height / 2,
Q
qiang 已提交
332
                  content: title,
Q
qiang 已提交
333
                  boxShadow,
Q
qiang 已提交
334 335 336 337
                }
            if (callout) {
              callout.setOption(calloutStyle)
            } else {
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
              if (getIsAMap()) {
                const callback = (id: number | string) => {
                  if (id !== '') {
                    trigger('callouttap', {} as Event, {
                      markerId: Number(id),
                    })
                  }
                }
                callout = marker.callout = new maps.Callout(
                  calloutStyle,
                  callback
                )
              } else {
                callout = marker.callout = new maps.Callout(calloutStyle)
                callout.div!.onclick = function ($event: Event) {
                  if (id !== '') {
                    trigger('callouttap', $event, {
                      markerId: Number(id),
                    })
                  }
                  $event.stopPropagation()
                  $event.preventDefault()
Q
qiang 已提交
360
                }
361 362

                // The mobile terminal prevent google map callout click trigger map click
fxy060608's avatar
fxy060608 已提交
363 364 365
                if (getMapInfo().type === MapType.GOOGLE) {
                  callout.div!.ontouchstart = function ($event: Event) {
                    $event.stopPropagation()
366 367 368 369 370
                  }
                  callout.div!.onpointerdown = function ($event: Event) {
                    $event.stopPropagation()
                  }
                }
Q
qiang 已提交
371 372 373 374
              }
            }
          } else {
            if (callout) {
375
              removeMarkerCallout(callout)
Q
qiang 已提交
376 377 378 379
              delete marker.callout
            }
          }
        }
Q
qiang 已提交
380 381 382 383 384
        if (option.iconPath) {
          img.src = getRealPath(option.iconPath)
        } else {
          console.error('Marker.iconPath is required.')
        }
Q
qiang 已提交
385 386 387
      }
      function addMarker(props: Props) {
        marker = new maps.Marker({
388
          map: map as any,
Q
qiang 已提交
389 390 391 392
          flat: true,
          autoRotation: false,
        })
        updateMarker(props)
393 394 395
        const MapsEvent =
          (maps as QQMaps | GoogleMaps).event || (maps as AMap.NameSpace).Event
        MapsEvent.addListener(marker, 'click', () => {
Q
qiang 已提交
396
          const callout = marker.callout
397 398 399 400 401 402 403 404 405
          if (callout && !callout.alwaysVisible) {
            if (getIsAMap()) {
              callout.visible = !callout.visible
              if (callout.visible) {
                marker.callout!.createAMapText()
              } else {
                marker.callout!.removeAMapText()
              }
            } else {
Q
qiang 已提交
406
              callout.set('visible', !callout.visible)
407 408 409 410 411 412
              if (callout.visible) {
                const div = callout.div!
                const parent = div.parentNode!
                parent.removeChild(div)
                parent.appendChild(div)
              }
Q
qiang 已提交
413 414
            }
          }
415

Q
qiang 已提交
416 417 418
          if (id) {
            trigger('markertap', {} as Event, {
              markerId: Number(id),
419 420
              latitude: props.latitude,
              longitude: props.longitude,
Q
qiang 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
            })
          }
        })
      }
      addMarker(props as Props)
      watch(props, updateMarker)
    })
    if (id) {
      const addMapChidlContext: AddMapChidlContext = inject(
        'addMapChidlContext'
      ) as AddMapChidlContext
      const removeMapChidlContext: RemoveMapChidlContext = inject(
        'removeMapChidlContext'
      ) as RemoveMapChidlContext
      const context = {
        id: id,
        translate(data: TranslateMarkerOptions) {
          onMapReady((map, maps, trigger) => {
            const destination = data.destination
            const duration = data.duration
            const autoRotate = !!data.autoRotate
            let rotate: number = Number(data.rotate) || 0
Q
qiang 已提交
443 444 445 446
            let rotation = 0
            if ('getRotation' in marker) {
              rotation = marker.getRotation()
            }
Q
qiang 已提交
447
            const a = marker.getPosition()
448
            const b = new (maps as QQMaps | GoogleMaps).LatLng(
Q
qiang 已提交
449 450 451 452
              destination.latitude,
              destination.longitude
            )
            const distance =
453 454 455 456
              (
                maps as QQMaps | GoogleMaps
              ).geometry.spherical.computeDistanceBetween(a as any, b as any) /
              1000
Q
qiang 已提交
457 458 459 460
            const time =
              (typeof duration === 'number' ? duration : 1000) /
              (1000 * 60 * 60)
            const speed = distance / time
461 462 463 464
            const MapsEvent =
              (maps as QQMaps | GoogleMaps).event ||
              (maps as AMap.NameSpace).Event
            const movingEvent = MapsEvent.addListener(
Q
qiang 已提交
465 466 467 468 469 470
              marker,
              'moving',
              (e: any) => {
                const latLng = e.latLng
                const label = marker.label
                if (label) {
Q
qiang 已提交
471
                  ;(label as QLabel).setPosition(latLng)
Q
qiang 已提交
472 473 474 475 476 477 478
                }
                const callout = marker.callout
                if (callout) {
                  callout.setPosition(latLng)
                }
              }
            )
479
            const event = MapsEvent.addListener(marker, 'moveend', () => {
Q
qiang 已提交
480 481
              event.remove()
              movingEvent.remove()
482
              marker.lastPosition = a as QLatLng
Q
qiang 已提交
483
              marker.setPosition(b as any)
Q
qiang 已提交
484 485
              const label = marker.label
              if (label) {
Q
qiang 已提交
486
                ;(label as QLabel).setPosition(b as QLatLng)
Q
qiang 已提交
487 488 489 490 491 492
              }
              const callout = marker.callout
              if (callout) {
                callout.setPosition(b)
              }
              const cb = data.animationEnd
493
              if (isFunction(cb)) {
Q
qiang 已提交
494 495 496 497 498 499
                cb()
              }
            })
            let lastRtate = 0
            if (autoRotate) {
              if (marker.lastPosition) {
500 501 502
                lastRtate = (
                  maps as QQMaps | GoogleMaps
                ).geometry.spherical.computeHeading(
Q
qiang 已提交
503 504
                  marker.lastPosition as any,
                  a as any
Q
qiang 已提交
505 506
                )
              }
Q
qiang 已提交
507
              rotate =
508 509 510 511
                (maps as QQMaps | GoogleMaps).geometry.spherical.computeHeading(
                  a as any,
                  b as any
                ) - lastRtate
Q
qiang 已提交
512 513 514 515 516 517 518 519
            }
            if ('setRotation' in marker) {
              marker.setRotation(rotation + rotate)
            }
            if ('moveTo' in marker) {
              marker.moveTo(b as QLatLng, speed)
            } else {
              marker.setPosition(b as GLatLng)
520
              MapsEvent.trigger(marker, 'moveend', {})
Q
qiang 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533
            }
          })
        },
      }
      addMapChidlContext(context)
      onUnmounted(() => removeMapChidlContext(context))
    }
    onUnmounted(removeMarker)
    return () => {
      return null
    }
  },
})