(十九)原生js案例之h5地里位置信息与高德地图的初使用

h5 地里位置信息

1. 获取当前位置信息

在这里插入图片描述

window.onload = function () {
  const oBtn = document.querySelector("#btn");
  const oBox = document.querySelector("#box");

  oBtn.onclick = function () {
    window.navigator.geolocation.getCurrentPosition(
      function (position) {
        console.log("🚀 ~ position:", position);
        const { latitude, longitude } = position.coords;
        oBox.innerHTML += `${latitude} ${longitude}`;
      },
      function (error) {
        console.log("🚀 ~ error:", error);
      },
      {
        enableHighAccuracy: true,
        timeout: 5000,
      }
    );
  };
};
  • 失败编码

    • 0 未知错误,不包括下面的
    • 1 用户拒绝
    • 2 尝试获取用户信息,但失败了
    • 3 超时,设置了 timeout 参数
  • chrome 浏览器失败,edge 浏览器成功
    在这里插入图片描述

  • 数据收集,json 格式

    {
      "enableHighAccuracy": true, // 开启高精度,默认 false
      "timeout": 5000, // 超时时间,默认 infinity
      "maximumAge": 0 // 位置可以缓存时间,默认 0
    }
    

2. 获取当前位置信息

window.onload = function () {
  const oBtn = document.querySelector("#btn");
  const oBox = document.querySelector("#box");
  let timer = null;
  oBtn.onclick = function () {
    timer = window.navigator.geolocation.getCurrentPosition(
      function (position) {
        console.log("🚀 ~ position:", position);
        let str = "";
        for (const key in position.coords) {
          const value = position.coords[key];
          str += `${key}: ${value} <br/>`;
        }
        oBox.innerHTML = str;
      },
      function (error) {
        console.log("🚀 ~ error:", error);
        //移动端主要位置改变,这里就会一直报错
        //清除定时器
        window.navigator.geolocation.clearWatch(timer);
      },
      {
        enableHighAccuracy: true,
        timeout: 5000,
        frequence: 1000,
        maximumAge: 1000,
      }
    );
  };
};
  • h5 获取到地里位置信息后进行标注定位,配置使用高德地图

    • 封装高德地图,进行初始化
window._AMapSecurityConfig = {
  securityJsCode: "自己的key",
};

class AMapHelper {
  static async getMap() {
    if (window.AMap) {
      return window.AMap;
    }

    let AMap = null;

    const baseConfig = {
      key: window._AMapSecurityConfig.securityJsCode, //申请好的Web端开发者 Key,调用 load 时必填
      version: "2.0", //指定要加载的 JS API 的版本,缺省时默认为 1.4.15
    };

    try {
      AMap = await AMapLoader.load(baseConfig);
      console.log("高德地图初始化");
    } catch (error) {
      console.log(error);
    }

    return AMap;
  }
}
  • 拿到高德地图对象后,进行标记
window.onload = async function () {
  let timer = 0;
  await AMapHelper.getMap();
  let map = new AMap.Map("box", {
    resizeEnable: true,
  });
  getPos();
  function getPos() {
    timer = window.navigator.geolocation.getCurrentPosition(
      function (position) {
        console.log("🚀 ~ position:", position);
        //获取位置信息
        const { longitude, latitude } = position.coords;
        //创建标记
        const marker = new AMap.Marker({
          position: [longitude, latitude], //位置
        });
        map.add(marker); //添加到地图
      },
      function (error) {
        console.log("🚀 ~ error:", error);
        //移动端主要位置改变,这里就会一直报错
        //清除定时器
        window.navigator.geolocation.clearWatch(timer);
      },
      {
        enableHighAccuracy: true,
        timeout: 5000,
        frequence: 1000,
        maximumAge: 1000,
      }
    );
  }
};

案例,高德地图添加标记,事件,自定义标记 ICON

在这里插入图片描述

window.onload = async function () {
  let timer = 0;
  await AMapHelper.getMap();
  // console.log(window.AMap);
  let map = new AMap.Map("box", {
    resizeEnable: true,
  });
  const content = [
    "<div><b>高德软件有限公司</b>",
    "电话 : 010-84107000   邮编 : 100102",
    "地址 : 北京市望京阜通东大街方恒国际中心A座16层</div>",
  ];
  const icon = new AMap.Icon({
    size: new AMap.Size(25, 34), //图标尺寸
    image: "./img/site.png", //Icon 的图像
    imageOffset: new AMap.Pixel(-9, -3), //图像相对展示区域的偏移量,适于雪碧图等
    imageSize: new AMap.Size(135, 40), //根据所设置的大小拉伸或压缩图片
  });
  getPos();
  function getPos() {
    timer = window.navigator.geolocation.getCurrentPosition(
      function (position) {
        console.log("🚀 ~ position:", position);
        //获取位置信息
        const { longitude, latitude } = position.coords;
        //创建标记,自定义图片
        const marker = new AMap.Marker({
          position: new AMap.LngLat(longitude, latitude), //点标记的位置
          offset: new AMap.Pixel(-13, -30), //偏移量
          icon: icon, //添加 Icon 实例
          title: "高德科技",
          zooms: [2, 12], //点标记显示的层级范围,超过范围不显示
        });
        //添加窗体事件
        const infoWindow = new AMap.InfoWindow({
          //创建信息窗体
          isCustom: false, //使用自定义窗体
          // content: "<div id='info1'>这里可以显示自己的自定义描述内容</div>", //信息窗体的内容可以是任意html片段
          offset: new AMap.Pixel(16, -45),
          content,
          closeWhenClickMap: true,
        });
        //默认展示信息窗体
        infoWindow.open(map, [longitude, latitude]);
        const onMarkerClick = function (e) {
          // infoWindow.open(map, e.target.getPosition()); //点击打开信息窗体
          //e.target就是被点击的Marker
        };
        map.add(marker); //添加到地图
        marker.on("click", onMarkerClick); //绑定click事件
      },
      function (error) {
        console.log("🚀 ~ error:", error);
        //移动端主要位置改变,这里就会一直报错
        //清除定时器
        window.navigator.geolocation.clearWatch(timer);
      },
      {
        enableHighAccuracy: true,
        timeout: 5000,
        frequence: 1000,
        maximumAge: 1000,
      }
    );
  }
};

进阶之路: 高德地图2.0文档

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值