功能介绍

主要就是获取到用户当前位置的经纬度,调用后端api接口计算出距离最近的地铁站,并展示对应商家。用户可手动切换或者搜索地铁站点进行切换,切换后展示对应地铁站附近的商家
这里手动切换地铁站是直接用的picker组件对地铁线路以及地铁站点进行了一个对应,滑动线路动态更改站点列表

地铁站切换页面及逻辑代码(内有注释)

搜索页面html
<template><view><view class="box"><view class="search"><image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/mini-wx/images/homeIndex/search.png" mode=""></image><view class="inputCon"><input type="search"placeholder="搜索地铁站" v-model="searchValue"confirm-type="search"@confirm="search()"></view></view><view class="list-box" v-if="showList"><view class="item active" v-for="(item, index) in stationList" :key="index" @click="onSelectStation(item)" v-html="item.subway_name"></view></view><view v-if="isContent"><view style="margin-top: 20rpx;" class="pickers"><picker:value="multiIndex"@change="onChange"@columnchange="onColumnChange"mode="multiSelector":range="multiArray"range-key="label"><text>定位</text><view style="max-width:max-content;height: 46rpx;border-radius: 12rpx 12rpx 12rpx 12rpx;border: 2rpx solid rgba(0,139,124,0.1);padding: 10rpx;"><image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202304231132081261-Group%2034001.png" mode=""></image><text style="font-size: 28rpx;font-weight: 400;color: #008B7C;line-height: 33rpx;">{{station}}</text></view><!-- <view class="picker-value">{{ line }} - {{ station }}</view> --></picker></view><text class="search_txt">历史记录:</text><view class="search_history"><view v-for="(item, index) in searchHistory" :key="index" @tap="onSearchHistoryTap(item)" class="search_item" @click="toIndex()"><text>{{ item }}</text></view></view></view></view></view>
</template><script>
export default {data() {return {sub: "",multiArray: [],multiIndex: [0, 0],line: "", station: "",lines: [], stations: [] ,City:[],searchValue:'',searchHistory:[],stationList: [], // 下拉列表数据showList: false ,// 判断下拉列表是否显示timer: null ,// 定时器开关isContent:true,//出现下拉列表时隐藏页面内容zhanshi:""};
},watch: {searchValue: function(val) {if (this.timer) clearTimeout(this.timer); // 清除上个定时器this.timer = setTimeout(() => {if (val) {this.search(); // 发起搜索请求this.showList = true; // 显示下拉菜单this.isContent = false} else {this.stationList = []//清空上一次的下拉展示记录this.showList = false; // 隐藏下拉菜单this.isContent = true}}, 300); // 设置定时器,延迟 300 毫秒后开始搜索}},// 在组件挂载后获取 localcityNm 缓存值,并请求地铁线路列表mounted() {this.sub = uni.getStorageSync("localcityNm");this.getSubwayLinesList();},// 在页面加载时获取历史搜索记录和定位标志,将定位标志设为 falseonLoad(){this.searchHistory = uni.getStorageSync("searchHistory")console.log(this.searchHistory+'11')const isDinwei = uni.getStorageSync('isDinwei')uni.setStorageSync('isDinwei',false)},methods: {// 跳转到首页toIndex(){uni.navigateBack(1)},// 点击历史搜索记录项触发的事件onSearchHistoryTap(item) {console.log(item,'我是点击的某一项')// 将点击的历史搜索记录项值赋给搜索框this.searchValue = item;// 执行搜索方法进行搜索,并将定位标志设置为 truethis.onSelectStation();uni.setStorageSync('localcityNm', this.searchValue); const isDinwei = uni.getStorageSync('isDinwei')uni.setStorageSync('isDinwei',true)},
// 选择了某个地铁站时,更新当前页面显示的地铁站名称和存储的相关信息
onSelectStation(station) {this.station = station.subway_name; // 更新当前显示的地铁站名称uni.setStorageSync('localcityNm', station.subway_name); // 存储所选地铁站名称const currentStationObj = JSON.parse(JSON.stringify(station));const { subway_latitude, subway_longitude } = currentStationObj;const newCityData = { lat: subway_latitude, lng: subway_longitude };uni.setStorageSync('City', newCityData); // 存储所选地铁站的经纬度信息const history = uni.getStorageSync('searchHistory') || [];const newStationName = station.subway_name.replace(/<[^>]*>/g, ''); // 去除所有 HTML 标签if (!history.includes(newStationName)) {//判断搜索历史记录中是否有值,无值执行以下代码this.searchHistory = history;this.searchHistory.unshift(newStationName);//在历史记录数组中首位添加搜索内容if (this.searchHistory.length > 10) { // 保留10个值this.searchHistory.pop()//当大于十个值时删掉数组末尾的值}uni.setStorageSync('searchHistory', this.searchHistory); // 存储搜索历史记录const isDinwei = uni.getStorageSync('isDinwei');uni.setStorageSync('isDinwei', true); // 设置已定位标志为true,避免再次进行定位操作// history.push(newStationName);uni.setStorageSync('localcityNm', newStationName);this.searchValue = ''this.toIndex(); // 跳转到首页this.searchHistory = history;uni.setStorageSync('searchHistory', this.searchHistory); // 存储搜索历史记录}else{//有搜索记录,删除之前的旧记录,将新搜索值重新push到数组首位console.log('11111111111111111111111')this.searchHistory = history;let i = this.searchHistory.indexOf(newStationName);this.searchHistory.splice(i, 1);this.searchHistory.unshift(newStationName);if (this.searchHistory.length > 10) { // 保留10个值this.searchHistory.pop()}uni.setStorageSync('searchHistory', this.searchHistory); // 存储搜索历史记录// 请勿重复搜索this.toIndex(); // 跳转到首页const isDinwei = uni.getStorageSync('isDinwei');uni.setStorageSync('isDinwei', true); // 设置已定位标志为true,避免再次进行定位操作uni.setStorageSync('localcityNm', newStationName);uni.setStorageSync('isDinwei', true); // 设置已定位标志为true,避免再次进行定位操作this.searchValue = ''this.isContent = truethis.showList = false; // 关闭下拉列表}
},
async search() {try {const res = await this.$request.post("subway/getSubwayStation", {city_id: uni.getStorageSync("localcityId"),subway_name: this.searchValue.trim()});const data = res.data;// console.log(data,'数据格式')const station = data[0];if (station) {this.showList = true;this.isContent = false//一定要是大于等于,不然匹配规则就有问题,匹配到单个不会显示if (data.length >= 1) {// 如果匹配到多个地铁站,则将所有信息保存到stationList中,并显示下拉列表this.stationList = data;this.stationList = data.map(item => {const reg = new RegExp(this.searchValue, 'g'); // 使用正则表达式进行全局匹配const newName = item.subway_name.replace(reg, `<span style="color:#008B7C">${this.searchValue}</span>`); // 将匹配到的部分用<span>标签包裹,并修改文字颜色return { ...item, subway_name: newName };});console.log(this.stationList,'我是处理好的数据')}else {// 如果只匹配到一个地铁站,则直接定位到该地铁站this.station = station.subway_name;uni.setStorageSync('localcityNm', station.subway_name);const currentStationObj = JSON.parse(JSON.stringify(station));const { subway_latitude, subway_longitude } = currentStationObj;const newCityData = { lat: subway_latitude, lng: subway_longitude };uni.setStorageSync('City', newCityData);const history = uni.getStorageSync('searchHistory') || [];const newStationName = station.subway_name.replace(/<[^>]*>/g, '');//      if (!history.includes(newStationName)) {//        const isDinwei = uni.getStorageSync('isDinwei')//        uni.setStorageSync('isDinwei',true)//  this.toIndex()//        history.push(newStationName);//  uni.setStorageSync('localcityNm', newStationName);//        this.searchHistory=history;//        uni.setStorageSync('searchHistory', this.searchHistory);//      }}} else {this.showList = false;this.isContent = trueuni.showToast({title: '未找到该地铁站点',icon: 'none'});}} catch (error) {console.log(error);}
},// 请求地铁线路列表async getSubwayLinesList() {try {const res = await this.$request.post("subway/getSubwayLinesList", {city_id: uni.getStorageSync("localcityId")});const data = res.data;const lines = data;// 格式化地铁线路名称列表数据,并存储到当前组件实例的 lines 属性中this.lines = lines.map(item => ({label: item.lines,value: item.id}));this.line = lines[0].lines; // 初始化当前选中的地铁线路名this.getSubwayStations(lines[0].id); // 获取第一个地铁线路的站点列表} catch (error) {console.log(error);}},// 请求指定地铁线路的站点列表async getSubwayStations(lineId) {try {// 调用后端API获取数据const res = await this.$request.post("subway/getSubwayStationList", {lines_id: lineId});const data = res.data;// 将数据存储到stations变量中const stations = data;// 将每个站点的名称和id转换为label和value,存储到this.stations数组中this.stations = stations.map(item => ({label: item.subway_name,value: item.id})); // 存储地铁站点名称列表到 data 中// 将data中的所有数据存储到City变量中const City = datathis.City = City// 如果用户没有选择站点,则默认选择距离用户最近的站点if (!this.station) {// 如果用户还没有选择站点,则将其设为本地存储中的城市名localcityNmthis.station = uni.getStorageSync('localcityNm')}// 设置选中的站点为当前地铁线路的第一个站点this.multiIndex = [this.multiIndex[0], 0];// 更新多列选择器的数据源this.multiArray = [this.lines, this.stations];} catch (error) {console.log(error);}},// 线路选择器值改变事件onChange(e) {const that = this;// 获取picker选择器中的索引值const multiIndex = e.detail.value;// 获取当前选中的地铁线路的名称const lineName = that.lines[multiIndex[0]].label;// 获取当前选中的地铁站点的名称const stationName = that.stations[multiIndex[1]].label;// 将当前选中的地铁站点的名称存储到本地存储中,用于下次默认选择uni.setStorageSync('localcityNm', stationName);// 根据当前选中的地铁站点名称获取该站点的经纬度信息,并存储到localStorage中const currentStation = that.City.find(item => item.subway_name === stationName);if (currentStation) {const currentStationObj = JSON.parse(JSON.stringify(currentStation));const { subway_latitude, subway_longitude } = currentStationObj;const newObj ={lat:subway_latitude, lng:subway_longitude}uni.setStorageSync('City', newObj);}// 更新选中的地铁线路、站点名称that.line = lineName;that.station = stationName;// 重新获取并更新站点列表数据that.getSubwayStations(that.lines.find(item => item.label === lineName).value);// 更新多列选择器的数据源和选中的索引值that.multiArray = [that.lines, that.stations];that.multiIndex = multiIndex;// 跳转到首页this.toIndex()// 设置isDinwei为true,表示已经定位const isDinwei = uni.getStorageSync('isDinwei')uni.setStorageSync('isDinwei',true)},// 列变化事件onColumnChange(e) {let that = this// 获取列和行的索引值const columnIndex = e.detail.column;const rowIndex = e.detail.value;// 如果列变化的是地铁线路列,则重新获取站点列表并更新右侧 picker 列表的数据源if (columnIndex === 0) {const lineId = that.lines[rowIndex].value;that.getSubwayStations(lineId);}}}
};
</script><style lang="less" scoped>.box{padding-left:24rpx ;padding-right: 20rpx;.search_history{width: 100%;display: flex;flex-wrap: wrap;.search_item{width: max-content;height: 56rpx;border-radius: 12rpx 12rpx 12rpx 12rpx;opacity: 1;border: 2rpx solid rgba(0,0,0,0.1);margin-right:20rpx ;padding-left: 8rpx;padding-right: 8rpx;margin-bottom: 20rpx;text{font-size: 28rpx;font-weight: 400;line-height: 56rpx;text-align: center;color: #666666;}}}.picker {font-size: 16px;color: #000;line-height: 40px;text-align: center;border: 1px solid #ccc;border-radius: 4px;padding: 0 10px;margin-top: 20px;}.pickers{text{font-size: 24rpx;font-weight: 400;color: #666666;line-height: 68rpx;}image{width: 24rpx;height: 28rpx;vertical-align: middle;margin-right: 6rpx;}}.search_txt{font-size: 24rpx;font-weight: 400;color: #666666;line-height: 98rpx;}.search {/* // flex: 1; */height: 64rpx;position: relative;background-color: #FFFFFF;// bottom: -0rpx;border-radius: 300rpx;image {position: absolute;width: 22rpx;height: 18rpx;top: 22rpx;left: 22rpx;z-index: 999;}input {width: 90%;height: 62rpx;position: absolute;left: 0;top: 0;margin: 0 auto;// border: none;background-color: #FFFFFF;border: 1rpx solid rgba(0,0,0,0.2);border-radius: 300rpx;padding: 0;margin: 0;padding-left: 60rpx;color: #666666;font-size: 24rpx;}}.dinwei{font-size: 24rpx;font-weight: 400;color: #666666;line-height: 28rpx;}}.list-box{padding: 22rpx;.item{width: 100%;padding-bottom: 20rpx;padding-top: 20rpx;border-bottom: 1rpx solid rgba(0,0,0,0.02);color: #666666 ;font-size: 30rpx;}.item:hover .active{color: #000;}}
</style>

首页渲染对应商品列表

<template><view class="page"><view class="ebkContainer"><!-- 头部 --><view class="headerTop" :style="'padding-top: '+ capsuleTop + 'px;'" id="headerTop" @click="onNavigationBarTap"><view style="margin-right: 134rpx;"><image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202305161006489029-%E6%9C%AA%E6%A0%87%E9%A2%98-1%201%403x.png" mode="" style="width: 160rpx; height: 84rpx;"></image></view><text style="font-size: 36rpx;color: #333333;margin-top: 12rpx;font-weight: bold;">天天特价</text></view><view class="wrapper" :style="'padding-top: '+ Number(capsuleTop + 43) + 'px;'"><!-- 轮播图 --><view class="swiperBanner" v-if="barnnerList.length > 0"><view class="page-section swiper"><view class="page-section-spacing"><swiper class="swiper" :indicator-dots="true" :autoplay="true" :interval="5000" :duration="500"indicator-color="rgba(255, 255, 255, .5)" indicator-active-color="rgba(255, 255, 255)"><swiper-item v-for="(item, i) in barnnerList" :key="i"><view class="linkHref" @click="bannerLinkHref(item.wxmp_link)"><image :src="item.image" mode="" v-if="item.image"></image></view></swiper-item></swiper></view></view><view class="search" @click="backSearch" :style="'margin-right: '+ capsuleWidth + 'px;'"><image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202305160606186019-Group%2034002%403x.png" mode=""></image><input type="text" placeholder="搜索好物" @focus="search" /></view></view><view class="borderRadius"><!-- tab切换栏 --><view class="tabList" id="tabList":style="isTop == true ? 'position:fixed;background:#FFFFFF;z-index:9999;top:'+headerTop+'px' : ''"><view class="list clearfix"><view class="listCon" @click="tabChange(item.status, i)" v-for="(item, i) in tabList" :key="i">{{item.name}}<image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202304201038061510-Group%20523%403x.png" mode=""></image></view></view><view class="auto"><!-- 判断当前点击的是哪一个,给加高亮,并判断当前是否可点(数据未加载出来则切换不了) --><view class="listCon1" v-for="(item, i) in localsortWayList" :key="i" :class="{ 'active':i==localsortWayActiveIndex && !isActive}" @click.stop="selectlocalErcate(item.status, i)">{{item.name}}<view style="width: 6rpx;height: 6rpx;background: #008B7C;border-radius: 100%;margin-top: 6rpx;opacity: 0.8;margin: 6rpx auto;" v-if="i==localsortWayActiveIndex&&!isActive"></view></view></view><view class="filter" @click="filterSplist()"><!-- 定位 --><view   @click="location"  class="place"><view class="fl"><image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202304201119076630-Group%2033995%403x.png" mode=""></image></view><view class="fl"><text text-overflow="ellipsis" class="placeName" style="margin-left: 2rpx;">{{province}}</text></view><view style="clear:both;"></view></view></view></view><view :style="isTop == true ? 'height:'+tabList_height+'px': ''"></view><view class="goodLists" id="dataListWarp"><view class="list bargain" v-if="tabStatus == 2"><view class="listCon" v-for="(item, i) in bargainList" :key="i"><view class="linkHref" @click="bargainLinkHref(item.id)"><view class="spImg" :style="{backgroundImage:`url(${item.picture})`}"></view><view class="spCon"><view class="spName">{{item.goods_name}}</view><view class="distance fr jl" v-if="item.distance<1000">{{item.distance}}m</view><view class="distance fr jl" v-else="item.distance>1000">{{item.distance/1000}}km</view><view style="clear:both;"></view><view class="spDetail"><view class="nowPrice"><text style="font-size: 24rpx;color: #F53C13;font-weight: 500;">¥</text>{{ item.origin_price | bargainPriceFormat(item.already_grade_amount) }}</view><view class="oldPrice">¥{{item.origin_price / 100}}</view><view class="sendNum">电商参考价{{item.refer_price / 100}}</view></view><view class="buyBtn clearfix"><view class="barginBtn" v-if="item.is_bargain == 0 && item.finallyPrice != item.least_price / 100" @click.stop="bargainGood(i, item.id)"><view class="discount">砍价</view><view class="mustPrice">最低砍至{{item.least_price / 100}}元</view></view><view class="barginBtn active" v-else-if="item.is_bargain == 1 && item.finallyPrice != item.least_price / 100" @click.stop="inviteFriend(item.id)"><button open-type="share" v-bind:data-bargainGood="item" :data="item.id" class="share"><view class="discount">邀请帮砍 <image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/mini-wx/images/bargain/share.png"mode=""></image></view><view class="mustPrice">最低砍至{{item.least_price / 100}}元</view></button></view><view class="barginBtn bestPrice" v-else-if="item.finallyPrice == item.least_price / 100"><view class="discount">已至底价</view><view class="mustPrice">最低砍至{{item.least_price / 100}}元</view></view><view class="onceBuy" @click.stop="onceBuy(item.id, item.is_bargain, item.finallyPrice == item.least_price / 100, i)"><view class="buy">立即购买</view><view class="savePrice">(已砍{{item.already_grade_amount/100}}元)</view></view></view></view></view></view></view><view class="list localLife" v-if="tabStatus == 1"><view class="listCon" v-for="(item, i) in localList" :key="i" @click="toDetail(item)"><!-- <navigator class="linkHref" :url="'/pages/localLife/localLifespdetail?goodsId=' + item.store_goods_id"> --><view class="linkHref"><view class="spBg"><view class="shopping">抢购中</view><view class="spImg" :style="{backgroundImage:`url(${pictruesFormtata(item.picture)})`}"></view></view><view class="spDetail"><view class="spName">{{item.goods_name}}</view><view class="spOrder clearfix"><view class="orderNum fl">销量{{item.order_total}}</view><view class="distance fr" v-if="item.distance<1000">{{item.distance}}m</view><view class="distance fr" v-else="item.distance>1000">{{item.distance/1000}}km</view></view><view class="spPrice"><view class="nowPrice" ><text style="font-size: 24rpx;color: #F53C13;">¥</text>{{item.vip_price / 100}}</text></view><view class="oldPrice">门市价¥{{item.origin_price / 100}}</view><!-- <view class="shopTip" :style="{backgroundImage: `url(${indexBackgroundImage})`}"></view> --><view style="width: 116rpx;height: 52rpx;background: linear-gradient(135deg, #F48218 0%, #F53C13 100%);border-radius: 200rpx 200rpx 200rpx 200rpx;font-size: 24rpx;font-weight: bold;color: #FFFFFF;line-height: 52rpx;text-align: center;">马上抢</view></view></view></view><!-- </navigator> --></view></view><view class="noData" v-if="tabStatus == 2"><view class="noMore" v-if="isEndflag && bargainList.length == 0">暂无数据</view><view class="noMore" v-if="isEndflag && bargainList.length > 0">没有更多数据了</view></view><view class="noData" v-else><view class="noMore" v-if="isEndflag && localList.length == 0">暂无数据</view><view class="noMore" v-if="isEndflag && localList.length > 0">没有更多数据了</view><view class="loading" v-if="!isEndflag&& localList.length > 0">{{loadingText}}</view></view><Loading v-if="isShow"></Loading></view>            </view></view></view></view></template><script>var _self, page = 1;let app = getApp();import Loading from "../loading/loading.vue"//import indexBackgroundImage from "@https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/mini-wx/images/homeIndex/pricebg.png"export default {components:{Loading},data() {return {isAcitive:false,//控制二级导航是否禁止切换的按钮(数据未加载出来则不能切换)loadingText:"",//分页上拉加载文本isShow:false,//控制自定义动画组件的开关headerTop:50,province:'',indexBackgroundImage:'https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/mini-wx/images/homeIndex/pricebg.png', //砍价背景图capsuleWidth: '', //胶囊宽度capsuleTop: '', //胶囊居顶barnnerList: [// {//  image:"https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202305160206168459-banner1.png"// },// {//    image:"https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202305160206289053-banner2.png"// },// {//    image:"https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202305160206458070-banner3.png"// }], //广告列表tabList: [{name: '天天特价',status: 1},],tabActiveIndex: 0,bargainList: [], //切换栏商品列表localList: [], //切换栏本地生活列表isTop: false, //默认切换栏不知顶tabBarTop: 0, //默认tab栏高度tabStatus: 1, //切换栏状态page: 1,pageSize: 10,isEndflag: false,uid: '',sortWayActiveIndex: 0,sortWayStatus: 0,couponisEndflag: false,bargainCategoryId: '', //砍价分类idbargainType: '', //砍价类型localCategoryId: '', //本地生活分类idlocalType: 1, //本地生活类型 1推荐 2距离 3销量 4价格popupFlag: false,bargainuseTypeList: [{'id':0,'name':'全部'}],bargainuseTypeActiveIndex: 0,bargainsortWayActiveIndex: 0,localuseTypeList: [{'id':0,'name':'全部'}],localuseTypeActiveIndex: 0,localsortWayList: [{name: '附近', status: 2},{name: '推荐', status: 1},                {name: '销量', status: 3},{name: '价格', status: 4}],localsortWayActiveIndex: 0,paramsUid: '',token:null,index:0,dinwei:0,tabList_height:0,isBackTop: true, // 初始化为trueisDinwen:false,lastTapTime: null,//用于记录上一次点击的时间戳screenHeight: 0,//高度设置为0isFirstLoad:false,//判断是否首次加载数据}},async onPullDownRefresh(){//下拉刷新app.checkLocationAuth()//判断用户是否授权定位//强制删除后重新赋值this.isFirstLoad = false;this.localList = [];this.page = 1this.localsortWayActiveIndex = 1//下拉刷新时设置二级菜单的默认状态this.localType = 1//渲染对应类型的数据 1为推荐   2为附近// uni.removeStorageSync('localcityNm')// uni.removeStorageSync('City')try{// this.province = app.globalData.fujin_sub// uni.setStorageSync('localcityNm',this.province)//     let City = await app.getLocation()//   console.log(City,'wadwadhaiuwdhawudhuahwduhaw')//     uni.setStorageSync('City',City)//     this.localList = [];//     this.tabChange(this.tabStatus,this.tabActiveIndex);uni.setStorageSync('isDinwei',true)this.isShow = true}catch (error) {console.error(error)}// })// this.getlocalList()// 强制删除后重新获取数据if(!this.localsortWayList.status === 2){this.localsortWayActiveIndex = 0}// if(!this.localsortWayList.status === 1){//  this.localsortWayActiveIndex = 1// }this.localList = [];this.couponpage = 1;this.couponisEndflag = falsethis.couponList = []this.tabChange(this.tabStatus,this.tabActiveIndex);uni.stopPullDownRefresh();},filters: {//计算打折折扣priceDiscount (newPrice, oldPrice) {let disNum = Math.round( newPrice / oldPrice * 100) / 10;if (!disNum) {disNum = 0}//    console.log(disNum,'disNum')return disNum}},onLaunch() {this.isDinwei = trueuni.setStorageSync('isDinwei',this.isDinwei)// console.log(uni.getStorageSync('isDinwei'),'wdawadaw')console.log('我是onLaunch')this.province = uni.getStorageSync('localcityNm')},onReady() {console.log('我是onReady')this.province = uni.getStorageSync('localcityNm')//  app.getLocation();let capsuleData = uni.getMenuButtonBoundingClientRect();this.capsuleWidth = Number(capsuleData.width) + 19this.capsuleTop = Number(capsuleData.top)},onUnload() {},onLoad(option) {this.localsortWayActiveIndex = 1//下拉刷新时设置二级菜单的默认状态this.localType = 1//渲染对应类型的数据 1为推荐   2为附近// if (this.isFirstLoad) {this.getlocalList();//  this.isFirstLoad = false//    }//获取屏幕高度const systemInfo = uni.getSystemInfoSync();this.screenHeight = systemInfo.windowHeight;this.isDinwei = trueuni.setStorageSync('isDinwei',this.isDinwei)// this.getSubWay()console.log('我是onLoad')this.province = uni.getStorageSync('localcityNm');this.bargainType =2;this.index=this.index+1;if(option.uid){this.paramsUid=option.uid;}if(this.index==1){     // this.getBannerCateList()  //大牌好券分类this.getlocalCateList() //本地生活分类// this.getlocalList()}if(option.type){this.tabChange(1,0);} let query = uni.createSelectorQuery().in(this);let that = this;setTimeout(function(){       query.select('#headerTop').boundingClientRect(data => {//头部搜索that.headerTop=data.height-10;}).exec();query.select('#tabList').boundingClientRect(data => { //导航栏that.tabList_height=data.height;that.dinwei=data.height+that.headerTop;}).exec();},1000);},onShow() {this.localsortWayActiveIndex = 1//下拉刷新时设置二级菜单的默认状态this.localType = 1//渲染对应类型的数据 1为推荐   2为附近// if (!this.isFirstLoad) {//         this.localList = [];app.get_token().then( res => {this.token = uni.getStorageSync('token').token})// this.getlocalList();//     }this.province = uni.getStorageSync('localcityNm')console.log(this.province,'onshow中原本存入的这个变量')// if(uni.getStorageSync('localcityNm')==''){//   uni.setStorageSync('localcityNm',this.province)// }setTimeout(()=>{console.log(this.province,'wadadawdada')console.log(app.globalData.fujin_sub,'234567876453')},1000)console.log('我是onShow')this.province = uni.getStorageSync('localcityNm')this.getBannerList() //轮播图// this.$forceUpdate()// this.getlocalList()this.token = uni.getStorageSync('token').token        //判断是否手动选择更改了地铁站,如果不是则不需要重新加载数据if(uni.getStorageSync('isDinwei')!=false){// this.getlocalList()//否则就得根据新的定位经纬度去请求新的数据this.province = uni.getStorageSync('localcityNm')this.isShow = true// var City = app.globalData.jwd// uni.setStorageSync('City',City)if (!this.token) {app.get_token().then( res => {this.token = uni.getStorageSync('token').tokenthis.tabChange(this.tabStatus, this.tabActiveIndex); })}else {app.get_token().then( res => {this.token = uni.getStorageSync('token').tokenthis.tabChange(this.tabStatus, this.tabActiveIndex); })}}this.couponpage = 1;this.couponisEndflag = false// this.getCouponList() //大牌好券列表},// 上拉加载onReachBottom() {if (this.isEndflag) {this.loadingText = '';} else {this.page++this.loadingText = '加载中...';if (this.tabStatus == 1) {this.getlocalList()} else {}}},onPageScroll: function(e) {const query = uni.createSelectorQuery().in(this);query.select('#dataListWarp').boundingClientRect(data => {if (data.top < this.dinwei) {this.isTop = true} else {this.isTop = false}}).exec();},//点击tabbar栏切换onTabItemTap(item) {//新旧值进行对比this.province = uni.getStorageSync('localcityNm')// console.log(this.province,'刚切过来的')if (item.index === 0) {//切换tabbar后新旧定位如果一样则不需要更新数据if(uni.getStorageSync('localcityNm')==this.province){uni.setStorageSync('isDinwei',false)// 否则更新数据}else{uni.setStorageSync('isDinwe',true)}// 执行首页相关操作console.log('切换到首页')// uni.setStorageSync('isDinwei',false)}},mounted() {// this.getSubWay()// this.get_City()// console.log('我是mounted')// this.province = uni.getStorageSync('localcityNm')// console.log(this.province)uni.setStorageSync('localcityNm',this.province)const query = uni.createSelectorQuery().in(this);query.select('#tabList').boundingClientRect(data => {//console.log('1111')// console.log(data.top)this.tabBarTop = data.top}).exec();},methods: {toDetail(item){uni.navigateTo({url:'/pages/localLife/localLifespdetail?goodsId=' + item.store_goods_id})},//在导航栏上添加一个@click事件的监听函数,判断两次点击的时间间隔是否小于300ms,如果是,则认为是双击事件,执行页面滚动到顶部的操作。onNavigationBarTap(event){const currentTimeStamp = event.timeStamp;const lastTimeStamp = this.lastTapTime || 0;const timeDiff = currentTimeStamp - lastTimeStamp;if (timeDiff < 300) { // 双击事件uni.pageScrollTo({scrollTop: 0,duration: 300});}this.lastTapTime = currentTimeStamp;},location(){//点击进入自选位置页面时候设为true,进入了自选位置页面如果没有更改地址,则在刚进入页面触发onload函数就已经将值更改为false了,在选择完地铁站之后在将值更改为true,返回首页后第一次会重新计算经纬度加载数据,之后不会// this.isDinwen = true// uni.setStorageSync('isDinwei',this.isDinwen)let that = this;uni.navigateTo({url:'/pages/map/map'})},moveHandle () {},// 无用,防止报错},// 轮播图async getBannerList() {const res = await this.$request.post("ad/getAdList", {// 小程序首页地铁美食轮播图name: "小程序首页地铁美食轮播图"}, {native: true})var data = res.dataif (data.status == 'ok') {this.barnnerList = data.data}},// 轮播图跳转bannerLinkHref(hrefUrl) {//console.log(hrefUrl)uni.navigateTo({url: hrefUrl})},// 本地生活列表第一张图片pictruesFormtata(pictrues) {var pictruesArr = (pictrues || "").split(',')var imgSrc;if (pictruesArr.length > 0) {imgSrc = pictruesArr[0]} else {imgSrc = ''}return imgSrc},async get_City(){//获取定位if(!uni.getStorageSync('localcityNm')){ //判断当前是否自选位置app.getLocation();this.City=   uni.getStorageSync('City');}var localcityNm=uni.getStorageSync('localcityNm');// console.log(localcityNm+'222')if(localcityNm){this.province=localcityNm;// console.log(this.province+'111')}},// 获取切换栏本地生活列表async getlocalList() {let  City=  uni.getStorageSync('City');if(!City){app.getLocation().then(res=>{this.getlist()});}else{this.getlist()}},async getlist(){if (this.isFirstLoad) {return;}this.isFirstLoad = true;//拿到计算完成之后最新的经纬度,不是传入当前位置经纬度var City = uni.getStorageSync('City')// 监听事件console.log('City3333获取附近商家列表',City)if(!uni.getStorageSync('localcityId')){var city_id=110100}else{var city_id=uni.getStorageSync('localcityId') }this.token = uni.getStorageSync('token').token//在更新商品列表之前先拿到地铁站名称var localcityNm=   uni.getStorageSync('localcityNm');if(localcityNm){this.province=localcityNm;}const res = await this.$request.post('localLive/getStoreGoodsList', {store_category_id: this.localCategoryId,type: this.localType,city_id    : city_id,latitude: City.lat,longitude: City.lng,page: this.page,page_size: this.pageSize}, {native: true})if (this.isEndflag) {this.loadingText = '';}if (res.data.status == 'ok') {this.isShow = truevar data = res.data.dataif (data.length == 0) {this.isEndflag = true} else {data.forEach((item, index) => {if (item.picture) {var pictruesArr = (item.picture || "").split(',')var imgSrc;if (pictruesArr.length > 0) {imgSrc = pictruesArr[0]} else {imgSrc = ''}item.picture = imgSrc}})this.localList = this.localList.concat(data)this.isActive = false//当数据赋值加载完毕后关闭禁止点击二级导航的限制,为了解决数据还未加载完成导航切换后导致的数据不对应问题this.isFirstLoad = false;// uni.setStorageSync('isDinwei',false)this.province = uni.getStorageSync('localcityNm')this.isShow = falseconsole.log(this.localList,'这是上拉加载更多数据')}} else {this.isEndflag = true}},// 切换栏tabChange(statusIndex, index) {// console.log(statusIndex,index)this.localList = [];this.page = 1this.tabStatus = statusIndexthis.tabActiveIndex = indexthis.isEndflag = falseif (statusIndex == 1) {this.isShow = truethis.getlocalList()} else {}},// 筛选框filterSplist() {this.popupFlag = !this.popupFlag},backSearch () {uni.setStorageSync("isDinwei",false)uni.navigateTo({url: '/pages/brandCoupon/searchList?type=1'})},// 获取本地生活分类async getlocalCateList () {const res = await this.$request.post('localLive/getStoreCategoryList', {}, {native: true})if (res.data.status == 'ok') {this.localuseTypeList= this.localuseTypeList.concat(res.data.data)// this.localuseTypeList = res.data.data}},// 本地生活筛选一级分类selectLocal (cateId, index) {this.localCategoryId = cateIdthis.localuseTypeActiveIndex = index},// 砍价筛选二级分类selectBargainErcate (status, index) {this.bargainType = statusthis.bargainsortWayActiveIndex = index},// 本地生活筛选二级分类selectlocalErcate (status, index) {//如果是false则是禁用状态不进行以下操作if (this.isActive) {return;}this.localType = statusthis.localsortWayActiveIndex = index//点击切换对应下标的导航栏设置为truethis.isActive = true;if (this.tabStatus == 1) {this.isShow = truethis.localList = [];this.page = 1this.isEndflag = falsethis.getlocalList() // this.popupFlag = !this.popupFlag} else {this.bargainList = [];this.page = 1this.isEndflag = falsethis.getbargainList() // this.popupFlag = !this.popupFlag}// this.popupFlag = !this.popupFlag},onceBuy (goodsId, isBargain, isBestPrice, index) {// console.log(isBestPrice)//跳转确认订单let isMobile = uni.getStorageSync('token').is_mobileif (isMobile == 0) {//无手机号uni.navigateTo({url:'/page/login/login'})} else {//  console.log(goodsId, '--0000')if (isBargain == 0 && !isBestPrice) {//没有砍过给确认框uni.showModal({title: '提示',content: '您今天还没有砍过该商品,请先砍价!',success: res=> {if (res.confirm) {//  console.log('用户点击确定');this.bargainGood(index, goodsId, isBargain)} else if (res.cancel) {//  console.log('用户点击取消');uni.navigateTo({url : '/pages/bargain/bargainconfirmOrder?goodsId='+goodsId })}}});} else {//砍过uni.navigateTo({url : '/pages/bargain/bargainconfirmOrder?goodsId='+goodsId })}}},bargainLinkHref (goodId) {uni.setStorageSync("isDinwei",false)uni.navigateTo({url : '/pages/bargain/bargainspDetail?goodsId='+ goodId})uni.createQRCode({path: '/pages/bargain/bargainspDetail?goodsId='+ goodId,success: function(res) {// console.log(res.path,'1212121243434s')}})}},// 邀请好友onShareAppMessage(e) {let goods_id=e.target.dataset.bargaingood.id;//    console.log(e.target.dataset.bargaingood.id,'onShareAppMessage'); let userId = uni.getStorageSync('userInfo').uidreturn {title: e.target.dataset.bargaingood.goods_name,imageUrl:e.target.dataset.bargaingood.picture,path:'pages/bargain/bargainspDetail?uid='+userId+'&goodsId='+goods_id}/*    return {path: '/pages/index/index?uid=' + userId,imageUrl : e.target.dataset.bargaingood.picture} */} }
</script><style lang="scss" scoped>.loading{ font-size: 24rpx; color: #999999; text-align: center; padding: 10rpx 0 10rpx 0;margin-top: -20rpx; }.page {width: 100%;overflow-x: hidden;}.jl{height: 32rpx;font-size: 24rpx;color: #999999;line-height: 32rpx;}.ebkContainer {background-color: #F7F7F7;}// 头部.headerTop {width: 100%;display: flex;// padding: 22rpx 0;position: fixed;background: white;top: -6rpx;left: 0;z-index: 999;.place {padding-left: 32rpx;height: 64rpx;display: inline-block;image {width: 48rpx;height: 56rpx;vertical-align: middle;}.placeName {height: 64rpx;font-size: 30rpx;color: #FFFFFF;line-height: 64rpx;margin-left: 4rpx;margin-right: 24rpx;width: 150rpx !important;overflow: hidden;word-break: break-all;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;white-space: nowrap;}}}.wrapper {width: 100%;// padding-top: 132rpx;background: white;}// 轮播图.swiperBanner {.search {// flex: 1;width: 246rpx;height: 64rpx;position: relative;background-color: #FFFFFF;left: 26rpx;top: -30rpx;border-radius: 300rpx;box-shadow: 0px 0px 4px 0px #cfcfcf;image {position: absolute;width: 28rpx;height: 28rpx;top: 17rpx;left: 22rpx;z-index: 2;}input {background: white;width: 186rpx;height: 62rpx;position: absolute;left: 0;top: 0;// border: none;// border: 1rpx solid rgba(0,0,0,0.2);// box-shadow: 0rpx 0.4rpx 2rpx #F7F7F7;border-radius: 300rpx;padding: 0;margin: 0;padding-left: 60rpx;color: #666666;font-size: 24rpx;}}// padding: 10rpx 0rpx;background-color: #FFFFFF;.swiper {width: 100%;height: 260rpx;.linkHref {width: 100%;display: block;image {width: 100%;height: 260rpx;// border-radius: 14rpx;}}/deep/ .uni-swiper-dot {width: 36rpx;height: 5rpx;margin-right: 0;border-radius: 0;}/deep/ wx-swiper .wx-swiper-dot {width: 36rpx;height: 5rpx;margin-right: 0;border-radius: 0;}/deep/ uni-swiper .uni-swiper-dots-horizontal {bottom: 20rpx;}/deep/ wx-swiper .wx-swiper-dots-horizontal {bottom: 20rpx;}}}.borderRadius{border-top-left-radius:40rpx ;border-top-right-radius:40rpx ;width: 100%;background: #f7f7f7;margin-top: -10rpx;}//tab切换栏.tabList {width: 100%;border-top-left-radius:40rpx ;border-top-right-radius:40rpx ;overflow: hidden;padding-bottom: 8rpx;padding-top: 10rpx;position: relative;display: flex;background-color: #F7F7F7 !important;.filter {position: absolute;right: 24rpx;top: 18rpx;z-index: 999;.place{padding-top: 12rpx;image{width: 24rpx;height: 28rpx;}}image {width: 20rpx;height: 20rpx;vertical-align: middle;}text {font-size: 13px;color: #999999;line-height: 32rpx;margin-left: 2rpx;}}.auto{display: flex;justify-content: space-between;width: 46%;margin-left: -140rpx;margin-top: 22rpx;position: relative;.listCon1{width: 60rpx;// width: 100%;font-size: 30rpx;font-weight: 400;color: #333333;}.listCon1.active {font-size: 30rpx;font-weight: bold;color: #008B7C;}.listCon1.active::after {content: '';width: 144rpx;height: 8rpx;// background-color: #F8C85D;border-radius: 6rpx;position: absolute;bottom: 5rpx;left: 50%;transform: translateX(-50%);visibility: visible;z-index: -1;}}.list {width: 38%;padding: 24rpx 20rpx;padding-bottom: 18rpx;margin-left: 4rpx;// background-color: #F7F7F7 ;position: relative;display: flex;.listCon {//   width: 50%;width: 48%;text-align: center;font-size: 34rpx;font-weight: bold;color: #333333;height: 44rpx;line-height: 30rpx;position: relative;z-index: 1;image{position: absolute;top: 14rpx;left: 40rpx;width: 44rpx;height: 44rpx;}}.listCon.active {font-size: 32rpx;font-weight: 600;}.listCon.active::after {content: '';width: 144rpx;height: 8rpx;// background-color: #F8C85D;border-radius: 6rpx;position: absolute;bottom: 5rpx;left: 50%;transform: translateX(-50%);visibility: visible;z-index: -1;}}}//商品列表.goodLists {padding-left: 28rpx;padding-right: 28rpx;margin: 0 auto;padding-bottom: 20rpx;margin-top: -22rpx;.localLife {width: 100%;padding-top: 26rpx;.listCon {background: #FFFFFF;border-radius: 16rpx;width: 100%;margin-bottom: 20rpx;padding-top: 20rpx;padding-bottom:10rpx ;.linkHref {display: flex;padding-left: 24rpx;padding-right: 32rpx;.spBg {width: 222rpx;.shopping {padding-left: 16rpx;width: 80rpx;height: 38rpx;border-radius: 8rpx 8rpx 8rpx 8rpx;background: #FF8F50;line-height: 38rpx;font-size: 22rpx;color: #FFFFFF;// margin: 0 auto;margin-top: 6rpx;}.spImg {width: 250rpx;height: 146rpx;border-radius: 8rpx;background-repeat: no-repeat;background-size: 100% 100%;background-position: center;margin-top: 20rpx;}}.spDetail {margin-left: 52rpx;flex: 1;padding-bottom: 12rpx;// border-bottom: 2rpx dashed rgba(151, 151, 151, 0.19);.spName {padding-left: 8rpx;color: #333333;font-size: 28rpx;height: 80rpx;// width: 100%;line-height: 40rpx;text-overflow: -o-ellipsis-lastline;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 2;line-clamp: 2;-webkit-box-orient: vertical;}.spOrder {// width: 100%;padding-top: 20rpx;padding-bottom: 30rpx;padding-left: 8rpx;.orderNum {font-size: 24rpx;color: #999999;height: 28rpx;line-height: 12rpx;}.distance {height: 28rpx;font-size: 22rpx;color: #C5C5C5;line-height: 12rpx;}}.spPrice {width: 100%;height: 64rpx;// background: linear-gradient(90deg, #F46333 0%, #F8472D 100%);border-radius: 16rpx;display: flex;.nowPrice {// font-size: 24rpx;line-height: 66rpx;color: #F53C13;font-size: 42rpx;text {color: #F53C13;// font-family: DIN-Medium, DIN;font-weight: 500;margin-left: 10rpx;}}.oldPrice {font-size: 20rpx;font-weight: 400;color: #666666;line-height: 80rpx;margin-left: 10rpx;overflow: hidden;height: 64rpx;text-decoration: line-through;flex: 1;}.shopTip {width: 154rpx;height: 64rpx;background-repeat: no-repeat;background-size: contain;background-position: center;}}}}}}}.noData {position: relative;bottom: 0;width: 100%;text-align: center;height: 40rpx;line-height: 40rpx;.noMore {font-size: 24rpx;color: #333333;}}.popWrapper {width: 100%;height: 100%;position: fixed;background-color: rgba(0, 0, 0, 0.1);top: 0;left: 0;z-index: 9999;.popContent {width: 100%;position: absolute;bottom: 0;left: 0;height: 514rpx;background: #FFFFFF;border-radius: 32rpx 32rpx 0rpx 0rpx;.title {padding-top: 18rpx;position: relative;text-align: center;text {height: 36rpx;font-size: 26rpx;color: #666666;line-height: 36rpx;text-align: center;}image {width: 24rpx;height: 24rpx;position: absolute;top: 24rpx;right: 32rpx;}}.content {padding-top: 44rpx;.item {width: 100%;.titleName {padding: 0 32rpx;height: 36rpx;font-size: 26rpx;color: #666666;line-height: 36rpx;}.list {// width: 100%;padding: 0 32rpx;margin-bottom: 26rpx;white-space: nowrap;.listCon {width: 156rpx;height: 64rpx;background: #EAEAEA;border-radius: 32rpx;display: inline-block;line-height: 64rpx;text-align: center;font-size: 22rpx;color: #666660;margin-right: 32rpx;margin-top: 16rpx;}.listCon.active {background: linear-gradient(90deg, #FC8233 0%, #FB5423 100%);color: #FFFFFF;}}}}.bottom {position: absolute;bottom: 0;left: 32rpx;right: 32rpx;.list {width: 50%;float: left;height: 88rpx;background: linear-gradient(90deg, #FAC73B 0%, #F8982F 100%);border-radius: 44rpx 0 0 44rpx;font-size: 28rpx;color: #FFFFFF;line-height: 88rpx;text-align: center;font-weight: 600;}.done {background: linear-gradient(113deg, #FC8233 0%, #FB5423 100%);border-radius: 0 44rpx 44rpx 0;text-align: center;}}}}</style>

全局app.vue中获取用户进入时候的经纬度去计算附近地铁站

<script>export default {globalData: {URL: 'https://aaa.aaa.cn/api/', //测试环境//    URL: 'https://aaa.aaa.cn/api/', //预发布环境// URL: 'https://aaa.aaa.cn/api/', //正式环境is_mobile: 0, //手机号是否存在//is_user_info:0,//头像是否存在token: null,subway_name:''},methods: {updateData(){console.log('刷新数据')uni.getStorageSync('isDinwei',true)},get_token() {let that = this;return new Promise(function (resolve, reject) {uni.login({ //获取codeprovider: 'weixin',success: (res2) => {//console.log(res2.code,'111111111111111111111111');                           //return false;uni.request({url: that.globalData.URL + "auth/mpLogin",method: 'POST',data: {version: '251',client: 'wxmp',code: res2.code,},success(res) {//console.log(res.data, '111111111111111111111111');if (res.data.status == 'ok') {uni.setStorageSync('token', res.data.data);that.globalData.is_user_info = res.data.data.is_user_info;that.globalData.is_mobile = res.data.data.is_mobile;that.globalData.token = res.data.data.token;uni.$emit('uptoken', {msg: 'token更新',data: res.data.data})}that.getUserInfo()resolve()}})},fail: () => {uni.showToast({title: "微信登录授权失败22",icon: "none"});reject()}})// 一段耗时的异步操作// resolve('成功') // 数据处理完成// reject('失败') // 数据处理出错})},getLocation() {return new Promise((resolve, reject) => {let that =this// wx.getSetting({//   success: (res) => {//     let authSetting = res.authSetting//     if (res.authSetting['scope.userLocation']) {// 已授权wx.getLocation({type: "gcj02",isHighAccuracy: "true",success: (res) => {console.log(res)console.log(res.longitude, 'getLocation获取当前经纬度')console.log(res.latitude, 'getLocation获取当前经纬度')uni.request({url: this.globalData.URL + "subway/getSubway",method: 'POST',data: {version: '251',client: 'wxmp',latitude: res.latitude + 0.001276,longitude: res.longitude + 0.006256},success: (res) => {console.log(res, '地铁站计算距离')this.globalData.fujin_sub = res.data.data.result.geo_subwaythis.globalData.jwd = res.data.data.result.locationuni.setStorageSync('getCity', res.data.data.result.addressComponent);if (res.data.data.result.addressComponent.cityId == '0') {uni.setStorageSync('localcityId', 9999);} else {uni.setStorageSync('localcityId', res.data.data.result.addressComponent.cityId);}uni.setStorageSync('localcityNm', res.data.data.result.geo_subway);uni.setStorageSync('City', res.data.data.result.location);resolve(res.data.data.result.location)}})},fail: () => {reject('getLocation failed')}});// } else if (authSetting['scope.userLocation'] === false) {//   wx.showModal({//     title: '您未开启地理位置授权',//     content: '请在系统设置中打开位置授权,以便我们为您提供更好的服务',//     success: (res) => {//       if (res.confirm) {//         wx.openSetting()//       }//     }//   })//   reject('getLocation failed')// } else {//   wx.authorize({//     scope: 'scope.userLocation',//     success: () => {//       this.getLocation().then((res) => {//         resolve(res)//       }).catch(() => {//         reject('getLocation failed')//       })//     },//     fail: () => {//       wx.showModal({//         title: '您未开启地理位置授权',//         content: '请在系统设置中打开位置授权,以便我们为您提供更好的服务',//         success: (res) => {//           if (res.confirm) {//             wx.openSetting()//           }//         }//       })//       reject('getLocation failed')//     }//   })// }// }// })})},checkLocationAuth() {return new Promise((resolve, reject) => {wx.getSetting({success: (res) => {let authSetting = res.authSetting;if (authSetting['scope.userLocation']) {// 已授权this.getLocation();resolve();} else if (authSetting['scope.userLocation'] === false) {wx.showModal({title: '您未开启地理位置授权',content: '请在系统设置中打开位置授权,以便我们为您提供更好的服务',success: (res) => {if (res.confirm) {wx.openSetting();}reject();}});} else {wx.authorize({scope: 'scope.userLocation',success: () => {this.getLocation();resolve();},fail: () => {wx.showModal({title: '您未开启地理位置授权',content: '请在系统设置中打开位置授权,以便我们为您提供更好的服务',success: (res) => {if (res.confirm) {wx.openSetting();}reject();}});}});}}});});},is_user_info(){//用户信息是否齐全let isMobile = uni.getStorageSync('token')if(!isMobile){return   this.get_token();}if ( uni.getStorageSync('token').is_mobile == 0 || uni.getStorageSync('token').is_user_info == 0) {uni.showModal({title: '需要获取你的授权信息',                   success: function (res) {if (res.confirm) {uni.navigateTo({url: "/pages/login/login",fail:(e)=>{                              }})} else if (res.cancel) {console.log('用户点击取消');}}});       return 0;                          }else{return 1; }},formatRichText(html) {// store_source_id 为1是平台的,2是享库存,3是联联,3需要其他方式去解析let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');return match;});newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');return match;});newContent = newContent.replace(/<br[^>]*\/>/gi, '');newContent = newContent.replace(/\<img/gi,'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');return newContent;},copy(e){uni.setClipboardData({data: e,success: function () {//  console.log('success');}});},getUserInfo() {let that = this;uni.request({url: that.globalData.URL + "user/getUserInfo",method: 'POST',data: {version: '251',client: 'wxmp',token: that.globalData.token,},success(res) {uni.setStorage({key: 'userInfo',data:  res.data,success: function () {uni.$emit('upuserInfo', {msg: 'userInfo更新',data: res.data})}});// console.log(res,'头像')}})},//获取当前页面路径和参数get_url(){let pages = getCurrentPages()let len = pages.lengthlet curParam = pages[len - 1].options //获取当前页面参数let param = []for (let key in curParam) { //获取key=value键值对格式数组param.push(key + '=' + curParam[key])}let _url = '' //除去第一个参数拼接后面参数param.forEach((item, i) => {if (i != 0) { //拼接&符号,由于第一组前拼接的是?所有第一组需要单独处理_url += '&' + item}})let url = '/' + pages[len - 1].route + '?' + param[0] + _url;return url;} },onLoad() {this.getUserInfo()this.get_token()// this.checkLocationAuth();},onLaunch() {let that = thisPromise.all([that.get_token().then( res => {// this.checkLocationAuth();})// 其他异步操作...]).then(() => {// 所有异步操作都完成后执行下一步操作// ...});},// onLaunch: function() {//     let that = this//  // that.getLocation().then(res=>{//     //  // const obj = {res.lat}//     //  uni.setStorageSync('City',res);//     //  that.globalData.jwd = res//    //  // uni.setStorageSync('localcityNm',that.globalData.subway_name);//   // })//     console.log('App Launch')// },onShow: function() {//  uni.showShareMenu();console.log('App Show')},onHide: function() {console.log('App Hide')}}
</script><style>/*每个页面公共css */page {height: 100%;background-color: #F7F7F7;}.fl {float: left;}.fr {float: right;}.clearfix::after {content: "";width: 0;height: 0;line-height: 0;display: block;visibility: hidden;clear: both;}.clearfix {zoom: 1;}</style>

小程序获取用户当前位置计算距离最近的地铁站并获取对应地区的商品(可手动切换地铁线路及地铁站)相关推荐

  1. 微信小程序 - 获取用户当前位置信息(用于定位地址及获取地址等需求)

    前言 有两种获取位置的方式,一种是 直接返回经纬度等信息(必须代码处理后才能显示到界面上),另一种是 "界面选择式" 由用户打开地图选择位置. 最近有添加用户收货地址需求(外卖项目 ...

  2. 微信小程序中通过两点经纬度计算距离

    效果图 先拿到自己的经纬度 data:{// 目的地坐标latitude2: 22.490548,longitude2: 113.921921,}/*** 生命周期函数--监听页面加载*/onLoad ...

  3. 微信外卖小程序 怎么计算与客户的距离_微信小程序结合腾讯位置服务实现用户商家距离计算...

    前言 小程序实操,距离计算总结. 思路 一共有两种方法,各有利弊: 1.利用小程序的wx.getLocation 方法得到用户的经纬度,然后用已知的商家的经纬进行计算; 2.利用腾讯地图位置服务cal ...

  4. 计算两个经纬度之间的距离软件_小程序使用腾讯位置服务计算两地之间的距离(有源码)...

    背景: 在最近的小程序开发中,需要计算当前位置到目标位置之间的距离.背靠"腾讯爸爸",没有理由不使用腾讯的位置服务啊!趁着周末把使用方式整理一下,还写了一个demo,和大家分享一下 ...

  5. 微信小程序弹出用户授权弹窗,微信小程序引导用户授权,获取位置经纬度

    我们在开发小程序时,有些操作必须让用户授权.比如我们获取用户位置,需要用户授权位置信息.授权操作我们需要给用户弹窗提示,在用户禁用某些权限时,又要引导用户去设置页开启相应权限.我们这里就以获取经纬度为 ...

  6. uni-app开发微信小程使用腾讯位置服务获取用户的位置信息

    uni-app开发微信小程使用腾讯位置服务获取用户的位置信息 一.开通腾讯位置服务 二.编码实现 (一)获取定位坐标 (二).在项目中使用 一.开通腾讯位置服务 在这里我们先要登录腾讯我i之服务的官网 ...

  7. 微信小程序(1)-用户头像-昵称的获取及其UI设计

    要做出来的样式如下 1-用户-User设计 user.js(该处代码为小程序的逻辑页面,就是说我们所编写的处理问题的函数就写在这里) userinfo:我们命名对的自变量,代表用户信息. onShow ...

  8. 微信中html5获取手机号,微信小程序通过用户授权获取手机号

    这篇文章主要介绍了微信小程序如何通过用户授权获取手机号(getPhoneNumber),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 小程序有一个获 ...

  9. 获取微信小程序右上角胶囊的位置

    获取微信小程序右上角胶囊的位置 微信中有一个api是用来获取胶囊的位置以及其他信息的,这个可以在我们使用自定义的标题的时候避开这个位置,或者自己写点什么东西 ,要和胶囊对齐的 api wx.getMe ...

最新文章

  1. Spring Boot 实现万能文件在线预览
  2. Java设计模式之适配器模式
  3. 常用CSS元素div ul dl dt ol的简单解释
  4. C++总结笔记(十二)—— 智能指针
  5. python3.6基础知识_python的基础知识
  6. 支持nvme的linux_Linux nvme驱动初探
  7. [Java学习资料] [成长之路]
  8. 敏捷软件开发宣言–Manifesto for Agile Software Development
  9. stringr | 文本处理方法(Ⅰ-3):字符串处理函数(下)
  10. PHP获得文件的md5并检验是否被修改
  11. php中求10递归算法,PHP递归算法的应用(含示例)
  12. eric python mysql_joson 、python和mysql的使用
  13. 关于高斯-博内-陈定理
  14. Unity3d报错:Error building Player: Win32Exception: ApplicationName='xxxxxx/zipalign.exe'
  15. 借鉴FCoin商业模式,写了一份白皮书去参赛
  16. 左益豪:用代码创造一个新世界|OneFlow U
  17. RSA非对称加密,前台vue加密,后台java解密
  18. 使用LiveGBS GB28181平台监控视频录像回放如何在页面上嵌入录像时间轴
  19. java导出pdf文件并下载_java根据模板生成pdf文件并导出
  20. 四面阿里巴巴如愿拿到offer定级P7,为此我筹备了半年

热门文章

  1. 图形学-反走样/抗锯齿
  2. [Errno 98] Address already in use
  3. Terraform实战 | 实用云部署编程入门指南,DevOps软件开发运维必备
  4. apollo学习之---如何标定车辆油门和制动
  5. 10.5 外部中断的处理过程
  6. 用python实现化学方程式配平
  7. 宝塔面板使用Supervisor管理器开启守护进程
  8. java 实现文件大小换算工具方法
  9. Reinforcement Learning with Evolutionary Trajectory Generator
  10. Object类中的方法