LoctaionPicker.tsx 11.4 KB
Newer Older
Q
qiang 已提交
1
/// <reference types="google.maps" />
fxy060608's avatar
fxy060608 已提交
2
import { extend } from '@vue/shared'
Q
qiang 已提交
3 4 5 6 7 8
import { ref, ExtractPropTypes, reactive, computed, watch } from 'vue'
import { debounce } from '@dcloudio/uni-shared'
import {
  createSvgIconVNode,
  ICON_PATH_CLOSE,
  ICON_PATH_CONFIRM,
Q
qiang 已提交
9 10
  initI18nChooseLocationMsgsOnce,
  useI18n,
Q
qiang 已提交
11 12 13 14 15 16 17
} from '@dcloudio/uni-core'
import {
  defineSystemComponent,
  Input,
  ScrollView,
} from '@dcloudio/uni-components'
import { usePreventScroll } from '../../../../helpers/usePreventScroll'
Q
qiang 已提交
18 19 20 21
import {
  Point,
  ICON_PATH_LOCTAION,
  ICON_PATH_TARGET,
Q
qiang 已提交
22 23
  MapType,
  getMapInfo,
Q
qiang 已提交
24
} from '../../../../helpers/location'
Q
qiang 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
import { Map } from '../../../../view/components'
import { getJSONP } from '../../../../helpers/getJSONP'
import { getLocation } from '../../location/getLocation'

const props = {
  latitude: {
    type: Number,
  },
  longitude: {
    type: Number,
  },
}

export type Props = ExtractPropTypes<typeof props>

function distance(distance: number): string {
  if (distance > 100) {
    return `${
      distance > 1000 ? (distance / 1000).toFixed(1) + 'k' : distance.toFixed(0)
    }m | `
  } else if (distance > 0) {
Q
qiang 已提交
46
    return '<100m | '
Q
qiang 已提交
47 48 49 50
  } else {
    return ''
  }
}
Q
qiang 已提交
51

Q
qiang 已提交
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
interface State {
  latitude: number
  longitude: number
  keyword: string
  searching: boolean
}
function useState(props: Props) {
  const state: State = reactive({
    latitude: 0,
    longitude: 0,
    keyword: '',
    searching: false,
  })
  function updatePosition() {
    if (props.latitude && props.longitude) {
      state.latitude = props.latitude
      state.longitude = props.longitude
    }
  }
  watch([() => props.latitude, () => props.longitude], updatePosition)
  updatePosition()
  return state
}

export interface Poi {
  name: string
  address: string
  distance: number
  latitude: number
  longitude: number
}

