美文网首页
Vue获取照片拍摄的地理位置信息

Vue获取照片拍摄的地理位置信息

作者: 赵客缦胡缨v吴钩霜雪明 | 来源:发表于2023-11-23 14:50 被阅读0次

    项目中有个需求:需要在图片上传时获取图片的地理位置信息

    思路分析

    1.先通过exif-js获取图片的经纬度;
    2.将获取到的经纬度使用逆地理编码转化成真实地址

    准备工作

    1.查阅exif-js官网文档
    2.申请高德地图key类型必须为Web服务API

    代码使用

    1.安装exif-js包

    npm install exif-js
    

    2.vue页面代码

    <template>
      <div>
        <img src="../../../assets/img/demo.jpg" style="width:300px;height:300px" ref="img">
        <button @click="getImgLocation">获取图片位置</button>
        <p>{{address}}</p>
      </div>
    </template>
    
    <script>
    import EXIF from 'exif-js'
    import axios from 'axios'
    export default {
        name: "exif-js",
        data(){
            return {
              address:''
            }
        },
        methods:{
          getImgLocation(){
            let _this = this
            EXIF.getData(this.$refs.img,function(){
              //图片包含的所有信息(例:拍照方向、相机设备型号、拍摄时间、ISO 感光度、GPS 地理位置等数据。)
              const imgAllInfo = EXIF.getAllTags(this);
              const imgLon = EXIF.getTag(this, 'GPSLongitude')
              const imgLat = EXIF.getTag(this, 'GPSLatitude')
              if(imgLon && imgLat){
                //计算出经纬度并保留6为小数
                const lon = (imgLon[0] + imgLon[1]/60 + imgLon[2]/60/60).toFixed(6)
                const lat = (imgLat[0] + imgLat[1]/60 + imgLat[2]/60/60).toFixed(6)
                //使用高德地图的逆地理编码,key申请类型为Web API服务
                const mapKey = '自己申请的key值'
                //调用高得API
                axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${mapKey}&location=${lon},${lat}`).then(res=>{
                  _this.address = res.data.regeocode.formatted_address
                })
              } else {
                _this.address = '暂未获得该图片地址'
              }
            })
          }
        }
    }
    </script>
    
    <style scoped>
    
    </style>
    
    

    运行结果

    相关文章

      网友评论

          本文标题:Vue获取照片拍摄的地理位置信息

          本文链接:https://www.haomeiwen.com/subject/jfkgwdtx.html