1. 程式人生 > >微信小程式實現搜尋城市的功能實現附效果圖和完整程式碼

微信小程式實現搜尋城市的功能實現附效果圖和完整程式碼

示例圖: 展示所有城市的資料,可實現模糊搜尋。

先上程式碼

<view class="page">
  <view class="closeLocation" bindtap="goBack">
    <image src="/img/icon/closeIcon.png"></image>
  </view>
  <view class="weui-search-bar">
    <view class="weui-search-bar__form">
      <view class="weui-search-bar__box">
        <icon class="weui-icon-search_in-box" type="search" size="16"></icon>
        <input type="text" class="weui-search-bar__input" placeholder="搜尋" value="{{inputVal}}" focus="{{inputShowed}}" bindconfirm='searchHandle' confirm-type="search" bindinput="searchInputCon" />
        <view class="weui-icon-clear" wx:if="{{inputVal.length > 0}}" bindtap="clearInput">
          <icon type="clear" size="16"></icon>
        </view>
      </view>
      <label class="weui-search-bar__label" hidden="{{inputShowed}}" bindtap="showInput">
        <icon class="weui-icon-search" style='margin-top:6rpx' type="search" size="16"></icon>
        <view class="weui-search-bar__text">搜尋</view>
      </label>
    </view>
    <view class="weui-search-bar__cancel-btn" hidden="{{!inputShowed}}" bindtap="hideInput">取消</view>
  </view>


  <view class="currentArea" bindtap="myCity" wx:if="{{currentCity}}">
    當前定位城市:
    <text>{{currentCity}}</text>
  </view>

  <view wx:elif="{{locationLodding && !currentCity}}" class="currentArea reload loadding">
    <button>
      <view>當前定位城市:定位中</view>
      <image src="/img/icon/loading_unicom.gif"></image>
    </button>
  </view>
  <view class="currentArea reload" wx:elif="{{ldata ==false && !currentCity && !locationLodding}}">
    <view>當前定位城市:</view>
    <button open-type="openSetting" catchopensetting="locationhandler">
      <view>獲取當前地理位置</view>
      <image src="/img/icon/reload.png"></image>
    </button>
  </view>
  <view class="currentArea" wx:else="{{!currentCity && locationLodding== false && ldata == false}}">
    當前定位城市:
    <text></text>
  </view>

  <view class="allCity" wx:if="{{!searchResult}}">
    <view class="provice" wx:if="{{BrowsingHistory}}">
      <view class="recently">最近訪問</view>
      <view class="cityList">
        <view wx:for="{{BrowsingHistory}}" data-city="{{item.CityName}}" data-id="{{item.CityId}}" wx:key="item.CityId" bindtap="getCity">{{item.CityName}}</view>
      </view>
    </view>
    <view class="provice" wx:for="{{cityList}}" wx:key="{{item.initial}}">
      <view class="recently">{{item.initial}}</view>
      <view class="cityList">
        <view wx:for="{{item.cityInfo}}" wx:for-item="ct" wx:key="{{ct.id}}" data-city="{{ct.city}}" data-id="{{ct.id}}" bindtap="getCity">{{ct.city}}</view>
      </view>
    </view>
  </view>

  <view class="allCity" wx:if="{{searchResult}}">
    <view class="provice">
      <view class="recently">搜尋結果</view>
      <view class="cityList">
        <view wx:for="{{searchResult}}" wx:for-item="ct" wx:key="{{ct.id}}" data-city="{{ct.city}}" data-id="{{ct.id}}" bindtap="getCity">{{ct.city}}</view>
      </view>
    </view>
  </view>
</view>

js

const app = getApp();
var city = require('../../utils/city.js');
var common = require('../templates/common.js');

