高德API

592 阅读1分钟

安装官方提供的 npm 包:

npm i @amap/amap-jsapi-loader -S

使用的时候,只需要:

import AMapLoader from '@amap/amap-jsapi-loader';

AMapLoader.load({
    "key": "",              // 申请好的Web端开发者Key,首次调用 load 时必填
    "version": "1.4.15",   // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    "plugins": []           // 需要使用的的插件列表,如比例尺'AMap.Scale'等
    "AMapUI": {             // 是否加载 AMapUI,缺省不加载
        "version": '1.1',   // AMapUI 缺省 1.1
        "plugins":[],       // 需要加载的 AMapUI ui插件
    },
    "Loca":{                // 是否加载 Loca, 缺省不加载
        "version": '1.3.2'  // Loca 版本,缺省 1.3.2
    },
}).then((res)=>{
    map = new res.Map('container');
}).catch(e => {
    console.log(e);
})

获取城市:

像比如说我们需要城市定位和经纬度定位。我们就可以用 AMap.Geolocation 这个插件,如下:

import AMapLoader from "@amap/amap-jsapi-loader";

AMapLoader.load({
  key: "",
  version: "1.4.15",
  plugins: ["AMap.Geolocation"],
})
  .then((res) => {
    const instance = new res.Geolocation({
      timeout: 1500,
    });

    instance.getCityInfo((status, result) => {
      if (status === "complete") {
        console.log(result);
      }
    });
  })
  .catch((e) => {
    console.log(e);
  });

简单来说:获取城市信息就用 getCityInfo 这个方法,速度也挺快的,大概在 0.5s 这样。

获取经纬度:

经纬度定位则需要用到 getCurrentPosition 这个方法,不过需要注意一点:不同于城市定位,这个属于高精度定位,速度会慢很多,实测下来大概需要 5s 左右。

用法如下(关键部分):

instance.getCurrentPosition((status, result) => {
  if (status === "complete") {
    console.log(result);
  }
});

官方链接:

amap-jsapi-loader

AMap.Geolocation 插件