2022-10-18 uniapp使用高德地图获取定位

解决方案1:编写一段html代码放到线上,然后通过web-view访问从而获取到定位。

h5代码可去这里拿https://www.cnblogs.com/iuniko/p/16801754.html

准备个高德开发者账号这些材料就不说了。

注:必须把h5代码放到线上,uniapp项目中在本地使用web-view打开是获取不到定位的,必须放到线上!

解决方案2(不使用web-view):

怎么把上面方案1的代码放到项目里使用而不借助web-view呢,我们直接把代码里的js放到项目里运行会报错:AMap未定义。

AMap is undefined的解决方案:

找到你的app.vue,在script里面放置下面的代码:

  onLaunch: function() {
    window._AMapSecurityConfig = {
      securityJsCode: "你的高德安全密钥",
    };
    var script = document.createElement("script");
    script.src =
      "https://webapi.amap.com/maps?v=1.4.15&key=你的高德key&plugin=AMap.CitySearch";
    document.head.appendChild(script);
  },

然后,在你的业务里面,找到mounted,放置下面代码:

  mounted() {
    setTimeout(() => {
      var citysearch = new AMap.CitySearch();
      console.log(citysearch);
      //自动获取用户IP,返回当前城市
      citysearch.getLocalCity(function(status, result) {
        console.log(result);
        if (status === "complete" && result.info === "OK") {
          console.log(result.rectangle.split(";")[0].split(","));
          document.getElementById("map").innerHTML =
            result.province + " " + result.city;
          //城市存到本地
          localStorage.setItem("cityLocation", result.city);
        }
      });
    }, 1000);
  },

注意是要给个定时器,不然还是会报未定义,而且你得设置个元素,id为map,当然啦这都是基操。

网上那些说是新建个index.html文件,然后把脚本放里面,接着在manifest.json里面引入,我试了没效果。

posted @ 2022-10-18 10:34  叶乘风  阅读(3416)  评论(0编辑  收藏  举报