React使用高德地圖的實現示例(react-amap)

pc版React重構,使用到瞭高德地圖。搜瞭資料,發現有一個針對React進行封裝的地圖插件react-amap。官方網址:https://elemefe.github.io/react-amap/components/map,有興趣的可以看下裡面的API。

react-amap 安裝

1、使用npm進行安裝,目前是1.2.8版本:

cnpm i react-amap

2、直接使用sdn方式引入

<script src="https://unpkg.com/[email protected]/dist/react-amap.min.js"></script>

react-amap 使用

import React,{Component} from 'react'
import {Map,Marker} from 'react-amap'
const mapKey = '1234567809843asadasd' //需要自己去高德官網上去申請
class Address extends Component {
	constructor (props) {
        super (props)
        this.state = {  
        }
    }
	render(){
		return (
			<div style={{width: '100%', height: '400px'}}>
				<Map amapkey={mapKey} 
				     zoom={15}></Map>
			</div>
		)
	}
}

export default Address

這樣的話,就會初始化一個簡單的地圖。

在這裡插入圖片描述

實際開發過程中,你會有比較復雜的使用場景。比如需要標記點、對地圖進行縮放、能夠定位到當前位置、位置搜索等等功能。需求大致如下圖所示:

在這裡插入圖片描述

這樣的話,那就需要引入插件以及組件的概念瞭。
ToolBar、Scale插件

<Map  plugins={["ToolBar", 'Scale']}></Map>

Marker 地圖標記

<Map>
	<Marker position={['lng','lat']}></Marker>
</Map>

InfoWindow 窗體組件

<Map>
	<InfoWindow
            position={this.state.position}
            visible={this.state.visible}
            isCustom={false}
            content={html}
            size={this.state.size}
            offset={this.state.offset}
            events={this.windowEvents}
          />
</Map>

通過 created 事件實現更高級的使用需求,在高德原生實例創建成功後調用,參數就是創建的實例;獲取到實例之後,就可以根據高德原生的方法對實例進行操作:

const events = {
    created: (instance) => { console.log(instance.getZoom())},
    click: () => { console.log('You clicked map') }
}
<Map events={events}  />

實現一個較為復雜地址搜索,地址標記、逆地理解析代碼:

import React , { Component } from 'react'
import { Modal , Input } from 'antd'
import styles from './index.scss'
import classname from 'classnames'
import { Map ,Marker,InfoWindow} from 'react-amap'
import marker from 'SRC/statics/images/signin/marker2.png'

const mapKey = '42c177c66c03437400aa9560dad5451e'

class Address extends Component {
    constructor (props) {
        super(props)
        this.state = {
            signAddrList:{
                name:'',
                addr:'',
                longitude: 0,
                latitude: 0
            },
            geocoder:'',
            searchContent:'',
            isChose:false
        }
    }

    //改變數據通用方法(單層)

    changeData = (value, key) => {
        let { signAddrList } = this.state
        signAddrList[key] = value
        this.setState({
            signAddrList:signAddrList
        })
    }

    placeSearch = (e) => {
        this.setState({searchContent:e})
    }

    searchPlace = (e) => {
        console.log(1234,e)
    }





    componentDidMount() {
    
    }

    render() {
        let { changeModal , saveAddressDetail } = this.props
        let { signAddrList } = this.state
        const selectAddress = {
            created:(e) => {
                let auto
                let geocoder
                window.AMap.plugin('AMap.Autocomplete',() => {
                    auto = new window.AMap.Autocomplete({input:'tipinput'});
                })

                window.AMap.plugin(["AMap.Geocoder"],function(){
                    geocoder= new AMap.Geocoder({
                        radius:1000, //以已知坐標為中心點,radius為半徑,返回范圍內興趣點和道路信息
                        extensions: "all"//返回地址描述以及附近興趣點和道路信息,默認"base"
                    });
                });

                window.AMap.plugin('AMap.PlaceSearch',() => {
                    let place = new window.AMap.PlaceSearch({})
                    let _this = this
                    window.AMap.event.addListener(auto,"select",(e) => {
                        place.search(e.poi.name)
                        geocoder.getAddress(e.poi.location,function (status,result) {
                            if (status === 'complete'&&result.regeocode) {
                                let address = result.regeocode.formattedAddress;
                                let data = result.regeocode.addressComponent
                                let name = data.township +data.street + data.streetNumber
                                _this.changeData(address,'addr')
                                _this.changeData(name,'name')
                                _this.changeData(e.poi.location.lng,'longitude')
                                _this.changeData(e.poi.location.lat,'latitude')
                                _this.setState({isChose:true})
                            }
                        })
                    })
                })
            },
            click:(e) => {
                const _this = this
                var geocoder
                var infoWindow
                var lnglatXY=new AMap.LngLat(e.lnglat.lng,e.lnglat.lat);
                let content = '<div>定位中....</div>'

                window.AMap.plugin(["AMap.Geocoder"],function(){
                    geocoder= new AMap.Geocoder({
                        radius:1000, //以已知坐標為中心點,radius為半徑,返回范圍內興趣點和道路信息
                        extensions: "all"//返回地址描述以及附近興趣點和道路信息,默認"base"
                    });
                    geocoder.getAddress(e.lnglat,function (status,result) {
                        if (status === 'complete'&&result.regeocode) {
                            let address = result.regeocode.formattedAddress;
                            let data = result.regeocode.addressComponent
                            let name = data.township +data.street + data.streetNumber
                          
                            _this.changeData(address,'addr')
                            _this.changeData(name,'name')
                            _this.changeData(e.lnglat.lng,'longitude')
                            _this.changeData(e.lnglat.lat,'latitude')
                            _this.setState({isChose:true})
                        }
                    })
                });
                
            }
        }
        return (
            <div>
                <Modal visible={true}
                       title="辦公地點"
                       centered={true}
                       onCancel={() => changeModal('addressStatus',0)}
                       onOk={() => saveAddressDetail(signAddrList)}
                       width={700}>
                    <div className={styles.serach}>
                        <input id="tipinput"
                               className={styles.searchContent}
                               onChange={(e) => this.placeSearch(e.target.value)}
                               onKeyDown={(e) => this.searchPlace(e)} />
                        <i className={classname(styles.serachIcon,"iconfont icon-weibiaoti106")}></i>
                    </div>
                    <div className={styles.mapContainer} id="content" >
                        {
                            this.state.isChose ? <Map amapkey={mapKey}
                                                      plugins={["ToolBar", 'Scale']}
                                                      events={selectAddress}
                                                      center={ [ signAddrList.longitude,signAddrList.latitude] }
                                                      zoom={15}>
                                <Marker position={[ signAddrList.longitude,signAddrList.latitude]}/>
                            </Map> : <Map amapkey={mapKey}
                                          plugins={["ToolBar", 'Scale']}
                                          events={selectAddress}
                                          zoom={15}>
                                <Marker position={[ signAddrList.longitude,signAddrList.latitude]}/>
                            </Map>
                        }
                    </div>
                    <div className="mar-t-20">詳細地址:
                        <span className="cor-dark mar-l-10">{signAddrList.addr}</span>
                    </div>
                </Modal>
            </div>
        )
    }
}

export default Address

到此這篇關於React使用高德地圖的實現示例(react-amap)的文章就介紹到這瞭,更多相關React 高德地圖內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀:

    None Found