微信小程序定位用户附近地铁站获取对应商家(可手动切换地铁线路及地铁站)

功能介绍

主要就是获取到用户当前位置的经纬度,调用后端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 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>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      sub: "",
      multiArray: [], // 多列选择器数据
      multiIndex: [0, 0], // 多列选择器当前选中索引值
      line: "", // 当前选中地铁线路名称
      station: "", // 当前选中地铁站点名称
      lines: [], // 地铁线路列表
      stations: [] ,// 地铁站点列表
	  City:[],//存储经纬度
	  searchValue:'',//用户搜索的内容
	  searchHistory:[],//历史记录列表
    };
  },

 // 在组件挂载后获取 localcityNm 缓存值,并请求地铁线路列表
 mounted() {
    
    
   this.sub = uni.getStorageSync("localcityNm");
   this.getSubwayLinesList();
 },
 
 // 在页面加载时获取历史搜索记录和定位标志,将定位标志设为 false
 onLoad(){
    
    
   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) {
    
    
     // 将点击的历史搜索记录项值赋给搜索框
     this.searchValue = item;
     // 执行搜索方法进行搜索,并将定位标志设置为 true
     this.search();
     const isDinwei = uni.getStorageSync('isDinwei')
     uni.setStorageSync('isDinwei',true)
   },
 
   // 执行搜索操作的方法
   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;
       const station = data[0];
   
       if (station) {
    
    
         // 更新选中的地铁站点,并将其存储到 localStorage 中
         this.station = station.subway_name;
         uni.setStorageSync('localcityNm', station.subway_name);
   
         // 获取当前地铁站点的经纬度信息,并更新到全局 City 中
         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);
 
         // 将搜索历史记录存储到 localStorage 中,如果已经存在则不添加
         const history = uni.getStorageSync('searchHistory') || [];
         if (!history.includes(station.subway_name)) {
    
    
           // 跳转到首页,并将定位标志设置为 true
           this.toIndex()
           const isDinwei = uni.getStorageSync('isDinwei')
           uni.setStorageSync('isDinwei',true)
           history.push(station.subway_name);
           this.searchHistory=history;
           uni.setStorageSync('searchHistory', this.searchHistory);
         }
       } else {
    
    
         // 如果没有找到匹配的地铁站点,则弹出未找到提示
         uni.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 = data
      this.City = City
      // 如果用户没有选择站点,则默认选择距离用户最近的站点
      if (!this.station) {
    
    
        // 如果用户还没有选择站点,则将其设为本地存储中的城市名localcityNm
  	  this.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;
				}
	}
	
</style>

首页渲染对应商品列表

