先上一个示例图
image.png
使用React+Antd V4+百度地图,在地图上,添加一个可以输入地址,检索的控件。
先看React组件
import React from 'react';
import BMap from 'BMap';
import {AutoComplete, Button, Form, Input, InputNumber, Row} from "antd";
import Ajax from "@utils/Ajax";
interface IState {
pointMap: any,
autoOptions: Array<any>,
autoValue: string
}
export default class PointMap extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
}
public readonly state: Readonly<IState> = {
pointMap: '',
autoOptions: [],
autoValue: ''
}
componentDidMount(): void {
this.initMap()
}
public initMap= () => {
const { gpsx, gpsy } = this.props
let map = new BMap.Map('mapContainer')
this.setState({ pointMap: map })
map.centerAndZoom(new BMap.Point(106.552566, 29.55642), 15);// 初始化地图,设置中心点坐标和地图级别
map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
let overviewControl = new BMap.OverviewMapControl({ anchor: 'BMAP_ANCHOR_BOTTOM_RIGHT', isOpen: true });
map.addControl(overviewControl);
map.addEventListener('click', (e: any) =>{
map.clearOverlays();
let marker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat)); // 创建标注
map.addOverlay(marker);
})
}
handleSearch= (searchText: string) => {
//http://api.map.baidu.com/place/v2/suggestion?query=天安门®ion=北京&city_limit=true&output=json&ak=你的ak //GET请求
//这是我去后台服务器上请求的地址检索,因为在前端直接请求会报跨域的问题
this.setState({ autoValue: searchText, autoOptions: [] })
Ajax.post('/biz/restTemplate/getUrl', {query: searchText, region: '重庆'}, { dataType: 'form' }, (data: any) => {
if (data.data.status === 0) {
this.setState({ autoOptions: data.data.result })
}
})
}
handleSelect= (value: string) => {
const { autoOptions, pointMap } = this.state
this.setState({ autoValue: value })
let select = autoOptions.filter((item: any) => item.name === value)
if (select.length > 0 && select[0].location) {
pointMap.clearOverlays();
let pointItem = select[0]
let point = {
latitude: pointItem.location.lat,
longitude: pointItem.location.lng
}
pointMap.centerAndZoom(new BMap.Point(point.longitude, point.latitude), 15);
let marker = new BMap.Marker(new BMap.Point(point.longitude, point.latitude)); // 创建标注
pointMap.addOverlay(marker);
}
}
render(): React.ReactNode {
const { autoOptions, autoValue } = this.state
const options = autoOptions.map((item: any, index: number) => ({ key: item.uid !== '' ? item.uid : index, value: item.name }))
return <div>
<Row style={{ position: 'absolute', zIndex: 10, top: 120, left: 50}} >
<AutoComplete
dropdownMatchSelectWidth={252}
style={{ width: 300 }}
options={options}
value={autoValue}
onSelect={this.handleSelect}
onChange={this.handleSearch}
>
<Input.Search placeholder="查询地址" enterButton="查询" />
</AutoComplete>
</Row>
<div id="mapContainer" style={{ height: 600, width: '100%' }} />
</div>;
}
}
网友评论