search-address.vue 7.3 KB
<template>
  <Page name="search-address">
    <template #header>
      <view style="display: flex; align-items: center">
        <view style="flex: 1"><search-bar v-model="searchForm.query" placeholder="请输入需要搜索的地址关键词" auto @confirm="onSearch" /></view>
        <view @click="selectLocation" style="width: 50px; padding-left: 10px; display: flex; align-items: center">
          <span> <u-icon name="map-fill"></u-icon></span>地图
        </view>
      </view>
    </template>
    <template #content>
      <template v-if="list.length === 0 && hisList.length > 0">
        <view class="search-history">历史地址</view>
        <template v-for="(item, index) in hisList">
          <zui-cell :key="index" :title="item.address" :label="`${item.cityName}${item.areaName}`" @click="onSelect(item)"></zui-cell>
        </template>
      </template>
      <List ref="list" v-model="list" :api="searchAPI">
        <template v-for="(item, index) in list">
          <zui-cell :key="index" :title="item.name" :label="`${item.cityName}${item.areaName}${item.address}`" @click="onSelect(item, true)"></zui-cell>
        </template>
        <template #empty>
          <view v-if="hisList.length > 0"></view>
          <u-empty v-else icon="https://download.shjiuze.cn/assets/image/empty/list.png" text="暂无数据"></u-empty>
        </template>
      </List>
    </template>
  </Page>
</template>

<script>
import { urlParam } from '@/utils/param';

export default {
  props: {
    getHisFun: Function,
  },
  data() {
    return {
      searchForm: {
        query: '',
      },
      list: [],
      hisList: [],
      lng: '',
      lat: '',
    };
  },
  onLoad(options) {
    this.lng = options.lng || '';
    this.lat = options.lat || '';
    this.queryHis(options.type);
  },
  methods: {
    queryHis(type) {
      if (type === 'getStartLatestAddress') {
        uni.$u.api.freightOrder.getStartLatestAddress({}).then(res => {
          this.hisList = res.result || [];
        });
      }
      if (type === 'getEndLatestAddress') {
        uni.$u.api.freightOrder.getEndLatestAddress({}).then(res => {
          this.hisList = res.result || [];
        });
      }
    },
    searchAPI() {
      if (!this.searchForm.query) {
        return new Promise(resolve => {
          resolve({ result: [], totalCount: 0 });
        });
      }
      return new Promise((resolve, reject) => {
        let params = {
          key: '1b987a62e5685a58cda5933e1bc66044',
          keywords: this.searchForm.query,
        };
        uni.request({
          headers: {
            'Content-Type': 'application/json;charset=UTF-8',
          },
          url: encodeURI(`https://restapi.amap.com/v5/place/text${urlParam(params)}`),
          method: 'GET',
          dataType: 'json',
          success: response => {
            const data = response.data ?? {};
            const pois = data.pois ?? [];
            let result = pois.map(item => {
              const lnglatArr = `${item.location || ''}`.split(',');
              return {
                name: item.name,
                provinceCode: item.pcode,
                provinceName: item.pname,
                areaCode: item.adcode,
                areaName: item.adname,
                cityCode: `${item.adcode}`.substring(0, 4) + '00',
                cityName: item.cityname,
                address: item.adname === item.address && item.name ? item.name : item.address || item.name,
                lng: lnglatArr[0],
                lat: lnglatArr[1],
              };
            });
            resolve({ result: result, totalCount: result.length });
          },
          fail: () => {
            uni.showToast({ title: '没有查询到结果', icon: 'none' });
            resolve({ result: [], totalCount: 0 });
          },
        });
      });
    },
    onSelect(item, append = false) {
      if (append) {
        item = {
          ...item,
          address: (item.provinceName || '') + (item.cityName || '') + (item.areaName || '') + item.address,
        };
      }
      uni.$emit('select-detail', item);
      uni.navigateBack();
    },
    // 地图选点
    selectLocation() {
      wx.chooseLocation({
        latitude: this.lat ? Number(this.lat) : undefined,
        longitude: this.lng ? Number(this.lng) : undefined,
      }).then(res => {
        uni.request({
          url: 'https://restapi.amap.com/v3/geocode/regeo', //逆地理编码接口地址。
          data: {
            key: '1b987a62e5685a58cda5933e1bc66044',
            location: res.longitude + ',' + res.latitude,
          },
          success: response => {
            console.info(response);
            const regeocode = response?.data?.regeocode || {};
            const addressComponent = regeocode?.addressComponent || {};
            const addressInfo = this.getAddress(response?.data);
            let location = {
              lng: res.longitude || '',
              lat: res.latitude || '',
              provinceCode: addressComponent.pcode,
              provinceName: addressComponent.pname,
              areaCode: addressComponent.adcode,
              areaName: addressComponent.district,
              address: addressInfo.address,
            };
            this.onSelect(location, true);
          },
        });
        // let location = {
        //   lng: res.longitude || '',
        //   lat: res.latitude || '',
        //   provinceCode: '',
        //   provinceName: '',
        //   cityCode: '',
        //   cityName: '',
        //   areaCode: '',
        //   areaName: '',
        //   address: res.address || '',
        // };
        // this.onSelect(location);
      });
      // uni.$once('webview-select', location => {
      //   this.onSelect(location);
      // });
      // const url = 'https://zeyi-tms-product.oss-cn-hangzhou.aliyuncs.com/webview/location-wx-freight.html';
      // const params = {
      //   lat: this.lat ? Number(this.lat) : '',
      //   lng: this.lng ? Number(this.lng) : '',
      // };
      // uni.navigateTo({ url: `/pages/common/webview?url=${url}&query=${JSON.stringify(params)}` });
    },
    // 格式化地址
    getAddress(geo) {
      const { regeocode = {} } = geo || {};
      const { addressComponent = {} } = regeocode || {};
      const { province, city, district, township, streetNumber } = addressComponent || {};
      const { street, number } = streetNumber || {};
      const formattedAddress = regeocode.formatted_address || regeocode.formattedAddress || '';
      let amapAddress = formattedAddress.replace(province, '');
      amapAddress = amapAddress.replace(city, '');
      amapAddress = amapAddress.replace(district, '');
      amapAddress = amapAddress.replace(township, '');
      amapAddress = amapAddress.replace(street, '');
      amapAddress = amapAddress.replace(number, '');
      return {
        formattedAddress,
        fullAddress: `${province}${city}${district}${township}${street}${number}`,
        address: `${township}${street}${number}${amapAddress}`,
        amapAddress,
        adcode: addressComponent.adcode,
        township,
      };
    },
  },
};
</script>
<style lang="scss">
.page-search-address {
  &__header {
    padding: 16rpx 32rpx !important;
  }
  .search-history {
    padding: 0 32rpx 32rpx 32rpx;
    font-weight: 500;
    font-size: 32rpx;
  }
  .zui-cell {
    padding: 12rpx 32rpx;
  }
  .zui-cell__label {
    padding-top: 8rpx;
  }
}
</style>