记录一次用uniapp在h5和微信小程序显示地图并获取当前位置

其中小程序是使用的是map组件显示地图;用uni.getLocation获取当前位置
h5网页使用是引入高德的地图;用高德地图的getCurrentPosition获取当前位置, 并使用了import和通过script标签的两种方式引入高德的js

1. 在高德开发平台注册账号

代码里的key和jsCode是我申请好的
下面是申请链接
https://console.amap.com/dev/key/app

2.代码如下

<template>
  <view class="content">
<!--    #ifdef MP-WEIXIN-->
    <map class="map" :latitude="latitude" :longitude="longitude">
    </map>
<!--    #endif-->
    <!-- #ifdef H5-->
    <div id="container" class="map"></div>
    <div id="status"></div>
    <div id="result"></div>
    <!-- #endif-->
  </view>
</template>

<script>
  //#ifdef H5
  window._AMapSecurityConfig = {
      securityJsCode:'dbcb154b2ba329d96e9a219e32f424b7',
  }
  import AMapLoader from '@amap/amap-jsapi-loader';
  //#endif
export default {
  data() {
    return {
      latitude: 1,
      longitude: 1,
      covers: [],
    }
  },
  onLoad() {
    //#ifdef H5
    this.loadMapJsH52()
    //#endif

    //#ifdef MP-WEIXIN
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
    uni.getSetting({
      success:(res) => {
        console.log('res.authSetting', res.authSetting)
        if (!res.authSetting['scope.userLocation']) {
          uni.authorize({
            scope: 'scope.userLocation',
            success: () => {
              // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
              this.getLocation()
            },
            fail: () => {
              console.log('authorize fail')
            }
          })
        } else {
          this.getLocation()
        }
      }
    })
    //#endif
  },
  methods: {
    // 引入方式1
    loadMapJsH51 () {
      //解析定位结果
      function onComplete(data) {
        document.getElementById('status').innerHTML='定位成功'
        var str = [];
        str.push('定位结果:' + data.position);
        str.push('定位类别:' + data.location_type);
        if(data.accuracy){
          str.push('精度:' + data.accuracy + ' 米');
        }//如为IP精确定位结果则没有精度信息
        str.push('是否经过偏移:' + (data.isConverted ? '是' : '否'));
        document.getElementById('result').innerHTML = str.join('<br>');
      }
      //解析定位错误信息
      function onError(data) {
        console.log('data', data)
        document.getElementById('status').innerHTML='定位失败'
        document.getElementById('result').innerHTML = '失败原因排查信息:'+data.message;
      }
      window.onLoad1  = function(){
        console.log('window.onLoad1')
        console.log(window.AMap)
        const AMap = window.AMap
        let map = new AMap.Map('container');
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默认:true
            timeout: 100000,          //超过10秒后停止定位,默认:5s
            buttonPosition:'RB',    //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
            zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition(function(status,result){
            if(status=='complete'){
              onComplete(result)
            }else{
              onError(result)
            }
          });
        });
      }
      var url = 'https://webapi.amap.com/maps?v=1.4.15&key=921241a52aee53f57547ce64737c24e7&callback=onLoad1';
      var jsapi = document.createElement('script');
      jsapi.charset = 'utf-8';
      jsapi.src = url;
      document.head.appendChild(jsapi);
    },
    // 引入方式2
    loadMapJsH52 () {
      //解析定位结果
      function onComplete(data) {
        document.getElementById('status').innerHTML='定位成功'
        var str = [];
        str.push('定位结果:' + data.position);
        str.push('定位类别:' + data.location_type);
        if(data.accuracy){
          str.push('精度:' + data.accuracy + ' 米');
        }//如为IP精确定位结果则没有精度信息
        str.push('是否经过偏移:' + (data.isConverted ? '是' : '否'));
        document.getElementById('result').innerHTML = str.join('<br>');
      }
      //解析定位错误信息
      function onError(data) {
        document.getElementById('status').innerHTML='定位失败'
        document.getElementById('result').innerHTML = '失败原因排查信息:'+data.message;
      }
      console.log('AMapLoader', AMapLoader)
      AMapLoader.load({
        "key": "921241a52aee53f57547ce64737c24e7",              // 申请好的Web端开发者Key,首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        "plugins": [],           // 需要使用的的插件列表,如比例尺'AMap.Scale'等
      }).then((AMap)=>{
        let map = new AMap.Map('container');
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默认:true
            timeout: 10000,          //超过10秒后停止定位,默认:5s
            buttonPosition:'RB',    //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
            zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition(function(status,result){
            if(status=='complete'){
              onComplete(result)
            }else{
              onError(result)
            }
          });
        });
      }).catch(e => {
        console.log(e);
      })
    },
    getLocation () {
      uni.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        success: (res) => {
          this.latitude = res.latitude
          this.longitude = res.longitude
          this.covers.push({
            latitude:res.latitude,
            longitude:res.longitude
          })
          console.log('res', res)
        },
        fail: () => {
          console.log('getLocation fail')
        }
      })
    }
  },
}
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: calc(100vh - 100px);
}
.map {
  width: 100%;
  height: 100%;
}
</style>

3.在线体验地址

在我手机上测试是可以获取到当前位置的并且位置也很准确
http://xyhnnx.gitee.io/uni-app-xyh/#/

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值