问题描述:最近在做微信小程序项目,根据业务需求需要绘制起点到终点的线路图, 但是不论起点和终点的距离有多远都需要将起点和终点 在地图的可视区域内显示,针对这个问题,我采取了以下解决方案,效果图如下所示
xml:
<view class="container">
<view>
<map id="myMap" style="width: 100%; height: {{height}}rpx;" markers="{{markers}}" include-points='{{points}}' polyline="{{polyline}}" ></map>
</view>
</view>
js:
const app = getApp()
var QQMapWX = require('../../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWX({
key: '填写自己的key' // 必填
});
Page({
data: {
height: 568,
markers: [],
polyline: [],
result:[],
points:[]
},
getHeight: function () {
let that = this;
wx.getSystemInfo({
success: function (res) {
let clientHeight = res.windowHeight;
let clientWidth = res.windowWidth;
let ratio = 750 / clientWidth;
let height = clientHeight * ratio;
that.setData({
height: height
});
}
});
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that=this
that.getHeight();
var start = JSON.parse(options.start).lat +","+ JSON.parse(options.start).lng
var end = JSON.parse(options.end).lat + "," + JSON.parse(options.end).lng
that.line(start,end);
var marker = [
{
iconPath: "../../../../images/start.png",
id: 0,
latitude: JSON.parse(options.start).lat,
longitude: JSON.parse(options.start).lng,
width: 23,
height: 33
},
{
iconPath: "../../../../images/end.png",
id: 0,
latitude: JSON.parse(options.end).lat,
longitude: JSON.parse(options.end).lng,
width: 24,
height: 34
}]
var points_=[
{
latitude: JSON.parse(options.start).lat,
longitude: JSON.parse(options.start).lng,
},
{
latitude: JSON.parse(options.end).lat,
longitude: JSON.parse(options.end).lng,
}
]
that.setData({
markers: marker,
points:points_,
})
},
onReady: function () {
this.mapCtx = wx.createMapContext('myMap');
},
line: function (start,end) {
var _this = this
qqmapsdk.direction({
mode: 'driving',//可选值:'driving'(驾车)、'walking'(步行)、'bicycling'(骑行),不填默认:'driving',可不填
from: start,
to: end,
success: function (res,data) {
console.log(res);
var ret = res;
var coors = ret.result.routes[0].polyline, pl = [];
//坐标解压(返回的点串坐标,通过前向差分进行压缩)
var kr = 1000000;
for (var i = 2; i < coors.length; i++) {
coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
}
//将解压后的坐标放入点串数组pl中
for (var i = 0; i < coors.length; i += 2) {
pl.push({ latitude: coors[i], longitude: coors[i + 1] })
}
console.log(pl)
//设置polyline属性,将路线显示出来,将解压坐标第一个数据作为起点
_this.setData({
latitude: pl[0].latitude,
longitude: pl[0].longitude,
polyline: [{
points: pl,
color: "#37C4FF",
width: 4,
dottedLine: false
}]
})
},
fail: function (error) {
console.error(error);
},
complete: function (res) {
console.log(res);
}
});
},
})
- 总结:
- 1不给map添加 longitude 和 latitude属性
- 2.添加属性include-points='{{points}}',points中将起点和终点包括在其中。
- 3.不设置scale