amap/amap-jsapi-loader -- 高德地图

一、准备

1.登录控制台

登录 高德开放平台控制台,如果没有开发者账号,请 注册开发者

2.创建 key

进入应用管理,创建新应用,新应用中添加 key,服务平台选择 Web端(JS API)。

3.获取 key 和密钥

创建成功后,可获取 key 和安全密钥。

 

二、初始化地图

1.下载依赖包

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

2.引入 JS API  Loader

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

3.新建 MapContainer.jsx 文件

在项目中新建 MapContainer.jsx 文件,用作地图组件脚本。

import AMapLoader from '@amap/amap-jsapi-loader';
import { useEffect } from 'react';
import styles from './MapContainer.css';

export default function MapContainer() {
  let map: any = null;

  useEffect(() => {
    AMapLoader.load({
      key: 'key', // 申请好的Web端开发者Key,首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    })
      .then((AMap: any) => {
        //创建地图实例
        map = new AMap.Map('container', {
          // 设置地图容器id
          viewMode: '2D', // 是否为3D地图模式
          zoom: 10, // 初始化地图级别
          center: [116.397428, 39.90923], // 初始化地图中心点位置
        });
      };)
      .catch((e) => {
        console.log(e);
      });

    return () => {
      map?.destroy(); //销毁地图
    };
  }, []);

  return (
      <div
        id="container"
        className={styles.container}
        style={{ height: '800px' }}
      ></div>
  );
}

4.新建 MapContainer.less 文件

在项目中新建 MapContainer.less 文件,用作地图组件样式。

.container{
  padding: 0px;
  margin: 0px;
  width: 100%;
}

5.效果图

三、插件的使用

1.基础插件引入

AMap.plugin(
    ['AMap.Scale', 'AMap.Geolocation', 'AMap.ToolBar', 'AMap.ControlBar'],
    function () {
        //在回调函数中实例化插件,并使用插件功能
        map.addControl(new AMap.Scale()); //比例尺
        map.addControl(new AMap.ToolBar()); //缩放工具条
        map.addControl(new AMap.ControlBar()); //控制罗盘
        map.addControl(
          new AMap.Geolocation({
            position: {
              bottom: '80px',
              left: '15px',
            },
          }),
        ); //定位控件,用来获取和展示用户主机所在的经纬度位置
    },
);

更多插件参考官方文档

 2.信息窗体 InfoWindow

默认信息窗体封装了关闭按钮,使用 API 默认的信息窗体样式,这个时候只需要对 InfoWindow 设定 content 属性即可,content 可以是 dom 对象,也可以是 html 识别的字符串。

        //定义信息窗口
        let infoWindow: any = null;
        
        //打开信息窗体
        map.on('click', function (e: any) {
          //构建信息窗体中显示的内容
          let info = [];
          info.push(
            '<div class=\'input-card content-window-card\'><div><img style="float:left;width:67px;height:16px;" src=" https://webapi.amap.com/images/autonavi.png "/></div> ',
          );
          info.push('<div style="padding:7px 0px 0px 0px;"><h4>高德软件</h4>');
          info.push(
            "<p class='input-item'>电话 : 010-84107000   邮编 : 100102</p>",
          );
          info.push(
            "<p class='input-item'>地址 :北京市朝阳区望京阜荣街10号首开广场4层</p></div></div>",
          );

          infoWindow = new AMap.InfoWindow({
            content: info.join(''), //使用默认信息窗体框样式,显示信息内容
          });

          infoWindow?.open(map, e.lnglat);
        });

        // 关闭信息窗体
        // infoWindow?.close();

3.右键菜单 ContextMenu

        //添加右键点击事件
        let contextMenu: any = null;

        //地图绑定鼠标右击事件——弹出右键菜单
        map.on('rightclick', function (e: any) {
          let contextMenuPositon: any = null;
          contextMenu = new AMap.ContextMenu({ isOpen: false });
          //右键放大
          contextMenu?.addItem(
            '放大一级',
            function () {
              map.zoomIn();
            },
            0,
          );

          //右键缩小
          contextMenu?.addItem(
            '缩小一级',
            function () {
              map.zoomOut();
            },
            1,
          );

          //右键显示全国范围
          contextMenu?.addItem(
            '缩放至全国范围',
            function () {
              map.setZoomAndCenter(4, [108.946609, 34.262324]);
            },
            2,
          );

          //右键添加Marker标记
          contextMenu?.addItem(
            '添加标记',
            function () {
              new AMap.Marker({
                map: map,
                position: contextMenuPositon, //基点位置
              });
            },
            3,
          );

          contextMenu?.open(map, e.lnglat);
          contextMenuPositon = e.lnglat;
        });

        // 关闭右键弹框
        // contextMenu?.close();

4.输入提示与 POI 搜索示例

首先需要设置一下密钥

window._AMapSecurityConfig = {
  securityJsCode: 'b4fcd93bbbaead6bcc38957a0f0e3df6',
};

创建id为tipinput的输入框 

<input id="tipinput" /> 

配置 

        // 搜索
        let auto = new AMap.AutoComplete({ input: 'tipinput' });
        let placeSearch = new AMap.PlaceSearch({
          map: map,
        }); //构造地点查询类
        auto.on('select', function (e: any) {
          placeSearch.setCity(e.poi.adcode);
          placeSearch.search(e.poi.name); //关键字查询查询
        }); //注册监听,当选中某条记录时会触发

 

四、完整代码

1.效果图

2.代码 

import AMapLoader from '@amap/amap-jsapi-loader';
import { Input } from 'antd';
import { useEffect } from 'react';
import './MapContainer.less';
window._AMapSecurityConfig = {
  securityJsCode: 'b4fcd93bbbaead6bcc38957a0f0e3df6',
};
export default function MapContainer() {
  let map: any = null;

  const createMap = (AMap: any) => {
    //1.创建地图实例
    map = new AMap.Map('container', {
      // 设置地图容器id
      viewMode: '2D', // 是否为3D地图模式
      zoom: 10, // 初始化地图级别
      center: [116.397428, 39.90923], // 初始化地图中心点位置
      resizeEnable: true, // 调整大小启用
      //   layers: [new AMap.TileLayer.Satellite()], //设置图层,可设置成包含一个或多个图层的数组
      //   mapStyle: 'amap://styles/whitesmoke', //设置地图的显示样式
    });

    // 2.加载插件
    AMap.plugin(
      [
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.HawkEye',
        'AMap.ControlBar',
        'AMap.MapType',
        'AMap.Geolocation',
        'AMap.ContextMenu',
        'AMap.AutoComplete',
        'AMap.PlaceSearch',
      ],
      function () {
        //在回调函数中实例化插件,并使用插件功能
        map.addControl(
          new AMap.ControlBar({
            position: {
              top: '10px',
              right: '10px',
            },
          }),
        ); //控制罗盘
        map.addControl(new AMap.HawkEye()); //鹰眼
        map.addControl(
          new AMap.Geolocation({
            position: {
              bottom: '160px',
              left: '20px',
            },
          }),
        ); //定位控件,用来获取和展示用户主机所在的经纬度位置
        map.addControl(
          new AMap.ToolBar({
            position: {
              bottom: '80px',
              left: '21px',
            },
          }),
        ); //缩放工具条
        map.addControl(
          new AMap.Scale({
            position: {
              bottom: '35px',
              left: '20px',
            },
          }),
        ); //比例尺

        // map.addControl(
        //   new AMap.MapType({
        //     position: {
        //       bottom: '300px',
        //       right: '0',
        //     },
        //   }),
        // ); //类别切换控件

        //3.添加右键点击事件
        let contextMenu: any = null;
        //4.信息窗口
        let infoWindow: any = null;

        //地图绑定鼠标右击事件——弹出右键菜单
        map.on('rightclick', function (e: any) {
          infoWindow?.close(); //清空点击事件弹框
          let contextMenuPositon: any = null;
          contextMenu = new AMap.ContextMenu({ isOpen: false });
          //右键放大
          contextMenu?.addItem(
            '放大一级',
            function () {
              map.zoomIn();
            },
            0,
          );

          //右键缩小
          contextMenu?.addItem(
            '缩小一级',
            function () {
              map.zoomOut();
            },
            1,
          );

          //右键显示全国范围
          contextMenu?.addItem(
            '缩放至全国范围',
            function () {
              map.setZoomAndCenter(4, [108.946609, 34.262324]);
            },
            2,
          );

          //右键添加Marker标记
          contextMenu?.addItem(
            '添加标记',
            function () {
              new AMap.Marker({
                map: map,
                position: contextMenuPositon, //基点位置
              });
            },
            3,
          );

          contextMenu?.open(map, e.lnglat);
          contextMenuPositon = e.lnglat;
        });

        //打开信息窗体
        map.on('click', function (e: any) {
          contextMenu?.close(); //关闭右键弹框
          //构建信息窗体中显示的内容
          let info = [];
          info.push(
            '<div class=\'input-card content-window-card\'><div><img style="float:left;width:67px;height:16px;" src=" https://webapi.amap.com/images/autonavi.png "/></div> ',
          );
          info.push('<div style="padding:7px 0px 0px 0px;"><h4>高德软件</h4>');
          info.push(
            "<p class='input-item'>电话 : 010-84107000   邮编 : 100102</p>",
          );
          info.push(
            "<p class='input-item'>地址 :北京市朝阳区望京阜荣街10号首开广场4层</p></div></div>",
          );

          infoWindow = new AMap.InfoWindow({
            content: info.join(''), //使用默认信息窗体框样式,显示信息内容
          });

          infoWindow?.open(map, e.lnglat);
        });

        // 4.搜索
        let auto = new AMap.AutoComplete({ input: 'tipinput' });
        let placeSearch = new AMap.PlaceSearch({
          map: map,
        }); //构造地点查询类
        auto.on('select', function (e: any) {
          placeSearch.setCity(e.poi.adcode);
          placeSearch.search(e.poi.name); //关键字查询查询
        }); //注册监听,当选中某条记录时会触发
      },
    );
  };

  const onCatch = (e: any) => {
    console.log(e);
  };

  const mountMap = () => {
    map?.destroy(); //销毁地图
  };

  useEffect(() => {
    AMapLoader.load({
      key: 'e558ae3e565bc8f545a98d88794aada5', // 申请好的Web端开发者Key,首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
      plugins: [], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
    })
      .then(createMap)
      .catch(onCatch);

    return mountMap;
  }, []);

  return (
    <div className="map">
      <div id="container" style={{ height: '800px' }}></div>
      <Input id="tipinput" placeholder="请输入搜索内容" />
    </div>
  );
}

3.样式 

.map {
  position: relative;
  .container {
    padding: 0px;
    margin: 0px;
    width: 100%;
  }
  #tipinput {
    position: absolute;
    left: 10px;
    top: 10px;
    width: 200px;
  }
  .amap-sug-result {
    z-index: 9999;
    visibility: visible;
  }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

王布尔

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

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

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

打赏作者

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

抵扣说明:

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

余额充值