跳到主要内容

微信小程序转uniApp

·6090 字·13 分钟

1. 转换 #

2. 不支持background-image引用本地图片 #

改成服务器上的图片

:style="‘background-image: url(’ + topbg + ‘);’"

topbg: app.globalData.imgurl + ‘/home/home_top_bg.png’,

3. 安装插件 #

vue插件

https://ext.dcloud.net.cn/plugin?id=10663

文档

https://uniapp.dcloud.net.cn/tutorial/debug/uni-vue-devtools.html

4. 腾讯地图(qqmap-wx-jssdk.reverseGeocoder)报错或者不走sucess #

initData: function () {
  var that = this;
  qqmapsdk = new QQMapWX({
    key: app.globalData.mapsdkkey
  });
  // 获取当前位置
  qqmapsdk.reverseGeocoder({
    success: function (res) {
      var adcode = res.result.ad_info.adcode;
      var indexv = 0;
      if (adcode != '') {
        var adcodesub = adcode.substring(0, 4);
        if (adcodesub == '3501') {
          var ctlist = that.cityArrCode;
          for (var i = 0; i < ctlist.length; i++) {
            if (ctlist[i] == adcode) {
              indexv = i;
              break;
            }
          }
        }
      }
      var aab301 = that.aab301;
      if (aab301 === '') {
        that.setData({
          index: indexv,
          aab301: '35'
        });
      }
      that.setData({
        latitude: res.result.location.lat,
        longitude: res.result.location.lng,
        wzlocation: res.result.address_component.district
      });
      that.queryCb33();
    },
    //定位失败回调
    fail: function (err) {
      uni.showToast({
        title: '定位失败',
        icon: 'none'
      });
    }
  });
},

调用initData()方法,执行了很长时间fail–>“getLocation:fail network error”

uniapp开发小程序调用腾讯位置服务reverseGeocoder方法报错"getLocation:fail network error"

解决

引用的const QQMapWX = require(’../../../components/js/qqmap-wx-jssdk.js’);这个sdk是为小程序设计的,所在在转为H5(vue)之后使用会存在跨域问题。目前有两种方法解决,一种是通过vue-jsonp对sdk进行修改,另一种是在manifest.json中进行代理配置。

第一种方法可以参考: [[在uniApp H5项目中使用腾讯地图sdk-改sdk版本]]

第二种方法可以在manifest.json中这样配置:

"h5" : {
  "devServer" : {
    "disableHostCheck" : true,
    "https" : false,
    "port" : 8080,
    "proxy" : {
      "/apis" : {
        "target" : "https://apis.map.qq.com",
        "changeOrigin" : true,
        "secure" : true,
        "pathRewrite" : {
          "^/apis" : ""
        }
      }
    }
  },
  "sdkConfigs" : {
    "maps" : {
      "tencent" : {
        "key" : "TE2BZ-C2WWJ-ICTFX-XPR4V-K2GI3-NSFRH"
      }
    }
  }
}

不知道为什么配置完之后调用时间比较长(实测有的时候达到3分钟,根本无法使用),不知道是不是因为公司使用inode之后中转比较多造成的,等待后续解决。

最终方案:

第二种方案太耗时了,遂直接通过腾讯地图的WebService API在线调用:

IP定位文档:https://lbs.qq.com/service/webService/webServiceGuide/position/webServiceIp

逆地址解析文档:https://lbs.qq.com/service/webService/webServiceGuide/address/Gcoder

由于现有代码只需要获取当前位置的区划和经纬度,所以使用ip定位即可

initData: function () {
  var that = this;
  uni.request({
    url: 'https://apis.map.qq.com/ws/location/v1/ip?key=' + app.globalData.mapsdkkey,
    data: {},
    method: 'GET',
    success: function (res) {
       console.log(res)
       var adcode = res.data.result.ad_info.adcode + '';
       var indexv = 0;
       if (adcode != '') {
         var adcodesub = adcode.substring(0, 4);
         if (adcodesub == '3501') {
           var ctlist = that.cityArrCode;
           for (var i = 0; i < ctlist.length; i++) {
             if (ctlist[i] == adcode) {
               indexv = i;
               break;
             }
           }
         }
       }
       var aab301 = that.aab301;
       if (aab301 === '') {
         that.setData({
           index: indexv,
           aab301: '35'
         });
       }
       that.setData({
         latitude: res.data.result.location.lat,
         longitude: res.data.result.location.lng
       });
       that.queryCb33();
      }
  });
},

5. 各种样式问题,具体问题具体调整就行了 #

6. 关于组件打开关闭后,再次点击组件没法出来的问题 #

