服务器之家

服务器之家 > 正文

React使用高德地图的实现示例(react-amap)

时间:2022-03-05 20:50     来源/作者:yzbyxmx

pc版React重构,使用到了高德地图。搜了资料,发现有一个针对React进行封装的地图插件react-amap。官方网址:https://elemefe.github.io/react-amap/components/map,有兴趣的可以看下里面的API。

react-amap 安装

1、使用npm进行安装,目前是1.2.8版本:

?
1
cnpm i react-amap

2、直接使用sdn方式引入

?
1
<script src="https://unpkg.com/react-amap@0.2.5/dist/react-amap.min.js"></script>

react-amap 使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

这样的话,就会初始化一个简单的地图。

React使用高德地图的实现示例(react-amap)

实际开发过程中,你会有比较复杂的使用场景。比如需要标记点、对地图进行缩放、能够定位到当前位置、位置搜索等等功能。需求大致如下图所示:

React使用高德地图的实现示例(react-amap)

这样的话,那就需要引入插件以及组件的概念了。
ToolBar、Scale插件

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

Marker 地图标记

?
1
2
3
<Map>
    <Marker position={['lng','lat']}></Marker>
</Map>

InfoWindow 窗体组件

?
1
2
3
4
5
6
7
8
9
10
11
<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 事件实现更高级的使用需求,在高德原生实例创建成功后调用,参数就是创建的实例;获取到实例之后,就可以根据高德原生的方法对实例进行操作:

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

实现一个较为复杂地址搜索,地址标记、逆地理解析代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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 高德地图内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/u013262823/article/details/92795965

标签:

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
返回顶部