美文网首页
React 高德地图(一)

React 高德地图(一)

作者: 爱吃豆包 | 来源:发表于2019-09-26 10:43 被阅读0次

由于从 Vue 切换到 React,就一直在学习React。
最近项目需要在React中使用地图

这里使用 react-amap组件

1.快速使用

2.使用高德原生API

(1)先看看快速使用

先引入地图组件

npm install --save react-amap

然后渲染在页面上

import React from 'react';
import ReactDOM from 'react-dom';
import { Map, Marker } from 'react-amap';
import styles from '../amap.less'

class Amap extends React.Component {

  render() {
    return (
      <>
        <div style={{ width: '100%', height: '400px', position: 'relative' }}>
          <Map events={this.amapEvents} amapkey={你的高德地图KEY}>
            <Marker position={this.markerPosition} events={this.markerEvents} />
          </Map>
        </div>
      </>
    )
  }
}

export default Amap

出现地图


高德地图

(2)使用高德原生API

更新记录:###

最后更新时间 2019-11-6:增加了标记点,缩放级别

import React from 'react';
import ReactDOM from 'react-dom';
import { Map, Marker } from 'react-amap';
import styles from '../amap.less'

class Amap extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      // 设置坐标点,就会在地图上显示一个 标记点
      markerPosition: { longitude: 120, latitude: 35 },
    }
    // 高德地图 Marker 实例
    this.markerInstance = undefined
    // 高德地图 Map 实例
    this.mapInstance = undefined

    this.amapEvents = {
      created: mapInstance => {
        console.log('高德地图 Map 实例创建成功;如果你要亲自对实例进行操作,可以从这里开始。比如:');
        console.log('缩放级别:', mapInstance.getZoom());
        this.mapInstance = mapInstance
        

        AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.CitySearch'], () => {
          // 实例化Autocomplete
          const autoOptions = {
            // city 限定城市,默认全国
            // city: '025',
            // input 为绑定输入提示功能的input的DOM ID
            input: 'amapInput',
          }
          const autoComplete = new AMap.Autocomplete(autoOptions);
          // 无需再手动执行search方法,autoComplete会根据传入input对应的DOM动态触发search

          const placeSearch = new AMap.PlaceSearch({
            // city: '南京',
            map: mapInstance,
          })

          // 监听下拉框选中事件
          AMap.event.addListener(autoComplete, 'select', e => {
            // TODO 针对选中的poi实现自己的功能
            placeSearch.setCity(e.poi.adcode)
            placeSearch.search(e.poi.name)
          })


          const citySearch = new AMap.CitySearch()
          citySearch.getLocalCity((status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              // 查询成功,result即为当前所在城市信息
              console.log('当前所在城市:', result)
              if (result && result.city && result.bounds) {
                // 当前城市名称
                // const cityinfo = result.city;

                // 当前城市位置信息
                const citybounds = result.bounds;
                // document.getElementById('info').innerHTML = '您当前所在城市:'+cityinfo;
                // 地图显示当前城市
                mapInstance.setBounds(citybounds);
                // 需要在设置坐标成功后,重新设置 缩放级别
                // mapInstance.setZoom(15)
              }
            }
          })
        })

        // 实例点击事件
        mapInstance.on('click', e => {
          const lngLat = `${e.lnglat.getLat()},${e.lnglat.getLng()}`
          console.log('坐标位置:', lngLat)
          this.props.onChange(lngLat)
        });
      },
    };
    this.markerEvents = {
      created: markerInstance => {
        console.log('高德地图 Marker 实例创建成功;如果你要亲自对实例进行操作,可以从这里开始。比如:');
        console.log(markerInstance.getPosition());

        this.markerInstance = markerInstance
      },
    }
    // this.markerPosition = { longitude: 120, latitude: 30 };
  }

  componentDidUpdate(prevProps) {
    const { value } = this.props
    if (this.props.value !== prevProps.value) {
      if (value) {
        const temp = value.split(',')

        // 重新设置地图坐标点
        this.setState({ markerPosition: { longitude: temp[1], latitude: temp[0] } }, () => {
          // 需要在设置坐标成功后,重新设置 缩放级别
          if (this.mapInstance) {
              this.mapInstance.setZoom(15)
          }
         
        })
      }
    }
  }

  render() {
    return (
      <>
        <div style={{ width: '100%', height: '400px', position: 'relative' }}>
          {/* zoom={15} 设置后,无效,不知道什么原因,必须手动设置 */}
          <Map plugins={['ToolBar']} events={this.amapEvents} amapkey={你的高德地图KEY} center={this.state.markerPosition}>
            <Marker position={this.state.markerPosition} events={this.markerEvents} />
          </Map>
          {
          <div className={styles.infoBox}>
            <span className={styles.inputText}>请输入关键字</span>
            <input id="amapInput" className={styles.input} type="text" />
          </div>
          }
        </div>
      </>
    )
  }
}

export default Amap

渲染页面结果


高德地图

这里有几个坑:

1.会提示找不到 AMap 实例问题,在react-amap这个组件引入后,实际上是可以使用到 AMap 这个实例的。

解决办法:
.eslintrc.js 文件中,加入 AMap

module.exports = {
  ...strictEslint,
  globals: {
    // 省略一大波内容

    // 引入 AMap
    AMap: true,
  },
};

然后全局搜索 useEslintrc 值改为 true,这个文件在 webpack.config.js 里面。
就可以调用 AMap 实例

2.地图实例问题

    // 高德地图 Marker 实例
    this.markerInstance = undefined
    // 高德地图 Map 实例
    this.mapInstance = undefined

   // 在渲染地图的时候,需要把实例赋值给这两个变量

在代码中这两行就是当前渲染出地图的实例,可以直接使用!
定义在外面,然后可以在React里面的其他函数中使用

相关文章

网友评论

      本文标题:React 高德地图(一)

      本文链接:https://www.haomeiwen.com/subject/upuguctx.html