举例:在招聘会页面中(http://localhost:8080/#/pages/rlzy/recruitment_list/recruitmentList),初次点击“筛选”按钮,筛选页面可以出来,关闭后再次点击,就没有反应了。

经排查,主页面recruitmentList.vue中通过isShowPickBar属性对zphBar进行显示关闭控制(关闭操作在zphbar.vue中),当打开bar再关闭之后,isShowPickBar这个属性没有设置为false,遂再次点击时bar没法出来。

<zphBar :showDv="isShowPickBar" :acb333="acb333" @myEvent="toSetSx" @doEvent="toSure"></zphBar>

解决:

在组件zphbar.vue中关闭bar的函数中增加一个自定义事件closeBar

toCancel: function () {
    this.setData({
        showDvClone: false
    });
    this.$emit('closeBar'); // 触发自定义事件
},

在主页面recruitmentList.vue中绑定closeBar事件,并设置isShowPickBar为false

<zphBar :showDv="isShowPickBar" :acb333="acb333" @myEvent="toSetSx" @doEvent="toSure" @closeBar="closeBar"></zphBar>
closeBar: function () {
  let that = this;
  that.setData({
    isShowPickBar: false
  });
}, 

7. 使用background设置背景图,background-size: 100% 100%;在元素中不显示的问题 #

<view class="logo" :style="'background: url(' + dwImg + ') center center no-repeat;background-size: 100% 100%;'"></view>

dwImg图片较大,在页面元素里background-size: 100% 100%;未生效。

解决:

<view class="logo" :style="'background: url(' + dwImg + ') center center / 100% 100% no-repeat;'"></view>

8. uni.openLocation报错Map key not configured. #

在manifest.json中配置一下即可

配置完源码是这样的:

9. nav-bar的title不显示问题 #

原来写法:

<nav-bar class="navbar" v-title="用户中心" :no-border="true" :showBack="true" :bg="navbg"></nav-bar>

修改为以下写法:

<nav-bar class="navbar" :v-title="vTitle" :no-border="true" :showBack="true" :bg="navbg"></nav-bar>
data() {
  return {
    vTitle: '用户中心',
  };
},

10. 部分页面navigationBarTitleText不显示问题 #

现象:

原因:头部样式覆盖了

解决:调整top举例即可

.all_pic {
  width: 100%;
  background-color: #ffffff;
  z-index: 999;
  float: left;
  position: fixed;
  top: 84rpx;
  clear: both;
}

11. 非标准结构页面改造(语法) #

比如下面这种方法:需要该写到method里面

var getCc2glist = function (self) {
    uni.request({
        url: app.globalData.urlConfig.jobBaseUrl + '/job/person/candidate/getVCc2gCb21Page',
        // url: app.urlConfig.jobBaseUrl+'/job/person/candidate/getVCc2gCb21PageDes',
        data: {
            acb2ga: 1,
            aac001: uni.getStorageSync('userinfo').businessid,
            pageNo: self.data.pageNo,
            pageSize: 20
        },
        header: app.globalData.getHeader(),
        method: 'POST',
        success: function (res) {
            if (res.statusCode == 401 || res.statusCode == 403) {
                app.globalData.handleTokenExpire();
            } else {
                for (var i = 0; i < res.data.result.length; i++) {
                    var acc2g1_ = res.data.result[i].acc2g1;
                    if (acc2g1_ != null && acc2g1_ != '') {
                        const timeString = acc2g1_;
                        const date = new Date(timeString);
                        // 转换为北京时间(UTC+8)
                        date.setUTCHours(date.getUTCHours() + 8);
                        // 获取日期部分
                        const beijingDate = date.getUTCFullYear() + '-' + ('0' + (date.getUTCMonth() + 1)).slice(-2) + '-' + ('0' + date.getUTCDate()).slice(-2);
                        res.data.result[i].acc2g1 = beijingDate;
                    }
                    if (res.data.result[i].acb213 == null || res.data.result[i].acb213 == '') {
                        res.data.result[i].acb213 = 'OK';
                    } else {
                        res.data.result[i].acb213 = res.data.result[i].acb213 / 1000 + 'k';
                    }
                    if (res.data.result[i].acb214 == null || res.data.result[i].acb214 == '') {
                        res.data.result[i].acb214 = 'OK';
                    } else {
                        res.data.result[i].acb214 = res.data.result[i].acb214 / 1000 + 'k';
                    }
                }
                if (self.data.pageNo == 1) {
                    list = res.data.result;
                } else {
                    var templist = self.data.result;
                    for (var i = 0; i < templist.length; ++i) {
                        list.push(templist[i]);
                    }
                }
                self.setData({
                    positionlist: list,
                    totalCount: res.data.total,
                    showLoadMore: false
                });
            }
        }
    });
    uni.stopPullDownRefresh();
};

改完之后:(其中self.data.pageNo需要改为self.pageNo,并且调用该方法的地方需要改为this.getCc2glist调用)

methods: {
		getCc2glist : function (self) {
		    uni.request({
		        url: app.globalData.urlConfig.jobBaseUrl + '/job/person/candidate/getVCc2gCb21Page',
		        // url: app.urlConfig.jobBaseUrl+'/job/person/candidate/getVCc2gCb21PageDes',
		        data: {
		            acb2ga: 1,
		            aac001: uni.getStorageSync('userinfo').businessid,
		            pageNo: self.pageNo,
		            pageSize: 20
		        },
		        header: app.globalData.getHeader(),
		        method: 'POST',
		        success: function (res) {
		            if (res.statusCode == 401 || res.statusCode == 403) {
		                app.globalData.handleTokenExpire();
		            } else {
		                for (var i = 0; i < res.data.result.length; i++) {
		                    var acc2g1_ = res.data.result[i].acc2g1;
		                    if (acc2g1_ != null && acc2g1_ != '') {
		                        const timeString = acc2g1_;
		                        const date = new Date(timeString);
		                        // 转换为北京时间(UTC+8)
		                        date.setUTCHours(date.getUTCHours() + 8);
		                        // 获取日期部分
		                        const beijingDate = date.getUTCFullYear() + '-' + ('0' + (date.getUTCMonth() + 1)).slice(-2) + '-' + ('0' + date.getUTCDate()).slice(-2);
		                        res.data.result[i].acc2g1 = beijingDate;
		                    }
		                    if (res.data.result[i].acb213 == null || res.data.result[i].acb213 == '') {
		                        res.data.result[i].acb213 = 'OK';
		                    } else {
		                        res.data.result[i].acb213 = res.data.result[i].acb213 / 1000 + 'k';
		                    }
		                    if (res.data.result[i].acb214 == null || res.data.result[i].acb214 == '') {
		                        res.data.result[i].acb214 = 'OK';
		                    } else {
		                        res.data.result[i].acb214 = res.data.result[i].acb214 / 1000 + 'k';
		                    }
		                }
		                if (self.pageNo == 1) {
		                    list = res.data.result;
		                } else {
		                    var templist = self.result;
		                    for (var i = 0; i < templist.length; ++i) {
		                        list.push(templist[i]);
		                    }
		                }
		                self.setData({
		                    positionlist: list,
		                    totalCount: res.data.total,
		                    showLoadMore: false
		                });
		            }
		        }
		    });
		    uni.stopPullDownRefresh();
		},
}

12. 使用wxs报错 #

var getPersonEvalStatus = function (eval, acd707,ace751) {
  console.log('============================eval='+eval);
  console.log('============================acd707='+acd707);
  console.log('============================ace751='+ace751);
  var currentTime = getDate();
  var acd707Time = getDate(acd707);
  if(ace751 == '审核通过'){
    if (acd707Time > currentTime) {
      return '该活动进行中';
    } else {
      return eval === '1' ? '查看评价' : '立即评价';
    }
  }else{
    return '审核通过才能评价';
  }
};

var getCompanyEvalStatus = function (eval, acd707) {
  console.log('============================eval='+eval);
  console.log('============================acd707='+acd707);
  var currentTime = getDate();
  var acd707Time = getDate(acd707);
  if (acd707Time > currentTime) {
    return '该活动进行中';
  } else {
    return eval === '1' ? '查看评价' : '立即评价';
  }
};

module.exports = {
  getPersonEvalStatus: getPersonEvalStatus,
  getCompanyEvalStatus: getCompanyEvalStatus
};

调试好几遍,真是无语。问题出在 rtw_eval.wxs 文件中使用了 eval 作为参数名,而 eval 是 JavaScript 中的一个保留字,在严格模式下不能用作变量名或参数名。

改成下面即可:

var getPersonEvalStatus = function (evaluation, acd707,ace751) {
    console.log('============================evaluation='+evaluation);
    console.log('============================acd707='+acd707);
    console.log('============================ace751='+ace751);
    var currentTime = getDate();
    var acd707Time = getDate(acd707);
    if(ace751 == '审核通过'){
        if (acd707Time > currentTime) {
            return '该活动进行中';
        } else {
        return evaluation === '1' ? '查看评价' : '立即评价';
        }
    }else{
        return '审核通过才能评价';
    }
};

var getCompanyEvalStatus = function (evaluation, acd707) {
    console.log('============================evaluation='+evaluation);
    console.log('============================acd707='+acd707);
    var currentTime = getDate();
    var acd707Time = getDate(acd707);
    if (acd707Time > currentTime) {
        return '该活动进行中';
    } else {
    return evaluation === '1' ? '查看评价' : '立即评价';
    }
};

module.exports = {
  getPersonEvalStatus: getPersonEvalStatus,
  getCompanyEvalStatus: getCompanyEvalStatus
};

13. 使用腾讯地图,markers不显示问题 #

麻了麻了,这个问题调了1个多小时,竟然就是因为图片url的问题!

问题描述:使用腾讯地图,markers不显示

比如:注意iconPath的url,这个url不是static下的

<template>
  <view>
    <view class="page-body">
      <view class="page-section page-section-gap">
        <map style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="covers">
        </map>
      </view>
    </view>
  </view>
</template>
<script>
  export default {
    data() {
      return {
        id:0, // 使用 marker点击事件 需要填写id
        title: 'map',
        latitude: 39.909,
        longitude: 116.39742,
        covers: [{
          latitude: 39.909,
          longitude: 116.39742,
          iconPath: '../../../images/map/icon_company.png'
        }, {
          latitude: 39.90,
          longitude: 116.39,
          iconPath: '../../../images/map/icon_company.png'
        }]
      }
    },
    methods: {

    }
  }
</script>

改写成这个版本就好用了

<template>
	<view>
		<view class="page-body">
			<view class="page-section page-section-gap">
				<map style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="covers">
				</map>
			</view>
		</view>
	</view>
</template>
<script>
export default {
	data() {
		return {
			id:0, // 使用 marker点击事件 需要填写id
			title: 'map',
			latitude: 39.909,
			longitude: 116.39742,
			covers: [{
				latitude: 39.909,
				longitude: 116.39742,
				iconPath: '../../../static/images/map/icon_company.png'
			}, {
				latitude: 39.90,
				longitude: 116.39,
				iconPath: '../../../static/images/map/icon_company.png'
			}]
		}
	},
	methods: {

	}
}
</script>

总结

  1. uniapp使用map标记点markers必须要有iconPath属性;
  2. iconPath引用的本地图片必须是static文件夹下的。

项目代码:

<template>
    <view>
        <!-- pages/website/job/job_map/map.wxml -->
        <!-- <view class="page">
    <view class="page__bd">
        <view class="map-search" bindtap="toSearch">搜索</view>
    </view>
</view> -->
        <view class="dv-top">
            <image :src="fdj" class="fdj" />
            <input type="text" class="dv-top-a" placeholder-class="input-placeholder" placeholder="输入关键字" @tap="search" />
            <view class="dv-top-b" @tap="search">搜索</view>
        </view>
        <view class="dv-dw" @tap="toMyLocation">
            <view class="item">
                <image :src="dingwei" />
                <view class="txt">定位</view>
            </view>
        </view>
        <!-- <view class="tab-condition">
     <view class="condition-o {{searchType=='1'? 'cdact' : ''}}" bindtap="doSearch1" >职位信息</view>
     <view class="condition-o {{searchType=='2'? 'cdact' : ''}}" bindtap="doSearch2" >公共就业服务机构</view>
     <view class="condition-o {{searchType=='3'? 'cdact' : ''}}" bindtap="doSearch3" >零工市场</view>
  </view> -->
        <map
            id="demoMap"
            :min-scale="minScale"
            @updated="bindupdated"
            @regionchange="regionchange"
            @tap="closeView"
            :setting="setting"
            @callouttap="callouttap"
            :longitude="longitude"
            :latitude="latitude"
            :scale="scale"
            :markers="markers"
            :style="'width:' + mapWidth + 'px;height:' + mapHeight + 'px;'"
            class="company-map"
        ></map>
        <!-- <image bindtap="toMyLocation" src="{{location}}" class="my-location {{halfshow?'deviation':''}}"></image> -->

        <!-- 职位view -->
        <view v-if="isPosition" class="bottom-view">
            <view class="card-box" @tap="halfshowclick" :data-ed="halfshowInfo.acb200">
                <image class="img-logo" :src="halfshowInfo.logoUrl" mode="aspectfill"></image>
                <view class="info-part">
                    <view class="row company-name">{{ halfshowInfo.content }}</view>
                    <view class="row">
                        <view class="inline btn emp-count" v-if="halfshowInfo.aab056 != null && halfshowInfo.aab056 != undefined">{{ halfshowInfo.aab056 }}</view>
                        <view class="inline btn industry" v-if="halfshowInfo.aab022 != null && halfshowInfo.aab022 != undefined">{{ halfshowInfo.aab022 }}</view>
                        <view class="inline btn business-type" v-if="halfshowInfo.aab019 != null && halfshowInfo.aab019 != undefined">{{ halfshowInfo.aab019 }}</view>
                    </view>
                    <view class="row">
                        <view class="inline position-count">在招职位{{ halfshowInfo.positionCount }}</view>
                    </view>
                    <view class="row" @tap.stop.prevent="openMap">
                        <image class="location-img" :src="locationImg"></image>
                        {{ halfshowInfo.aae006 }}
                    </view>
                </view>
            </view>
        </view>

        <!-- 服务机构/零工市场view -->
        <view v-if="isFwjg" class="bottom-view">
            <view class="card-box" :data-ed="halfshowInfo.adc011">
                <image class="img-logo" :src="halfshowInfo.logoUrl" mode="aspectfill"></image>
                <view class="info-part">
                    <view class="row company-name">{{ halfshowInfo.content }}</view>
                    <view class="row">
                        <view class="inline position-count">联系电话:{{ halfshowInfo.aae005 }}</view>
                    </view>
                    <view class="row" @tap.stop.prevent="openMap">
                        到这里去
                        <image class="location-img" :src="locationImg"></image>
                        {{ halfshowInfo.acd014 }}
                    </view>
                </view>
            </view>
        </view>

        <!-- 页底tab切换 -->
        <tabBar selected="2"></tabBar>
    </view>
</template>

<script>
import tabBar from '@/components/custom-tab-bar2/custom-tab-bar2';
const app = getApp();
var code = require('../../../components/code/aa10.js');
var util = require('../../../components/code/util');
// pages/website/job/agent/map.js
var locationData = [];
export default {
    components: {
        tabBar
    },
    data() {
        return {
            location: app.globalData.imgurl + '/rlzy-location.png',
            fdj: app.globalData.imgurl + '/map-fdj.png',
            dingwei: app.globalData.imgurl + '/dingwei.png',
            distance: 2,
            nowLongitude: '',
            nowLatitude: '',
            longitude: 119.317219,
            latitude: 26.093407,
            scale: '12',
            minScale: 7,
            markers: [],

            setting: {
                showLocation: true
            },

            halfshow: false,
            isPosition: false,
            isFwjg: false,

            halfshowInfo: {
                acb200: '',
                logoUrl: '',
                content: '',
                aab056: '',
                aab022: '',
                aab019: '',
                positionCount: '',
                adc011: '',
                aae005: ''
            },

            locationImg: app.globalData.imgurl + '/compos.png',
            inputShowed: false,
            inputVal: '',
            tablist: app.globalData.tablist,
            searchType: '',
            range: '',
            acd011: '',
            aca111: '',
            aab022: '',
            aab004: '',
            mapHeight: '',
            mapWidth: '',
            undefined: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        that.setData({
            range: options.ssfw,
            acd011: options.acd011,
            aca111: options.aca111,
            aab022: options.aab022,
            aab004: options.aab004,
            searchType: '1'
        });
        code.init(that);
        that.initMap(); // 初始化地图信息
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        var that = this;
        that.getCompanyLocationDataList(); // 获取公司列表
        /**
    _this.toMyLocation(); // 纠正定位偏移[真机调试会出现定位偏移,模拟器不影响]
  wx.getLocation({
    type: 'wgs84',
    success(res) {
      console.log(res);
      _this.setData({
        longitude: res.longitude,
        latitude: res.latitude
      });
       _this.getCompanyLocationDataList(); // 获取公司列表
    }
  })
      **/
    },
    methods: {
        /**
         * 滑块滑动事件
         * @param {*} e
         */
        bindchange: function (e) {
            var distance = e.detail.value;
            this.distance = distance;
            console.log('距离:' + distance + 'km');
        },

        /**
         * 获取所有单位地图信息
         */
        getCompanyLocationDataList: function () {
            var that = this;
            var demoMap = uni.createMapContext('demoMap');
            demoMap.getRegion({
                success: function (res) {
                    var laloInfo = res;
                    locationData = [];
                    if (laloInfo) {
                        if (that.searchType == '1') {
                            //职位搜索
                            console.log(that.aab004 + '!!!!!!职位搜索查询---');
                            uni.request({
                                url: app.globalData.urlConfig.jobBaseUrl + '/website/job/index/getVCb21MapPage',
                                method: 'POST',
                                data: {
                                    selname: '0',
                                    aca111: that.aca111,
                                    aab022: that.aab022,
                                    addkey: '福建省就业服务管理局',
                                    // "lnglat":"117.106448,36.668451",
                                    lnglat: that.longitude + ',' + that.latitude,
                                    pageNo: '1',
                                    pageSize: '50',
                                    aab004: that.aab004
                                },
                                success: function (res) {
                                    //  locationData = res.data
                                    let newData = [];
                                    let converData = res.data.result;
                                    for (let i = 0; i < converData.length; i++) {
                                        let qqMap = util.bMapTransqqMap(parseFloat(converData[i].gpsx), parseFloat(converData[i].gpsy));
                                        converData[i].latitude = qqMap.latitude;
                                        converData[i].longitude = qqMap.longitude;
                                        converData[i].content = converData[i].aab004;
                                        converData[i].display = 'ALWAYS';
                                        converData[i].padding = 10;
                                        converData[i].aab0a0 = converData[i].ylogo;
                                        converData[i].positionCount = converData[i].vcb21List.total;
                                        let obj = {
                                            callout: converData[i],
                                            id: i + 1,
                                            latitude: converData[i].latitude,
                                            longitude: converData[i].longitude
                                        };
                                        newData.push(obj);
                                    }
                                    locationData = newData;
                                    that.initMarkers(); // 初始化markers信息
                                }
                            });
                        } else {
                            //就业服务机构搜索
                            console.log(that.acd011 + '!!!!!!就业服务机构查询---');
                            uni.request({
                                url: app.globalData.urlConfig.jobBaseUrl + '/website/job/index/getVCd01Page',
                                method: 'POST',
                                data: {
                                    selname: '0',
                                    addkey: '福建省就业服务管理局',
                                    // "lnglat":"117.106448,36.668451",
                                    lnglat: that.longitude + ',' + that.latitude,
                                    // "lnglat":"121.5392082709998,38.86856341547656",
                                    pageNo: '1',
                                    pageSize: '50',
                                    acd011: that.acd011,
                                    range: that.range,
                                    aaf011: that.searchType == '2' ? '1' : '2'
                                },
                                success: function (res) {
                                    //  locationData = res.data
                                    let newData = [];
                                    let converData = res.data.result;
                                    for (let i = 0; i < converData.length; i++) {
                                        let qqMap = util.bMapTransqqMap(parseFloat(converData[i].gpsx), parseFloat(converData[i].gpsy));
                                        converData[i].latitude = qqMap.latitude;
                                        converData[i].longitude = qqMap.longitude;
                                        converData[i].content = converData[i].acd011;
                                        converData[i].display = 'ALWAYS';
                                        converData[i].padding = 10;
                                        converData[i].aab0a0 = converData[i].ylogo;
                                        converData[i].acd014 = converData[i].acd014;
                                        let obj = {
                                            callout: converData[i],
                                            id: i + 1,
                                            latitude: converData[i].latitude,
                                            longitude: converData[i].longitude
                                        };
                                        newData.push(obj);
                                    }
                                    locationData = newData;
                                    that.initMarkers(); // 初始化markers信息
                                }
                            });
                        }
                    }
                }
            });
        },

        /**
         * 获取地图范围内的单位信息
         */
        initMarkers: function () {
            var that = this;
            var demoMap = uni.createMapContext('demoMap');
            demoMap.getRegion({
                success: function (res) {
                    var laloInfo = res;
                    if (res) {
                        // _this.setData({markers: _this.getSNLocation(laloInfo)}); // 南北坐标范围定位辅助调试用
                        // 过滤markers数据
                        var markers = that.filterMarkers(locationData, laloInfo);
                        if (markers != undefined && markers.length > 0) {
							markers.forEach(function(item) {
								item.iconPath = '/static/images/map/icon_company.png';
								item.width = 38;
								item.height = 46;
							});
                            that.setData({
                                markers: markers
                            });
							demoMap.addMarkers({
								markers,
								clear: true,
								complete(res) {
									console.log('addMarkers', res);
								}
							});
                        }
                    }
                }
            });
        },

        /**
         * 过滤markers信息
         * @param {*} markers
         */
        filterMarkers: function (markersInfo, laloInfo) {
            var that = this;
            var markers;
            if (markersInfo && markersInfo instanceof Array && markersInfo.length > 0) {
                markers = markersInfo.filter(function (item, index) {
                    if (that.isInRange(item.latitude, item.longitude, laloInfo.southwest, laloInfo.northeast)) {
                        return item;
                    }
                });
            }
            return markers;
        },

        /**
         * 单位经纬度是否在范围内
         * @param {*} la
         * @param {*} lo
         * @param {*} southwest
         * @param {*} northeast
         */
        isInRange: function (la, lo, southwest, northeast) {
            var rlt = true;
            // if (southwest.latitude.toFixed(6) <= la.toFixed(6) &&
            //   la.toFixed(6) <= northeast.latitude.toFixed(6) &&
            //   southwest.longitude.toFixed(6) <= lo.toFixed(6) &&
            //   lo.toFixed(6) <= northeast.longitude.toFixed(6)) {
            //   rlt = true;
            // }
            return rlt;
        },

        /**
         * 计算范围内的坐标信息范围boolean值
         * @param {*} distance
         * @param {*} la
         * @param {*} lo
         */
        calcRange: function (la, lo) {
            var demoMap = uni.createMapContext('demoMap');
            var scale = demoMap.getScale();
            var rlt = false;
            var that = this;
            var la1 = that.nowLatitude;
            var lo1 = that.nowLongitude;
            var distance = that.distance;
            // 处理后的markers数据
            var markers = locationData.filter(function (item, index) {
                var calcDistance = that.distanceFun(la1, lo1, item.latitude, item.longitude);
                if (that.distance > calcDistance) {
                    return item;
                }
            });
            if (markers.length > 0) {
                that.setData({
                    markers: markers
                });
            }
            return rlt;
        },

        /**
         * 通过亮点经纬度计算距离(废弃)
         * @param {*} la1
         * @param {*} lo1
         * @param {*} la2
         * @param {*} lo2
         */
        distanceFun: function (la1, lo1, la2, lo2) {
            var La1 = (la1 * Math.PI) / 180;
            var La2 = (la2 * Math.PI) / 180;
            var La3 = La1 - La2;
            var Lb3 = (lo1 * Math.PI) / 180 - (lo2 * Math.PI) / 180;
            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
            s = s * 6378.137; //地球半径
            s = Math.round(s * 10000) / 10000;
            //console.log("计算结果", s);
            return s;
        },

        // 点击 地图标记点
        callouttap: function (e) {
            var marker = this.getMarkerByMarkerId(e.detail.markerId);
            var halfshowInfo = {};
            // if(this.data.searchType=="1"){
            //职位搜索
            halfshowInfo.acb200 = marker.callout.acb200;
            halfshowInfo.aab001 = marker.callout.aab001;
            halfshowInfo.content = marker.callout.content;
            halfshowInfo.aae006 = marker.callout.aae006;
            halfshowInfo.aab022 = marker.callout.aab022;
            halfshowInfo.aab056 = marker.callout.aab056;
            halfshowInfo.aab019 = marker.callout.aab019;
            halfshowInfo.aab022 = code.getCodeValue(this.show_arr_aab022, halfshowInfo.aab022);
            halfshowInfo.positionCount = marker.callout.positionCount;
            if (halfshowInfo.aab056 != null) {
                halfshowInfo.aab056 = code.getCodeValue(this.show_arr_aab056, halfshowInfo.aab056);
            }
            if (halfshowInfo.aab019 != null) {
                halfshowInfo.aab019 = code.getCodeValue(this.show_arr_aab019, halfshowInfo.aab019);
            }
            halfshowInfo.logoUrl =
                app.globalData.urlConfig.resourceReadBaseUrl +
                '/resource/download/downLoadByFk?type=view&fkid=' +
                marker.callout.aab0a0 +
                '&fktable=AB0A&fktablefield=AAB0A0&level=0';
            halfshowInfo.latitude = marker.latitude;
            halfshowInfo.longitude = marker.longitude;
            this.setData({
                halfshowInfo: halfshowInfo,
                // halfshow: true,
                isPosition: true,
                isFwjg: false,
                latitude: marker.latitude,
                longitude: marker.longitude
            });
            // }
        },

        callouttapPosition: function (e) {
            var marker = this.getMarkerByMarkerId(e.detail.markerId);
            var halfshowInfo = {};
            halfshowInfo.acb200 = marker.callout.acb200;
            halfshowInfo.aab001 = marker.callout.aab001;
            halfshowInfo.content = marker.callout.content;
            halfshowInfo.aae006 = marker.callout.aae006;
            halfshowInfo.aab022 = marker.callout.aab022;
            halfshowInfo.aab056 = marker.callout.aab056;
            halfshowInfo.aab019 = marker.callout.aab019;
            halfshowInfo.aab022 = code.getCodeValue(this.show_arr_aab022, halfshowInfo.aab022);
            halfshowInfo.positionCount = marker.callout.positionCount;
            if (halfshowInfo.aab056 != null) {
                halfshowInfo.aab056 = code.getCodeValue(this.show_arr_aab056, halfshowInfo.aab056);
            }
            if (halfshowInfo.aab019 != null) {
                halfshowInfo.aab019 = code.getCodeValue(this.show_arr_aab019, halfshowInfo.aab019);
            }
            halfshowInfo.logoUrl =
                app.globalData.urlConfig.resourceReadBaseUrl +
                '/resource/download/downLoadByFk?type=view&fkid=' +
                marker.callout.aab0a0 +
                '&fktable=AB0A&fktablefield=AAB0A0&level=0';
            halfshowInfo.latitude = marker.latitude;
            halfshowInfo.longitude = marker.longitude;
            this.setData({
                halfshowInfo: halfshowInfo,
                halfshow: true,
                latitude: marker.latitude,
                longitude: marker.longitude
            });
        },

        toMyLocation: function (e) {
            uni.createMapContext('demoMap').moveToLocation();
        },

        search: function () {
            uni.navigateTo({
                url: '/packageRlzy/website/job/job_list/jobList'
            });
        },

        closeView: function (e) {
            this.setData({
                halfshow: false
            });
            this.halfshowInfo = {};
        },

        bindupdated: function () {
            var that = this;
            //console.log("地图更新成功");
        },

        /**
         * 初始化地图信息
         */
        initMap: function () {
            var result = uni.getSystemInfoSync(); // 获取系统信息
            var h = result.windowHeight;
            var w = result.windowWidth;
            this.setData({
                mapHeight: h,
                mapWidth: w
            });
        },

        /**
         * rpx转换px
         * @param {*} rpx
         */
        rpxToPx: function (rpx) {
            return (rpx / 750) * uni.getSystemInfoSync().windowWidth;
        },

        getMarkerByMarkerId(markerId) {
            var marker;
            marker = this.markers.find(function (item) {
                if (item.id == markerId) {
                    return item;
                }
            });
            return marker;
        },

        toSearch: function () {
            uni.navigateTo({
                url: './mapsearch/mapsearch?searchtype=' + this.searchType
            });
        },

        /**
         * 点击单位详细地址,跳转地图
         */
        openMap: function () {
            let latitude = this.halfshowInfo.latitude;
            let longitude = this.halfshowInfo.longitude;
            if (latitude == null && longitude == null) {
                uni.showToast({
                    title: '单位暂未提供坐标信息',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                uni.openLocation({
                    latitude,
                    longitude,
                    scale: 15
                });
            }
            return false;
        },

        halfshowclick: function (e) {
            uni.navigateTo({
                url: '/packageRlzy/website/job/company_detail/company_detail?acb200=' + this.halfshowInfo.acb200
            });
        },

        callPhone: function () {
            let phonenumber = this.halfshowInfo.aae005;
            if (phonenumber) {
                uni.makePhoneCall({
                    phoneNumber: phonenumber
                });
            }
        },

        tabChange: function (e) {
            app.globalData.toTabber(e);
        },

        doSearch1: function (type) {
            // wx.redirectTo({
            //   url: '/pages/website/job/agent/map?searchType=1'
            // })
            var that = this;
            that.setData({
                searchType: '1',
                isPosition: false,
                isFwjg: false
            });
            var demoMap = uni.createMapContext('demoMap');
            demoMap.getRegion({
                success: function (res) {
                    var laloInfo = res;
                    if (laloInfo) {
                        locationData = [];
                        console.log(that.aab004 + '!!!!!!---');
                        uni.request({
                            url: app.globalData.urlConfig.jobBaseUrl + '/website/job/index/getVCb21MapPage',
                            method: 'POST',
                            data: {
                                selname: '0',
                                aca111: that.aca111,
                                aab022: that.aab022,
                                addkey: '福建省就业服务管理局',
                                // "lnglat":"117.106448,36.668451",
                                lnglat: that.longitude + ',' + that.latitude,
                                pageNo: '1',
                                pageSize: '50',
                                aab004: that.aab004
                            },
                            success: function (res) {
                                //  locationData = res.data
                                let newData = [];
                                let converData = res.data.result;
                                for (let i = 0; i < converData.length; i++) {
                                    let qqMap = util.bMapTransqqMap(parseFloat(converData[i].gpsx), parseFloat(converData[i].gpsy));
                                    converData[i].latitude = qqMap.latitude;
                                    converData[i].longitude = qqMap.longitude;
                                    converData[i].content = converData[i].aab004;
                                    converData[i].display = 'ALWAYS';
                                    converData[i].padding = 10;
                                    converData[i].aab0a0 = converData[i].ylogo;
                                    converData[i].positionCount = converData[i].vcb21List.total;
                                    let obj = {
                                        callout: converData[i],
                                        id: i + 1,
                                        latitude: converData[i].latitude,
                                        longitude: converData[i].longitude
                                    };
                                    newData.push(obj);
                                }
                                locationData = newData;
                                that.initMarkers(); // 初始化markers信息
                            }
                        });
                    }
                }
            });
        },

        regionchange() {
            console.log('占位:函数 regionchange 未声明');
        }
    }
};
</script>
<style>
@import './map.css';
</style>

14. 不支持mp-dialog,替换方案 #

原来的代码:

<mp-dialog title="提示消息" :show="dialogShow" @buttontap="tapDialogButton()" :buttons="buttons">
    <view>{{ dialogCon }}</view>
</mp-dialog> 

14.1 使用uni.showModal直接替换 #

uni.showModal({
    title: '保存成功',
    icon: 'success',
    duration: 2000,
    showCancel: false,
    success: function (res1) {
        this.tapDialogButton();
    }
});

14.2 使用uni-popup插件 #

  1. 安装:

[[uniApp:使用HBuilder导入插件uni-popup]]

  1. 使用:
  • 所有设置dialogShow为true的换成调用openPopup()
  • 所有设置dialogShow为false的换成调用closePopup()
<uni-popup ref="popup" type="dialog">
  <uni-popup-dialog mode="base" :content="dialogCon" :duration="0" :before-close="true" @close="closePopup" @confirm="tapDialogButton()"></uni-popup-dialog>
</uni-popup>

import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';

openPopup() {
   this.$refs.popup.open();
},
 closePopup() {
   this.$refs.popup.close();
},

15. 部署 #

15.1 本地开发 #

15.2 部署服务器 #

[[uniApp打包成H5部署到服务器教程]]

访问:http://10.0.66.101:3322/rlzyh5/index.html