react-bmap 百度地图 react组件

763 阅读1分钟

官网地址 lbsyun.baidu.com/jsdemo.htm#…

实现搜索、点击地图标点、定位、点击搜索下拉标点。

 注意:ios需要https
<script src='http://api.map.baidu.com/api?v=2.0&ak=地图key'></script>

import React, { Component } from 'react';
import { Toast, Radio, List, Modal, InputItem  } from 'antd-mobile';
import { observer, inject } from "mobx-react";
import  { Map, Marker } from 'react-bmap';
import app from 'app';
import _ from 'lodash';

const RadioItem = Radio.RadioItem;

@inject("personnelErrStore", "sysStore")
@observer
class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pois: [],
            signAddrList: [],
            latNum: 39.90932,
            lngNum: 116.396961,
            twoPage: false,
            _zoom: 10,
            subShow: false,
            mapRecord: {}
        }
        this.Mapfref = React.createRef();
    }

    componentDidMount() {
        document.title = '添加发生地点';
        this.initDataMap();
    }

    initDataMap=(val)=>{
        let ac = new window.BMap.Autocomplete({ input: "suggestId", location: this.Mapfref.current.map }); //建立一个自动完成的对象
        this.Mapfref.current.map.enableScrollWheelZoom(true)
        ac.addEventListener("onconfirm", this.handleConform);
        this.Mapfref.current.map.addEventListener("click", this.handelChakMap);
        this.props.$mi.getData({
            type:'getGPS',
            fn:{
              name:'sign-in-get-gps',
              listener:(data)=>{
                let obj = { point:data }
                this.handelChakMap(obj);
              }
            }
          });
    }
    
    handelChakMap = (info) => {
        const { point: { lat, lng } } = info
        this.setState({
            latNum: info.point.lat,
            lngNum: info.point.lng,
            _zoom: 18
        })
        let point = new window.BMap.Point(lng, lat);
        let gc = new window.BMap.Geocoder();
        let that = this;
        gc.getLocation(point, function (rs) {
            that.setState({
                pois:rs.surroundingPois,
                mapRecord: (rs.surroundingPois && rs.surroundingPois[0]) || {}
            })
        });
    }

    handleConform = (mapInfo) => {
        let _value = mapInfo.item.value;
        let myValue = _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business;
        this.setPlace(myValue);
    }

    setPlace = (myValue) => {
        this.Mapfref.current.map.clearOverlays(); //清除地图上所有覆盖物
        let local = new window.BMap.LocalSearch(this.Mapfref.current.map, {
            //智能搜索
            onSearchComplete: this.setPlaceMap
        });
        local.search(myValue);
    }

    setPlaceMap = result => {
        var pp = result.getPoi(0).point; //获取第一个智能搜索的结果
        this.setState({
            latNum: pp.lat,
            lngNum: pp.lng,
            _zoom: 18,
            pois: result.Yr,
            mapRecord: (result.Yr && result.Yr[0]) || {}
        })
    };

    handelCheck = (record) => {
        const { point: { lat, lng } } = record;
        this.setState({
            latNum: lat,
            lngNum: lng,
            mapRecord: record,
            _zoom: 18
        });
    }


    handelSave = ()=>{
        const { personnelErrStore: { handelAddMapInFo } } = this.props;
        const { mapRecord } = this.state;
        if (_.isEmpty(mapRecord)) {
            Toast.info('请选择发生地点', 1);
            return false;
        }
        this.setState({ subShow: true })
        handelAddMapInFo(mapRecord, '');


    }

    handChangeInput = (val) =>{
        const { personnelErrStore: { handelAddMapInFoName } } = this.props;
        handelAddMapInFoName(val)
    }

    handelOk = ()=>{
        const { personnelErrStore: { mapInFoName } } = this.props;
        if(!mapInFoName){
            Toast.info('输入发生地址',1);
            return false;
        }
        this.setState({subShow:false})
        this.props.history.goBack();
    }

    handelCona = ()=>{
        const { personnelErrStore: { handelAddMapInFo } } = this.props;
        handelAddMapInFo('clear');
        this.props.history.goBack();
    }

    render() { 
        const { subShow, _zoom, lngNum,latNum, pois, mapRecord  } = this.state;
        const { personnelErrStore: { mapInFoName } } = this.props;
        return (
            <div className="errMange" style={{ height: app.appHeight }}>
                <div className="sear-userErr" >
                    <div className="userErr-input">
                        <img src={require("../img/per_sear.png")} alt="" />
                        <input
                            type="text"
                            placeholder="搜索地点"
                            id='suggestId'
                        />
                    </div>
                </div>
                <div className='mapBox'>
                <Map ref={this.Mapfref} center={{ lng: lngNum, lat: latNum }} zoom={_zoom} style={{ height: 300 }}>
                    {pois && pois.length? <Marker position={{ lng: lngNum, lat: latNum }} />:''}
                </Map>
                </div>
                <div className='tipName'>
                    请选择要添加的发生地点
                </div>
                <div className='positionList' style={{ height: app.appHeight - 464, overflow: 'auto' }}>
                    <List>
                        {
                            pois.map(item => {
                                return (
                                    <RadioItem key={item.uid} checked={mapRecord.uid === item.uid} onChange={() => { this.handelCheck(item) }}>
                                        <div className='basicsName'>{item.title}</div>
                                        <div className='detailedName'>
                                            <span>{item.address}</span>
                                        </div>
                                    </RadioItem>
                                )
                            })
                        }
                    </List>
                </div>
                <div className='mapfooter'>
                    <div className='mapBtn'>
                        <div className='back' onClick={() => { this.handelCona() }}>取消</div>
                        <div className='ok' onClick={this.handelSave}>确定</div>
                    </div>
                </div>
                <Modal
                    visible={subShow}
                    transparent
                    maskClosable={false}
                    className='mapSubmitMod'
                    title="请完善发生地点名称"
                    footer={[{ text: '取消', onPress: () => { this.setState({subShow:false}); } },{ text: '确定', onPress: () => { this.handelOk() } }]}
                    >
                    <div style={{ height: 100, overflow: 'scroll', marginTop: '10px' }}>
                        <InputItem
                            className='mapInput'
                            value={mapInFoName}
                            placeholder="请输入发生地址"
                            clear
                            moneyKeyboardAlign="left"
                            onChange={this.handChangeInput}
                        />
                        <div>
                            {mapRecord.title}
                        </div>
                    </div>
                </Modal>
            </div>
          )
    }
}
 
export default Index;

自定义搜索

    handeSear = _.debounce((val) => {
        let local = new window.BMap.LocalSearch(this.Mapfref.current.map);
        local.setSearchCompleteCallback((searchResult) => {
            if (searchResult && searchResult) {
                const { Yr = [] } = searchResult;
                const { point = {} } = Yr[0] || {};
                this.setState({
                    pois: Yr,
                    mapRecord: (Yr && Yr[0]) || {},
                    latNum: point.lat || 0,
                    lngNum: point.lng || 0,
                })
            }
        })
        local.search(val);
    }, 1500)