腾讯位置服务计算最佳线路和预估里程和时间(微信小程序)

腾讯位置服务的API:
https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/methodDirection

<map
  id="map"
  :longitude="from.longitude"
  :latitude="from.latitude"
  :style="contentStyle"
  scale="12"
  :enable-traffic="false"
  :show-location="true"
  class="map"
  :polyline="polyline"
  :markers="markers"
></map>

封声明装计算最佳线路的函数

calculateLine: function(ref) {
    qqmapsdk.direction({
        mode: 'driving',
        from: {
            latitude: ref.from.latitude,
            longitude: ref.from.longitude
        },
        to: {
            latitude: ref.to.latitude,
            longitude: ref.to.longitude
        },
        success: function(resp) {
            if (resp.status != 0) {
                uni.showToast({
                    icon: 'error',
                    title: resp.message
                });
                return;
            }
            let route = resp.result.routes[0];
            let distance = route.distance;
            let duration = route.duration;
            let polyline = route.polyline;
            ref.distance = Math.ceil((distance / 1000) * 10) / 10;
            ref.duration = duration;
            let points = ref.formatPolyline(polyline);

            ref.polyline = [
                {
                    points: points,
                    width: 6,
                    color: '#05B473',
                    arrowLine: true
                }
            ];
            ref.markers = [
                {
                    id: 1,
                    latitude: ref.from.latitude,
                    longitude: ref.from.longitude,
                    width: 25,
                    height: 35,
                    anchor: {
                        x: 0.5,
                        y: 0.5
                    },
                    iconPath: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png'
                },
                {
                    id: 2,
                    latitude: ref.to.latitude,
                    longitude: ref.to.longitude,
                    width: 25,
                    height: 35,
                    anchor: {
                        x: 0.5,
                        y: 0.5
                    },
                    iconPath: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png'
                }
            ];
        }
    });
},

在onShow()回调函数中,我们要调用这个封装函数。有的同学说,为什么不在onLoad()函数中调用?如果小程序挂起在后台,过了几分钟,你又切回到小程序,你说是不是应该立即重新计算最佳线路,因为有可能有的路段已经开始堵车了。你觉得onLoad()和onShow()哪个更适合?

onShow: function() {
    let that = this;
    that.calculateLine(that);
}
posted @ 2026-01-12 11:20  hwq1992  阅读(0)  评论(1)    收藏  举报