vue使用高德地图实现城市定位封装(pc和h5同用)

21 篇文章 0 订阅

1. 新建一个utilis.js

// 定位
export function ip(callback, error) {
  let map, geolocation;
  //加载地图,调用浏览器定位服务
  const mapObj = new AMap.Map("iCenter");
  mapObj.plugin("AMap.Geolocation", function() {
    geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, // 是否使用高精度定位,默认:true
      timeout: 10000, // 超过10秒后停止定位,默认:无穷大
      maximumAge: 60 * 24 * 60 * 60 * 1000, // 定位结果缓存0毫秒,默认:0
      convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
      showButton: true, // 显示定位按钮,默认:true
      buttonPosition: "LB", // 定位按钮停靠位置,默认:'LB',左下角
      buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
      showMarker: true, // 定位成功后在定位到的位置显示点标记,默认:true
      showCircle: true, // 定位成功后用圆圈表示定位精度范围,默认:true
      panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
      zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
    })
    mapObj.addControl(geolocation);
    geolocation.getCurrentPosition();
    AMap.event.addListener(geolocation, "complete", onComplete) // 返回定位信息
    AMap.event.addListener(geolocation, "error", onError) // 返回定位出错信息
  })
  // 解析定位结果
  function onComplete (data) {
    var str = [ "定位成功" ]
    // alert(JSON.stringify(data));
    let { province, city, district } = data.addressComponent
    city = city || province
    // setCookie("province", JSON.stringify(data.addressComponent))
    // setCookie("city",JSON.stringify(city))
    callback && callback(city)
    str.push("经度:" + data.position.getLng())
    str.push("纬度:" + data.position.getLat())
    if (data.accuracy) {
      str.push("精度:" + data.accuracy + " 米");
    } // 如为IP精确定位结果则没有精度信息
    str.push("是否经过偏移:" + (data.isConverted ? "是" : "否"));
    // document.getElementById("tip").innerHTML = str.join("<br>");
  }
  // 解析定位错误信息
  function onError(data) {
    error && error(data)
    console.log('定位失败');
  }
}
export default{
    ip
}

 

2. 在index.html引入高德地图

 <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.8&amp;key=自己的地图key"></script>

3.页面使用

import utilt from '路径地址'

import utils from '../utils/utils'
 mounted(){
        utils.ip(e=>{
            this.city = e
        },data=>{
           
        })
    }

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沫熙瑾年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值