uniapp使用webview来加载地图达到地图选点功能

2020-08-01 04:24
椰子皮
7114
1
12
移动端

“ uniapp上要做选择地址的功能,顿时感觉有点不好实现,灵光一闪,可以用腾讯地图的选点组件以webview来实现呀 ”

在uniapp中选择地址,本来是想用地图map组件,但看了一下没有比较好的实现方式,于是就想到了用网页来实现;下面看看我的代码吧。

首先我们需要一个html网页,对,就是.html后缀的文件

map.html

复制代码
 <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>地点选择</title>
  </head>
  <body>
    <iframe
      id="mapPage"
      width="100%"
      height="750px"
      frameborder=0
      src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=你的key&referer=myapp">
    </iframe>
    <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.1.js"></script>
    <script type="text/javascript">
      window.addEventListener('message', function (event) {
        var loc = event.data;
        if (loc && loc.module == 'locationPicker') {
          console.log('location', loc);
          uni.postMessage({
            data: loc
          })
        }
      }, false);
    </script>
  </body>
</html>

然后我们拿到这个html地址,例如:可以放到static目录,/static/html/map.html

APP上面map.vue

复制代码
<template>
  <div class="map-warp">
    <!--#ifdef H5-->
    <web-view
      src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=你的key&referer=myapp"
      @message="onMessage">
    </web-view>
    <!--#endif-->

    <!--#ifdef APP-PLUS-->
    <web-view src="/static/html/map.html" @message="onMessage"></web-view>
    <!--#endif-->

	</div>
</template>

<script>
  export default {
  data() {
    return {
      height: uni.getSystemInfoSync().screenHeight,
    }
  },
  onReady() {
    const self = this
    //#ifdef H5
    if (window.isListen) {
      // 防止多次注册addEventListener事件
        return
    }
    window.addEventListener('message', function (event) {
    var loc = event.data;
    if (loc && loc.module == 'locationPicker') {
      console.log('location', loc);
      self.getPositon(loc, self)
    };
      window.isListen = true
      window.removeEventListener('message', function() {}, true)
    }, false)
    //#endif
  },
  methods: {
    onMessage(res) {
      console.log('app接收网页消息:', res.detail.data[0])
      this.getPositon(res.detail.data[0], this)
    },
    getPositon(res, self) {
      uni.$emit('onAddressChange', res)
      setTimeout(function() {
        self.$nav.back()
      }, 1000)
     }
  },
}
</script>

<style scoped lang="scss">
</style>

到此就可以愉快的玩耍了,APP和H5都能使用

觉得不错点个赞哦

赏
支付宝微信
12
关注公众号获取更多内容
vue3.0+typescript使用tinymce富文本编辑器
uniapp去掉安卓启动提示存储权限
共有 1 条评论
发表评论
  • 黑瞳#10096
    2022-09-27 16:28
    山东省潍坊市奎文区
    Windows 10
    Chrome

    H5的话 我的页面为啥加载很慢 大约加载六七秒 有调整的方法吗

    回复
共 1 条 第 1-1 条
每页
10
条
  • 1
不支持canvas