vue项目web端根据腾讯地图获取当前定位并通过关键字搜索地址列表

1.先去腾讯地图开放平台申请一个key 腾讯地图开放平台
在这里插入图片描述
2.在vue初始化时 created函数中调用下面的方法 因为要先拿到当前城市信息比较好用 ,不拿也没关系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
created() {
    this.Tmap();
},
/**
* 腾讯地图获取当前定位
* 只调用此方法就行
 */
Tmap() {
    that = this;
    var geolocation = new qq.maps.Geolocation("HFXBZ-NQSWI-ZGQGW-5URX4-WUXCF-VWFUQ", "mapqq");
    // geolocation.getIpLocation(this.showPosition, this.showErr);
    geolocation.getLocation(this.showPosition, this.showErr); //或者用getLocation精确度比较高
},
showPosition(position) {
    console.log(position);
    // this.latitude = position.lat;
    // this.longitude = position.lng;
    this.city = position.city;
},
showErr() {
    console.log("定位失败");
    this.Tmap(); //定位失败再请求定位,测试使用
},

3.然后在输入框输入关键字(标签代码我就不写了 )要先配置跨域 不然会报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//触发关键词输入提示事件
/**
 * @param {输入值} e
 */
getsuggest: function(e) {
    that = this;
    if (e.length <= 0) {
        //用于接收地址列表的数组,在data声明
        that.addressList = []
        return;
    }
    //在执行这一步之前要配置跨域,不然会报错
    this.$axios
        .get("/api/ws/place/v1/suggestion", {
            params: {
                keyword: e,//关键字
                region: that.city,//当前城市
                key: "HFXBZ-NQSWI-Z"//你申请的key
            }
        })
        .then(res => {
        //成功返回的信息
            console.log(that.city)
            console.log(res);
            that.addressList = res.data.data;
        })
        .catch(err => {
            console.log(err)
            this.$message.error("请求超时");
        });
},

4.最终效果

在这里插入图片描述