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

h5 地里位置信息

1. 获取当前位置信息

js 复制代码
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 格式

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

2. 获取当前位置信息

js 复制代码
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 获取到地里位置信息后进行标注定位,配置使用高德地图

    • 封装高德地图,进行初始化
js 复制代码
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;
  }
}
  • 拿到高德地图对象后,进行标记
js 复制代码
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

js 复制代码
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 小时前
端侧模型多端部署实战:从格式转换到灰度发布,Web 和移动端统一部署流水线
前端·人工智能·大模型·ai编程·ai模型·ai产品·端侧ai
vx-程序开发4 小时前
springboot农产品运输服务平台---附源码75498
java·javascript·spring boot·python·eclipse·django·php
独隅4 小时前
前端离线暂停更新策略:Service Worker 与 PWA 的静默控制实践
前端
妙码生花4 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(五十八):后台系统配置管理实现
前端·后端·go
用户938515635074 小时前
React 受控/非受控组件与 React.memo 性能优化——从本质到实战
前端·javascript·react.js
IT_陈寒4 小时前
Java并行流把我坑惨了:原来不是线程安全的!
前端·人工智能·后端
计科土狗5 小时前
GESP六级专题之类与对象
java·前端·数据库
anOnion5 小时前
构建无障碍组件之Listbox Pattern
前端·html·交互设计
凌涘5 小时前
前端路由(三):鉴权、拦截与重定向
前端