function useList(state: State) {
  const key = __uniConfig.qqMapKey
  const list: Poi[] = reactive([])
  const selectedIndexRef = ref(-1)
  const selectedRef = computed(() => list[selectedIndexRef.value])
  const listState = reactive({
    loading: true,
Q
qiang 已提交
91 92
    // google map default
    pageSize: 20,
Q
qiang 已提交
93
    pageIndex: 1,
Q
qiang 已提交
94 95
    hasNextPage: true,
    nextPage: null as null | (() => void),
Q
qiang 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109
    selectedIndex: selectedIndexRef,
    selected: selectedRef,
  })
  const adcodeRef = ref('')
  const boundaryRef = computed(() =>
    adcodeRef.value
      ? `region(${adcodeRef.value},1,${state.latitude},${state.longitude})`
      : `nearby(${state.latitude},${state.longitude},5000)`
  )
  function pushData(array: any[]) {
    array.forEach((item) => {
      list.push({
        name: item.title,
        address: item.address,
110
        distance: item._distance || item.distance,
Q
qiang 已提交
111 112 113 114 115 116 117
        latitude: item.location.lat,
        longitude: item.location.lng,
      })
    })
  }
  function getList() {
    listState.loading = true
Q
qiang 已提交
118 119 120 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
    const mapInfo = getMapInfo()
    if (mapInfo.type === MapType.GOOGLE) {
      if (listState.pageIndex > 1 && listState.nextPage) {
        listState.nextPage()
        return
      }
      const service = new google.maps.places.PlacesService(
        document.createElement('div')
      )
      service[state.searching ? 'textSearch' : 'nearbySearch'](
        {
          location: {
            lat: state.latitude,
            lng: state.longitude,
          },
          query: state.keyword,
          radius: 5000,
        },
        (results, state, page) => {
          listState.loading = false
          if (results && results.length) {
            results.forEach((item) => {
              list.push({
                name: item.name || '',
                address: item.vicinity || item.formatted_address || '',
                distance: 0,
                latitude: item.geometry!.location!.lat(),
                longitude: item.geometry!.location!.lng(),
              })
            })
          }
          if (page) {
            if (!page.hasNextPage) {
              listState.hasNextPage = false
            } else {
              listState.nextPage = () => {
                page.nextPage()
              }
            }
Q
qiang 已提交
157 158
          }
        }
Q
qiang 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
      )
    } else if (mapInfo.type === MapType.QQ) {
      const url = state.searching
        ? `https://apis.map.qq.com/ws/place/v1/search?output=jsonp&key=${key}&boundary=${boundaryRef.value}&keyword=${state.keyword}&page_size=${listState.pageSize}&page_index=${listState.pageIndex}`
        : `https://apis.map.qq.com/ws/geocoder/v1/?output=jsonp&key=${key}&location=${state.latitude},${state.longitude}&get_poi=1&poi_options=page_size=${listState.pageSize};page_index=${listState.pageIndex}`
      // TODO 列表加载失败提示
      getJSONP(
        url,
        {
          callback: 'callback',
        },
        (res: any) => {
          listState.loading = false
          if (state.searching && 'data' in res && res.data.length) {
            pushData(res.data)
          } else if ('result' in res) {
            const result = res.result
            adcodeRef.value = result.ad_info ? result.ad_info.adcode : ''
            if (result.pois) {
              pushData(result.pois)
            }
          }
          if (list.length === listState.pageSize * listState.pageIndex) {
            listState.hasNextPage = false
          }
        },
        () => {
          listState.loading = false
        }
      )
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    } else if (mapInfo.type === MapType.AMAP) {
      window.AMap.plugin('AMap.PlaceSearch', function () {
        var autoOptions = {
          city: '全国',
          pageSize: 10,
          pageIndex: listState.pageIndex,
        }
        var placeSearch = new (window.AMap as any).PlaceSearch(autoOptions)
        if (state.searching) {
          placeSearch.searchNearBy(
            state.keyword,
            [state.longitude, state.latitude],
            50000,
            function (status: string, result: any) {
              if (status === 'error') {
                console.error(result)
              } else if (status === 'no_data') {
                listState.hasNextPage = false
              } else {
                pushData(result.poiList.pois)
              }
            }
          )
        } else {
          placeSearch.searchNearBy(
            '',
            [state.longitude, state.latitude],
            5000,
            function (status: string, result: any) {
              if (status === 'error') {
                console.error(result)
              } else if (status === 'no_data') {
                listState.hasNextPage = false
              } else {
                pushData(result.poiList.pois)
              }
            }
          )
        }
        listState.loading = false
      })
Q
qiang 已提交
230
    }
Q
qiang 已提交
231 232
  }
  function loadMore() {
Q
qiang 已提交
233
    if (!listState.loading && listState.hasNextPage) {
Q
qiang 已提交
234 235 236 237 238 239 240
      listState.pageIndex++
      getList()
    }
  }
  function reset() {
    listState.selectedIndex = -1
    listState.pageIndex = 1
Q
qiang 已提交
241 242
    listState.hasNextPage = true
    listState.nextPage = null
Q
qiang 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    list.splice(0, list.length)
  }
  return {
    listState,
    list,
    loadMore,
    reset,
    getList,
  }
}

