先上一個示例圖
使用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);// 初始化地圖,設(shè)置中心點坐標(biāo)和地圖級別
map.enableScrollWheelZoom(true); // 開啟鼠標(biāo)滾輪縮放
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)); // 創(chuàng)建標(biāo)注
map.addOverlay(marker);
})
}
handleSearch= (searchText: string) => {
//http://api.map.baidu.com/place/v2/suggestion?query=天安門®ion=北京&city_limit=true&output=json&ak=你的ak //GET請求
//這是我去后臺服務(wù)器上請求的地址檢索,因為在前端直接請求會報跨域的問題
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)); // 創(chuàng)建標(biāo)注
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>;
}
}