Page({
    data: {
        searchshow : true,
        inputShowed: false,
        inputVal: "",
        locationLodding : false
    },
    onLoad:function(options){
        common.init.apply(this, []); //公共元件

        // 從修改地區過來
        if(options.editAccount){
            this.setData({
                editAccount: options.editAccount
            })
        }   
        if (!wx.getStorageSync('cityPosition')) {
          this.getLocation();
        } else {
          this.setData(wx.getStorageSync('cityPosition'))
        }
        //this.getLocation();  //獲取當前位置資訊
        var cityList = city.cityList(); //城市列表
        this.setData({
            cityList : cityList
        })
    },
    // 選擇城市
    getCity:function(e){
        var getCityName = e.currentTarget.dataset.city;
        var getCityId = e.currentTarget.dataset.id;
        var currentCity = {
            CityName :getCityName,
            CityId : getCityId
        }
        var BrowsingHistory = wx.getStorageSync('BrowsingHistory'); 
        // 當沒有瀏覽歷史記錄
        if(!BrowsingHistory){
            BrowsingHistory = [];
            BrowsingHistory.push(currentCity);
        }else{
            var checkRepeat = BrowsingHistory.find(item => {
                return item.CityId ==  getCityId;
            })
             // 當不重複時插入地區
            if(!checkRepeat){
              BrowsingHistory.unshift(currentCity);
            }
            // 當重複時,先刪除再插入
            if (checkRepeat){
              BrowsingHistory = BrowsingHistory.filter((item) => {
                return item.CityId != getCityId
              })
              // console.log('BrowsingHistory',BrowsingHistory)
              BrowsingHistory.unshift(currentCity);
            }
        }

        // 當長度等於9 刪除最後一個
        if (BrowsingHistory && BrowsingHistory.length == 9) {
          BrowsingHistory.pop(1);
        }

        wx.setStorageSync('currentCity',currentCity);
        // 設定一天過期時間
        var timestamp = Date.parse(new Date());
        var currentCity_expiration = timestamp + 60 * 60 * 24 * 1000;
        // var session_expiration = timestamp + 3 * 1000; //測試 10s 過期
        wx.setStorageSync("currentCity_expiration", currentCity_expiration);
        wx.setStorageSync('BrowsingHistory',BrowsingHistory);
        if(this.data.editAccount){
            let pages = getCurrentPages(); //當前頁面
            let prevPage = pages[pages.length - 2]; //上一頁面
            prevPage.setData({ //直接給上移頁面賦值
                editAccount: this.data.editAccount
            });
            this.goBack();
        }else{
            this.goBack();
        }
        
        
    },
    // 當前定位城市
    myCity:function(){
        currentCity = this.data.currentCity;
        var currentCity = {
            CityName :currentCity,
            CityId: this.data.CityId
        }
        wx.setStorageSync('currentCity',currentCity);
        // 設定一天過期時間
        var timestamp = Date.parse(new Date());
        var currentCity_expiration = timestamp + 60 * 60 * 24 * 1000;
        wx.setStorageSync("currentCity_expiration", currentCity_expiration);
        this.goBack();
    },
    searchInputShow:function(){
        this.setData({
            searchshow : false,
            searchContext : ''
        })  
    },
    searchInputHidden:function(){
        this.setData({
            searchshow : true,
            searchContext : ''
        })  
    },
    goBack:function(){
        wx.navigateBack({
            delta: 1
        })
    },
    onShow:function(){
        var BrowsingHistory = wx.getStorageSync('BrowsingHistory');
        this.setData({
            BrowsingHistory : BrowsingHistory
        })
    },
    // 搜尋 及搜尋結果
    searchHandle:function(e){
        var searchContext = this.data.searchContext;
        var cityList = this.data.cityList;
        var searchArr = [];
        cityList.forEach(item =>{
            var citylist = item.cityInfo;
            citylist.forEach(value => {
                if(value.city.indexOf(searchContext) >= 0){
                    searchArr.push(value);
                }
            })
        })
        if(searchArr){
            this.setData({
                searchResult : searchArr
            })
        }
    },
    // 文字輸入 事件
    searchInputCon:function(e){
        let keywords = e.detail.value;
        this.setData({
            searchContext : keywords
        })
    },
    showInput: function () {
      this.setData({
        inputShowed: true
      });
    },
    hideInput: function () {
      this.setData({
        inputVal: "",
        inputShowed: false
      });
    },
    clearInput: function () {
      this.setData({
        inputVal: ""
      });
    }
   
});

css


.closeLocation{
    height: 85rpx;
    position: relative;
}

.closeLocation image{
    width: 22rpx;
    height: 22rpx;
    position: absolute;
    right: 30rpx;
    top: 30rpx;
}
.search{
    height: 90rpx;
    background: #fff;
    width: 100%;
    position: relative;
}

.search .searchLeftText{
    width: 85rpx;
    height: 90rpx;
    position: relative;
    left: 0;top: 0;
    position: absolute;
    display: flex;
    
}
.search .searchLeftText image{
    width: 35rpx;
    height: 34rpx;
    margin-left: 35rpx;
    margin-top: 30rpx;
}
.search .undo{
    width: 100rpx;
    line-height: 90rpx;
    position: absolute;
    right: 0;
    top: 0;
    color: #55b837;
    font-size: 32rpx;
}

.search .search_input{
    height: 90rpx;
    line-height: 90rpx;
    width: 80%;
    box-sizing: border-box;
    padding-left: 85rpx;
    padding-right: 110rpx;
    background: none
}
.searchTextP{
    width: 100%;
    height: 90rpx;
}
.search .searchText{
    position: absolute;
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size:32rpx;
    color: #999;
    flex-direction: row;
    top: 0;
    left: 0;
    pointer-events:none;
}

.search .searchText image{
    width: 35rpx;
    height: 34rpx;
    margin-right: 15rpx;
}


.currentArea{
    font-size: 32rpx;
    color: #999;
    height: 90rpx;
    line-height: 90rpx;
    background: #fff;
    box-sizing: border-box;
    padding: 0 30rpx;
    margin-top: 40rpx;
}
.currentArea text{
    color: #55b837;
}

.allCity{
    height: auto;
    font-size: 28rpx;
    color: #000;
}

.allCity .provice{
    height: auto;
}

.allCity .provice .recently{
    height: 90rpx;
    line-height: 90rpx;
    color: #999999;
    padding-left: 30rpx;
}
.allCity .provice  .cityList{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}
.allCity .provice  .cityList view{
    background: #fff;
    height: 88rpx;
    border-right: 1px solid #f4f4f4;
    border-bottom: 1px solid #f4f4f4;
    width: 25%;
    overflow: hidden;
    box-sizing: border-box;
    text-align: center;
    line-height: 88rpx;
}


  .reload{
      display: flex;

  }
  
  .reload button{
    display: flex;
    padding: 0;
    margin: 0;
    background: none;
    justify-content: center;
    align-items: center;
    height: 90rpx;
    color: #999
  }
  
  .reload button image{
    width: 30rpx;
    height: 30rpx;
    margin-left: 15rpx;
  }


    .loadding button image{
    width: 25rpx;
    height: 25rpx;
  }
  /* 搜尋樣式 */
  .weui-search-bar{
    background: #fff
  }
  .weui-search-bar__form{
    border:none
  }
  .weui-search-bar{
    border:none
  }
  .weui-search-bar__input {
    font-size: 30rpx;
  }
  .weui-search-bar__text{
    font-size: 30rpx
  }

引用的   ../../utils/city.js

檔案下載: 點選下載