export default /*#__PURE__*/ defineSystemComponent({
  name: 'LoctaionPicker',
  props,
  emits: ['close'],
  setup(props, { emit }) {
    usePreventScroll()
Q
qiang 已提交
260 261
    initI18nChooseLocationMsgsOnce()
    const { t } = useI18n()
Q
qiang 已提交
262 263
    const state = useState(props)
    const { list, listState, loadMore, reset, getList } = useList(state)
fxy060608's avatar
fxy060608 已提交
264 265 266 267 268 269 270 271 272 273
    const search = debounce(
      () => {
        reset()
        if (state.keyword) {
          getList()
        }
      },
      1000,
      { setTimeout, clearTimeout }
    )
Q
qiang 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    watch(
      () => state.searching,
      (val) => {
        reset()
        if (!val) {
          getList()
        }
      }
    )
    function onInput(event: { detail: { value: string } }) {
      state.keyword = event.detail.value
      search()
    }

    function onChoose() {
fxy060608's avatar
fxy060608 已提交
289
      emit('close', extend({}, listState.selected))
Q
qiang 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    }

    function onBack() {
      emit('close')
    }

    function onRegionChange(event: { detail: { centerLocation: Point } }) {
      const centerLocation = event.detail.centerLocation
      if (centerLocation) {
        // TODO 图钉 icon 动画
        move(centerLocation)
      }
    }

    function moveToLocation() {
      getLocation({
        type: 'gcj02',
        success: move,
        fail: () => {
Q
qiang 已提交
309 310 311 312
          // move({
          //   latitude: 0,
          //   longitude: 0,
          // })
Q
qiang 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
        },
      })
    }

    function move({ latitude, longitude }: Point) {
      state.latitude = latitude
      state.longitude = longitude
      if (!state.searching) {
        reset()
        getList()
      }
    }

    if (!state.latitude || !state.longitude) {
      moveToLocation()
    }

    return () => {
      const content = list.map((item, index) => {
        return (
          <div
            key={index}
            class={{
              'list-item': true,
              selected: listState.selectedIndex === index,
            }}
            onClick={() => {
              listState.selectedIndex = index
              state.latitude = item.latitude
              state.longitude = item.longitude
            }}
          >
            {createSvgIconVNode(ICON_PATH_CONFIRM, '#007aff', 24)}
            <div class="list-item-title">{item.name}</div>
            <div class="list-item-detail">
              {distance(item.distance)}
              {item.address}
            </div>
          </div>
        )
      })
      if (listState.loading) {
        content.unshift(
          <div class="list-loading">
            <i class="uni-loading" />
          </div>
        )
      }
      return (
        <div class="uni-system-choose-location">
          <Map
            latitude={state.latitude}
            longitude={state.longitude}
            class="map"
            show-location
Q
qiang 已提交
368 369
            libraries={['places']}
            onUpdated={getList}
Q
qiang 已提交
370 371
            onRegionchange={onRegionChange}
          >
Q
qiang 已提交
372 373 374 375
            <div
              class="map-location"
              style={`background-image: url("${ICON_PATH_TARGET}")`}
            />
Q
qiang 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
            <div class="map-move" onClick={moveToLocation}>
              {createSvgIconVNode(ICON_PATH_LOCTAION, '#000000', 24)}
            </div>
          </Map>
          <div class="nav">
            <div class="nav-btn back" onClick={onBack}>
              {createSvgIconVNode(ICON_PATH_CLOSE, '#ffffff', 26)}
            </div>
            <div
              class={{
                'nav-btn': true,
                confirm: true,
                disable: !listState.selected,
              }}
              onClick={onChoose}
            >
              {createSvgIconVNode(ICON_PATH_CONFIRM, '#ffffff', 26)}
            </div>
          </div>
          <div class="menu">
            <div class="search">
              <Input
                value={state.keyword}
                class="search-input"
Q
qiang 已提交
400
                placeholder={t('uni.chooseLocation.search')}
Q
qiang 已提交
401 402 403 404 405 406 407 408 409 410 411 412
                // @ts-ignore
                onFocus={() => (state.searching = true)}
                onInput={onInput}
              />
              {state.searching && (
                <div
                  class="search-btn"
                  onClick={() => {
                    state.searching = false
                    state.keyword = ''
                  }}
                >
Q
qiang 已提交
413
                  {t('uni.chooseLocation.cancel')}
Q
qiang 已提交
414 415 416 417 418 419 420 421 422 423 424 425
                </div>
              )}
            </div>
            <ScrollView scroll-y class="list" onScrolltolower={loadMore}>
              {content}
            </ScrollView>
          </div>
        </div>
      )
    }
  },
})