Vue项目调用腾讯地图服务(关键词提示服务)及使用axios的跨域问题

一,需求:

输入学校名称,调用腾讯地图的关键词提示服务选择学校的地址,项目需要学校地址的坐标。

腾讯地图服务官网api

二,实现:

(一)使用axios请求接口:

schoolNameChange(e) {

      const that = this;

      const schoolName = e.target.value;

      this.schoolName = schoolName;

      this.$axios.get("https://apis.map.qq.com/ws/place/v1/suggestion/", {

        region: "中国",

        keyword: schoolName,

        key: "4K6BZ-EJ5ED-3524H-HYYVS-3QQ3J-JUFVI",

      })

        .then(res => {

          that.addressArr = res.data;

        })

        .catch(err => {

          console.log("catch", err);

        });

    }

然后就遇到跨域问题:

(二)解决跨域问题:

经过一番查找,找到了一个方法。使用插件 vue-jsonp,解决跨域问题。

1,安装vue-jsonp,

npm install vue-jsonp

2,在项目的main.js中引用,使用vue-jsonp

import VueJsonp from 'vue-jsonp'

Vue.use(VueJsonp)

3,将axios请求变为jsonp请求

this.$axios.get("https://apis.map.qq.com/ws/place/v1/suggestion/", {

        region: "中国",

        keyword: schoolName,

        key: "4K6BZ-EJ5ED-3524H-HYYVS-3QQ3J-JUFVI",

      })

4,腾讯地图默认的请求是json,在请求的时候需要加 output:"jsonp"

5,完整的请求函数

schoolNameChange(e) {

      const that = this;

      const schoolName = e.target.value;

      this.schoolName = schoolName;

      this.$axios.get("https://apis.map.qq.com/ws/place/v1/suggestion/", {

        region: "中国",

        keyword: schoolName,

        key: "4K6BZ-EJ5ED-3524H-HYYVS-3QQ3J-JUFVI",

        output:"jsonp"

      })

        .then(res => {

          that.addressArr = res.data;

        })

        .catch(err => {

          console.log("catch", err);

        });

    }

注意:

上文中所有的key都是假的,无法使用,请换成自己的key

效果图:

发布了58 篇原创文章 · 获赞 41 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/Zeng__Yi/article/details/103918915