1.第一步要加入项目package.json中或者直接yarn install它都可以
想必大家应该都会
"@amap/amap-jsapi-loader": "0.0.7"
2.加入项目中
关于接口获取key的接口 大家改成自己对应的项目请求方法
import React, { PureComponent } from 'react';
import { Input, Spin } from 'antd';
import AMapLoader from '@amap/amap-jsapi-loader';
import { services } from '@comall-backend-builder/core';import './index.less';const { api } = services;
const pfix = 'scal-select';
interface ScalSelectProps {onChange: (data: any) => void;/*** 当前值*/value: any;row: any;/*** 坐标查询-按钮* 默认展示*/showBtn: any;
}interface ScalSelectStates {/*** 当前地图实例*/map: any;/*** 地图api*/AMap: any;/*** 位置标记*/marker: any;/*** 当前选择位置经纬度*/centerPosition: any[];loading: boolean;
}export class ScalSelect extends PureComponent<ScalSelectProps, ScalSelectStates> {constructor(props: any) {super(props);this.state = {map: undefined,AMap: undefined,marker: undefined,centerPosition: [],loading: false,};}componentDidMount() {this.initMap();}initMap = () => {this.setState({ loading: true });api.get({}, { apiPath: '/admin/amap/config' }).then((result: any) => {AMapLoader.load({key: result.key, // 申请好的Web端开发者Key,首次调用 load 时必填version: '1.4.15', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15plugins: ['AMap.Marker', 'AMap.ToolBar', 'AMap.IndoorMap'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等}).then((AMap: any) => {let map = new AMap.Map('mapContainer', {zoom: 13,});map.addControl(new AMap.ToolBar());map.on('click', this.showInfoClick);this.setState({ AMap, map, loading: false });map.on('complete', this.mapEnd);}).catch((e: any) => {console.log(e);});});};showInfoClick = (e: any) => {const lat = e.lnglat.lat;const lng = e.lnglat.lng;this.setState({centerPosition: [lng, lat],},() => {this.changePosition();});};mapEnd = () => {const { centerPosition } = this.state;if (centerPosition.length) {this.changePosition();}};changePosition = () => {const { AMap, map, centerPosition, marker } = this.state;//移除所有覆盖物if (marker) {map.remove(marker);}// 创建一个 Marker 实例:let newMarker = new AMap.Marker({icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png', // 添加 Icon 实例zoom: 18,position: centerPosition,});// 将创建的点标记添加到已有的地图实例:map.add(newMarker);// 缩放地图到合适的视野级别// map.setFitView(newMarker);//地图中心点平移至指定点位置map.panTo(centerPosition);this.props.onChange(centerPosition);this.setState({AMap,map,marker: newMarker,});};render() {const { loading, centerPosition } = this.state;const longitudeAndLatitude = centerPosition && centerPosition.join(',');const innerName = {box: `${pfix}`,wrap: `${pfix}--wrap`,searchBox: `${pfix}--search_box`,searchBtn: `${pfix}--search_box_btn`,};return (<div className={innerName.box}><Spin spinning={loading}><div className={innerName.searchBox}><Inputdisabled={true}value={longitudeAndLatitude}placeholder={services.language.getText('qxzzb')}/></div><div className={innerName.wrap}><div className="map-container" id="mapContainer"></div></div></Spin></div>);}
}
效果图如下