<template>
	<view class="page">
		<view class="ebkContainer">
				<!-- 头部 -->
				<view class="headerTop" :style="'padding-top: '+ capsuleTop + 'px;'" id="headerTop">
					
					<view class="search" @click="backSearch" :style="'margin-right: '+ capsuleWidth + 'px;'">
						<image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/mini-wx/images/homeIndex/search.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 }" @click.stop="selectlocalErcate(item.status, i)">{
    
    {
    
    item.name}}</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">{
    
    {
    
    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 localLife" v-if="tabStatus == 1">
											<view class="listCon" v-for="(item, i) in localList" :key="i">
												<navigator class="linkHref" :url="'/pages/localLife/localLifespdetail?goodsId=' + item.store_goods_id">
													<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>{
    
    {
    
    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-family: PingFang SC-Bold, PingFang SC;
															font-weight: bold;
															color: #FFFFFF;
															line-height: 52rpx;text-align: center;">
																马上抢
															</view>
														</view>
													</view>
												</navigator>
											</view>
										</view>
										<view class="noData" v-if="tabStatus == 1">
											<view class="noMore" v-if="isEndflag && localList.length == 0">暂无数据</view>
											<view class="noMore" v-if="isEndflag && localList.length > 0">没有更多数据了</view>
										</view>
									</view>			
								</view>
					</view>
			
		
			</view>
	</view>
	
</template>

<script>
	var _self, page = 1;
	let app = getApp();
	//import indexBackgroundImage from "@https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/mini-wx/images/homeIndex/pricebg.png"
	export default {
    
    
		data() {
    
    
			return {
    
    
				headerTop:50,
				province:'',
				indexBackgroundImage:'https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/mini-wx/images/homeIndex/pricebg.png', //砍价背景图
				capsuleWidth: '', //胶囊宽度
				capsuleTop: '', //胶囊居顶
				tabList: [{
    
    
						name: '天天特价',
						status: 1
					},
					
				],
				tabActiveIndex: 0,
				localList: [], //切换栏本地生活列表
				isTop: false, //默认切换栏不知顶
				tabBarTop: 0, //默认tab栏高度
				tabStatus: 1, //切换栏状态
				page: 1,
				pageSize: 10,
				isEndflag: false,
				uid: '',
				sortWayActiveIndex: 0,
				sortWayStatus: 0,
				couponisEndflag: false,
				localCategoryId: '', //本地生活分类id
				localType: 2, //本地生活类型
				popupFlag: false,
				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, // 初始化为true
				isDinwen:false
			}
		},
		async onPullDownRefresh() {
    
    //下拉刷新
			// 强制删除后重新获取数据
			if(!this.localsortWayList.status === 2){
    
    
				this.localsortWayActiveIndex = 0
			}
			uni.removeStorageSync('localcityNm')
			uni.removeStorageSync('City')
			// this.$forceUpdate()

				// console.log(this.province+'去存储中获取值之后')
			this.couponpage = 1;
			this.couponisEndflag = false
			this.couponList = []
			// this.getCouponList() //大牌好券列表
			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 = true
			 uni.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) + 19
		 	this.capsuleTop = Number(capsuleData.top)
		 },
		 onUnload() {
    
    
		 },
		onLoad(option) {
    
    
			console.log()
			// setTimeout(()=>{
			// 	 this.province = uni.getStorageSync('localcityNm');
			// 	 this.getlocalList()
			// },1000)
			// this.isDinwen = uni.setStorageSync('isDinwei',false)
			// this.isDinwei = uni.getStorageSync('isDinwei')
			this.isDinwei = true
			uni.setStorageSync('isDinwei',this.isDinwei)
			console.log(uni.getStorageSync('isDinwei'),'wdawadaw')
			// 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.getlocalCateList() //本地生活分类
			 }
			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() {	
			
			console.log('我是onShow')
			this.province = uni.getStorageSync('localcityNm')
			this.token = uni.getStorageSync('token').token		
			console.log(this.isDinwen)
			//判断是否手动选择更改了地铁站,如果不是则不需要重新加载数据
			if(uni.getStorageSync('isDinwei')===false){
				this.getlocalList()
			}else{
				//否则就得根据新的定位经纬度去请求新的数据
				if (!this.token) {
					app.get_token().then( res => {
						this.token = uni.getStorageSync('token').token
						this.tabChange(this.tabStatus, this.tabActiveIndex); 
					})
				}else {
					app.get_token().then( res => {
						this.token = uni.getStorageSync('token').token
						this.tabChange(this.tabStatus, this.tabActiveIndex); 
					})
				}
			}
			this.isDinwen = false
			uni.setStorageSync('isDinwei',this.isDinwen)
		
			this.couponpage = 1;
			this.couponisEndflag = false
			
		},
		// 上拉加载
		onReachBottom() {
			if (this.isEndflag) {
				return
			} else {
				this.page++
				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();
				
		},
		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: {
			location(){
				//点击进入自选位置页面时候设为true,进入了自选位置页面如果没有更改地址,则在刚进入页面触发onload函数就已经将值更改为false了,在选择完地铁站之后在将值更改为true,返回首页后第一次会重新计算经纬度加载数据,之后不会
				this.isDinwen = true
				uni.setStorageSync('isDinwei',this.isDinwen)
				let that = this;
				uni.navigateTo({
					url:'/pages/map/map'
				})
			},
			moveHandle () {},
			
			// 本地生活列表第一张图片
			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(){
    
    
					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) {
    
    
						return
					}
					if (res.data.status == 'ok') {
    
    
						var data = res.data.data
						if (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.province = uni.getStorageSync('localcityNm')
						}
					} else {
    
    
						this.isEndflag = true
					}
			},
			// 切换栏
			tabChange(statusIndex, index) {
    
    
				console.log(statusIndex,index)
				this.localList = [];
				this.page = 1
				this.tabStatus = statusIndex
				this.tabActiveIndex = index
				this.isEndflag = false
				if (statusIndex == 1) {
    
    
					this.getlocalList()
					
				} else {
    
    
				
				}
			},
			backSearch () {
    
    
				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 = cateId
				this.localuseTypeActiveIndex = index
			},
			// 本地生活筛选二级分类
			selectlocalErcate (status, index) {
    
    
				this.localType = status
				this.localsortWayActiveIndex = index
				if (this.tabStatus == 1) {
    
    
					this.localList = [];
					this.page = 1
					this.isEndflag = false
					this.getlocalList() 
					// this.popupFlag = !this.popupFlag
				} else {
    
    
					this.bargainList = [];
					this.page = 1
					this.isEndflag = false
					this.getbargainList() 
					// this.popupFlag = !this.popupFlag
				}
				// this.popupFlag = !this.popupFlag
			},
	
			
			bargainLinkHref (goodId) {
    
    
				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').uid
			return {
    
    
				title: e.target.dataset.bargaingood.goods_name,
				imageUrl:e.target.dataset.bargaingood.picture,
				path:'pages/bargain/bargainspDetail?uid='+userId+'&goodsId='+goods_id
				}
	
		} 
	}
</script>

<style lang="scss" scoped>
	.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: 0;
		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;
			}
		}

		.search {
    
    
			// flex: 1;
			width: 430rpx;
			height: 64rpx;
			position: relative;
			background-color: #FFFFFF;
			left: 32rpx;
			bottom: 3rpx;
			image {
    
    
				position: absolute;
				width: 22rpx;
				height: 18rpx;
				top: 22rpx;
				left: 22rpx;
				z-index: 999;
			}

			input {
    
    
				width: 100%;
				height: 62rpx;
				position: absolute;
				left: 0;
				top: 0;
				// border: none;
				border: 1rpx solid rgba(0,0,0,0.2);
				border-radius: 300rpx;
				padding: 0;
				margin: 0;
				padding-left: 60rpx;
				color: #666666;
				font-size: 24rpx;
			}
		}
	}
   
    .wrapper {
    
    
		width: 100%;
		// padding-top: 132rpx;
		background: white;
	}
	.borderRadius{
    
    
		border-top-left-radius:40rpx ;
		border-top-right-radius:40rpx ;
		width: 100%;
		background: #f7f7f7;
	}
	//tab切换栏
	.tabList {
    
    
		border-top-left-radius:40rpx ;
		border-top-right-radius:40rpx ;
		width: 100%;
		overflow: hidden;
		padding-bottom: 8rpx;
        // margin-top: 8rpx;
		position: relative;
		display: flex;
		background-color: #F7F7F7 !important;
		
		.filter {
    
    
			position: absolute;
			right: 32rpx;
			top: 18rpx;
			z-index: 999;
			.place{
    
    
				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;
			width: 50%;
			margin-left: -140rpx;
			margin-top: 24rpx;
			position: relative;
			.listCon1{
    
    
				width: 100%;
				font-size: 26rpx;
				font-weight: 400;
				color: #333333;
			}
			
			.listCon1.active {
    
    
				font-size: 26rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				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: 20rpx 20rpx;
			padding-bottom: 18rpx;
			margin-left: 4rpx;
            // background-color: #F7F7F7 ;
			position: relative;
			display: flex;
			.listCon {
    
    
			//	width: 50%;
			    width: 45%;
				text-align: center;
				font-size: 32rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				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 {
    
    
		width: 92%;
		margin: 0 auto;
		padding-bottom: 20rpx;
		margin-top: -16rpx;

		.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: 56rpx;
					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: 230rpx;
							height: 136rpx;
							background-repeat: no-repeat;
							background-size: 100% 100%;
							background-position: center;
							margin-top: 20rpx;
					    }
					}
					
		
					.spDetail {
    
    
						margin-left: 42rpx;
		                flex: 1;
						padding-bottom: 12rpx;
						// border-bottom: 2rpx dashed rgba(151, 151, 151, 0.19);
						.spName {
    
    
							color: #333333;
							font-size: 24rpx;
							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;
							.orderNum {
    
    
								font-size: 20rpx;
								color: #999999;
								height: 28rpx;
								line-height: 28rpx;
							}
							.distance {
    
    
								height: 28rpx;
								font-size: 22rpx;
								color: #C5C5C5;
								line-height: 28rpx;
							}
							
						}
						.spPrice {
    
    
							width: 100%;
		                    height: 64rpx;
							// background: linear-gradient(90deg, #F46333 0%, #F8472D 100%);
							border-radius: 16rpx;
							display: flex;
							.nowPrice {
    
    
								font-size: 24rpx;
								line-height: 68rpx;
								padding-left: 0rpx;
								color: #F53C13;
								font-size: 28rpx;
								text {
    
    
									font-size: 28rpx;
									color: #F53C13;
									font-family: DIN-Medium, DIN;
									font-weight: 500;
									margin-left: 10rpx;
								}
							}
							.oldPrice {
    
    
								font-size: 20rpx;
								font-weight: 400;
								color: #666666;
								line-height: 68rpx;
								margin-left: 16rpx;
								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 {
    
    
		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://weaa', //测试环境
		//	URL: 'https://wada', //预发布环境
		 // URL: 'https:waa', //正式环境
			is_mobile: 0, //手机号是否存在
			//is_user_info:0,//头像是否存在
			token: null
		},
		methods: {
    
    
			get_token() {
    
    
				let that = this;
				return new Promise(function (resolve, reject) {
    
    
					uni.login({
    
     //获取code
						provider: '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;
					uni.getLocation({
    
    
						type: 'wgs84',
						success: function (res) {
    
    
							console.log(res,'夫')
							//City
							uni.setStorageSync('City',{
    
    'longitude':res.longitude,'latitude':res.latitude});
							uni.request({
    
    
								url: that.globalData.URL + "subway/getSubway",
									method: 'POST',
									data: {
    
    
										version:'251',
										client:'wxmp',
										latitude: res.latitude,
										longitude: res.longitude
									},
									success(res) {
    
    
										
										console.log(res)
										//this.province=res.data.data.addressComponent.province;
											uni.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('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)
										
									}
								})	
						
						}
					});
				})
			},
			 
			 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) {
    
    
					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
						     })
						    }
						});
					}
				})
			},
			//获取当前页面路径和参数
			get_url(){
    
    
				
				 let pages = getCurrentPages()
				    let len = pages.length
				    let 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.getLocation();
		},
		onLaunch: function() {
    
    
			// uni.setStorageSync('localcityNm','北京市');
			this.get_token().then( res => {
    
    
				this.getLocation();
			})
				
			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>

猜你喜欢

转载自blog.csdn.net/qq_47272950/article/details/130370205