一,理论
1.注册,浏览器搜索腾讯位置服务点进去,右上角有登录没有账号的注册一下。
2.点击右上角的控制台,再点击应用管理,创建一个应用,名字随便起。在创建好的应用右边有一个添加key,勾选上webServiceApi创建好了以后会有一个key属性,复制好,腾讯地图每个api都需要这个key。
3.官方的api在开发文档当中,选择WebService API,右侧边栏选择批量距离计算。
4.https://apis.map.qq.com/ws/distance/v1/matrix可以看到是get请求,必传参数有四个,
分别是key就是上面创建app的key,复制粘贴即可,from就是用户本身的坐标,to是一个字符串拼接,
一般来说需要前端进行一些处理,mode是一个计算方式根据传递参数不同,计算需多少时间,如果不需要算多少时间,只需要距离,三个参数哪一个都一样。
二:实战
1.获取用户ip地址, navigator.geolocation.getCurrentPosition是浏览器给我们提供的方法,使用以后会返回经纬度,由于这是一个异步的方法所以最好搭配promise async await等方法使用,下面是promise写法。
new Promise((reslove, rej) => {
navigator.geolocation.getCurrentPosition(function succ(res) {
reslove(res);
});
}).then(resdata => {
});
2.处理参数,我这是一个Vue项目,使用的是axios。不过在请求前需处理参数。
gpsAddress: "116.40245266652492:39.90433862375979"后端返回的经纬度,但是看api得知,
我需要你将经纬度之间用逗号分割,而不是冒号,并且多个ip地址用分号分割,都需要处理。
this.$store.state.cineamlist.forEach((item, index) => {
if (index < 5) {
str +=
`${item.gpsAddress}`.split(":")[1] +
"," +
`${item.gpsAddress}`.split(":")[0] +
";";
}
});
采用split进行分割在之间加上逗号,在结尾加上分号。to参数处理完毕。mode和key都是死值,
就不细说了,最后一个是from参数是本身的坐标上面的获取经纬度操作以及完成了,经纬度在coords.latitude和coords.longitude将它们拼接起来用,分割经纬度,注意不要有分号,否则会说form参数有问题。最后代码奉上。
new Promise((reslove, rej) => {
navigator.geolocation.getCurrentPosition(function succ(res) {
reslove(res);
});
}).then(resdata => {
let str = ""; //存储id地址
this.$store.state.cineamlist.forEach((item, index) => {
if (index < 5) {
str +=
`${item.gpsAddress}`.split(":")[1] +
"," +
`${item.gpsAddress}`.split(":")[0] +
";";
}
}); //对影院id地址进行处理
str = str.slice(0, str.length - 1); //删除最后一位的分号
axios({
method: "get",
url:
"/logo?mode=driving&from=" +
resdata.coords.latitude +
"," +
resdata.coords.longitude +
"&to=" +
str +
"" +
"&key=WX2BZ-4E2KU-X6MVH-B2KTN-4N7F3-E5B7L"
}).then(res => {
if (res.data.status === 0) {
let IpLIist = res.data.result.rows[0].elements;
let list = this.$store.state.cineamlist.map((item, index) => {
if (index < 5) {
item.juli = IpLIist[index];
}
return item;
});
this.cinemaList = list;
this.selectAddressArr = this.$store.state.address;
this.selectAddress = this.selectAddressArr[0];
}
});
});
补充一句,这个to不能太长,并且最好只携带5个ip地址,太多ip地址,需向腾讯购买使用数量。