React 高德地图(React Amap)

  React Amap 官方文档

  最近做后台选址地图的更换,由百度地图换到高德地图。原有功能为用户先圈定城市范围,点击定位图标,打开弹窗,将用户原有的地图信息以经纬度的形式带入,地图中心点切换为当前经纬度,用户可以通过搜索选择地址,在右侧选择详细地址后点击确定,将选择的信息带出,关闭弹窗。

  涉及到的高德地图API有地址编码与逆编码、poi选点,地图展示。

具体效果如下:

 具体实现代码如下:

import React, { memo } from 'react';
import { Map, Markers } from 'react-amap';
import { debounce } from 'lodash';
import { AutoComplete, Spin, Cascader, Modal, Input } from 'antd';
import styles from './mapSelect.less';
import ManageForm from './ManageForm';
import activeIcon from './location_active.png';
import localIcon from './location.png';

let loading;
// 高德地图实例
let mapInstance = null

export default class MapSelect extends React.PureComponent {

  state = {
    loading: true,
    searchResult: [],
    current: null,
    address: '',
    city: '北京市',
    point: null
  };

  // init after localSearch
  doSearch = () => {};

  async componentWillReceiveProps(props) {
    if (props.visible) {
      const city = props.city || '北京市';
      this.setState(
        {
          address: props.address,
          city,
          loading: true,
        },
        () => {
          if (Array.isArray(props.point)) {
            console.info('from point', props.point)
            this.setState({
              point: props.point
            })
          } else {
            console.info('from name', city)
          }
        }
      );
    }
  }

  emit = (key, item) => {
    if (typeof this.props[key] === 'function') {
      this.props[key](item);
    }
  };

  onOk = () => {
    const { current } = this.state;
    if (!current) {
      return Modal.error({
        title: '提示',
        content: '请选择一个地址',
      });
    }
    this.emit('onChange', current);
    this.clear();
  };

  onCancel = () => {
    this.props.onCancel();
    this.clear();
  };

  clear() {
    this.setState({
      searchResult: [],
      current: null,
      address: '',
      city: '北京市',
    });
  }

  onInputChange = e => {
    const address = e.target.value;
    this.setState(
      {
        address,
        loading: true,
      },
      () => {
        this.doSearch(address);
      }
    );
  };

  render() {
    const { address, city } = this.state;
    const { visible } = this.props;
    const amapEvents = {
      created: (el) => {
        // react amap 自带的生命周期,在这里可以执行一些初始化操作
        mapInstance = el
        AMap.service(["AMap.PlaceSearch"], () => {
          // 构造地点查询类
          this.doSearch = debounce(doSearch.bind(this), 500);
          let placeSearch = new AMap.PlaceSearch({ 
              pageSize: 10, // 单页显示结果条数
              pageIndex: 1, // 页码
              city, // 兴趣点城市
              citylimit: true,  // 是否强制限制在设置的城市内搜索
              map: mapInstance, // 展现结果的地图实例
              panel: "panel", // 结果列表将在此容器中进行展示。
              autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          });
          AMap.event.addListener(placeSearch,"selectChanged",(e) => {
            console.log('e', e);
            this.setState({
              current: e.selected.data
            })
            mapInstance.setZoomAndCenter(17, [e.selected.data.location.lng, e.selected.data.location.lat]) // 设置中心点
          })
          // 经纬度查询
          if (Array.isArray(this.props.point)) {
            placeSearch.searchNearBy('', this.state.point, 500, (status, result) =>{
              console.log('result1', this.state.point, status, result)
              if (status === 'complete') {
                this.setState({
                  searchResult: result.poiList.pois,
                  current: result.poiList.pois[0]
                })
              } else {
                this.setState({
                  searchResult: [],
                  current: null
                })
              }
            })
          } else {
            // 关键字查询
            console.log('this.state.address', this.state.address)
            this.doSearch(city + '政府')
          }
          function doSearch (value) {
            if (this.state.searchResult.length) {
              this.setState({
                searchResult: [],
              });
            }
            if (value) {
              placeSearch.search(city + value, (status, result) => {
                console.log('result3', this.state.address, status,  result)
                if (status === 'complete') {
                  this.setState({
                    searchResult: result.poiList.pois,
                    current: result.poiList.pois[0]
                  })
                } else {
                  this.setState({
                    searchResult: [],
                    current: null
                  })
                }
              });
            }
          }
          
      });
      },
      click: (e) => {
        console.log('ee', e)
      }
    }
    return (
      <Modal
        className={styles.modal}
        width="1000px"
        title={city}
        visible={visible}
        onOk={this.onOk}
        onCancel={this.onCancel}
      >
        <div className={styles.address}>
          搜索:
          <Input value={address} allowClear onChange={this.onInputChange} />
        </div>
        {visible && 
          <div className={styles.main}>
            <Map loading={<Spin />} events={amapEvents} amapkey='高德地图key' />
            <div id='panel' style={{overflowY: 'auto', width: '300px'}} />
          </div>}
      </Modal>
    );
  }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
React高德地图是一个针对React进行封装的地图插件,可以通过引入react-amap库来使用。你可以在官方网址https://elemefe.github.io/react-amap/components/map找到更多关于该插件的API文档。在使用时,你可以通过安装react-amap来引入插件,也可以直接使用SDN方式引入。在React组件中,你可以使用Map和Marker等组件来展示地图和标记点。你需要在高德官网上申请一个地图的API Key,并将其作为amapkey属性传递给Map组件。你还可以通过设置属性和绑定事件来自定义地图的行为,比如设置地图的中心点、缩放级别,以及绑定单击、双击、移动等事件。如果需要销毁地图实例,你可以使用map.destroy()方法来注销地图实例并释放内存。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *2* [React使用高德地图react-amap)(一)](https://blog.csdn.net/u013262823/article/details/92795965)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [【高德地图React项目中的使用——(二)各种配置的使用】](https://blog.csdn.net/qq_45149366/article/details/126125667)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值