React implementation example using Amap (react-amap)

React implementation example using Amap (react-amap)

The PC version of React was refactored to use Amap. After searching for information, I found a map plug-in react-amap that is encapsulated for React. Official website: https://elemefe.github.io/react-amap/components/map. If you are interested, you can check out the API.

react-amap installation

1. Use npm to install, currently version 1.2.8:

cnpm i react-amap

2. Directly use sdn to introduce

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

React-amap usage

import React,{Component} from 'react'
import {Map,Marker} from 'react-amap'
const mapKey = '1234567809843asadasd' //You need to apply for it on the official website of Amap 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

In this case, a simple map will be initialized.

insert image description here

In the actual development process, you will have more complex usage scenarios. For example, you need to mark points, zoom in and out on the map, locate the current location, search for locations, and so on. The requirements are roughly as shown in the figure below:

insert image description here

In this case, it is necessary to introduce the concepts of plug-ins and components.
ToolBar, Scale plug-in

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

Marker map marker

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

InfoWindow form component

<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>

The created event is used to achieve more advanced usage requirements. It is called after the Amap native instance is successfully created. The parameter is the created instance. After obtaining the instance, you can operate the instance according to the Amap native method:

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

Implement a more complex address search, address marking, and reverse geography parsing code:

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
        }
    }

    //Change data general method (single layer)

    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, //Using the known coordinates as the center point and radius as the radius, return the points of interest and road information within the range extensions: "all" //Return the address description and nearby points of interest and road information, the default is "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>Positioning....</div>'

                window.AMap.plugin(["AMap.Geocoder"],function(){
                    geocoder = new AMap.Geocoder({
                        radius:1000, //Using the known coordinates as the center point and radius as the radius, return the points of interest and road information within the range extensions: "all" //Return the address description and nearby points of interest and road information, the default is "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="Office Location"
                       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">Detailed address:
                        {signAddrList.addr}
                    </div>
                </Modal>
            </div>
        )
    }
}

export default Address

This is the end of this article about the implementation example of using Amap in React (react-amap). For more relevant React Amap content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use Amap API in Java environment
  • Android Gaode map marker custom pop-up window
  • WeChat applet Amap multi-point route planning process example detailed explanation
  • Detailed steps of integrating SpringBoot with Mybatis to realize Amap positioning and store data in the database
  • How to use Amap in front-end Vue
  • WeChat applet implements weather component (dynamic effect) based on Amap API
  • vue+Amap realizes map search and click positioning operation
  • React+Amap obtains latitude and longitude in real time and locates the address

<<:  Nginx reverse proxy and load balancing practice

>>:  mysql add, delete, modify and query basic statements

Recommend

Modify the maximum number of mysql connections and configuration files in docker

1. Find the mysql image docker ps 2. Enter the mi...

Vue+spring boot realizes the verification code function

This article example shares the specific code of ...

Detailed explanation of MySQL master-slave inconsistency and solutions

1. MySQL master-slave asynchrony 1.1 Network Dela...

Detailed steps for developing WeChat mini-programs using Typescript

We don't need to elaborate too much on the ad...

How to simulate network packet loss and delay in Linux

netem and tc: netem is a network simulation modul...

The role of MySQL 8's new feature window functions

New features in MySQL 8.0 include: Full out-of-th...

Solve the problem of blocking positioning DDL in MySQL 5.7

In the previous article "MySQL table structu...

Why can't the MP4 format video embedded in HTML be played?

The following code is in my test.html. The video c...

Implement QR code scanning function through Vue

hint This plug-in can only be accessed under the ...

Implementation of deploying Apollo configuration center using docker in CentOS7

Apollo open source address: https://github.com/ct...

CSS mimics remote control buttons

Note: This demo is tested in the mini program env...

How to bypass unknown field names in MySQL

Preface This article introduces the fifth questio...