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/react-amap@0.2.5/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

How to install git on linux

1. Introduction Git is a free, open source distri...

Simple implementation method of vue3 source code analysis

Table of contents Preface 🍹Preparation 🍲vue3 usag...

How to use Node.js to determine whether a png image has transparent pixels

background PNG images take up more storage space ...

How to Dockerize a Python Django Application

Docker is an open source project that provides an...

Mysql implements null value first/last method example

Preface We already know that MySQL uses the SQL S...

Discussion on the problem of garbled characters in iframe page parameters

I encountered a very unusual parameter garbled pro...

How to set up Referer in Nginx to prevent image theft

If the server's images are hotlinked by other...

Some improvements in MySQL 8.0.24 Release Note

Table of contents 1. Connection Management 2. Imp...

MySQL uses binlog logs to implement data recovery

MySQL binlog is a very important log in MySQL log...

Docker Swarm from deployment to basic operations

About Docker Swarm Docker Swarm consists of two p...

Nginx stream configuration proxy (Nginx TCP/UDP load balancing)

Prelude We all know that nginx is an excellent re...

HTML tutorial, HTML default style

html , address , blockquote , body , dd , div , d...

Implementation of react loop data (list)

First, let's simulate the data coming from th...

The use and difference between vue3 watch and watchEffect

1.watch listener Introducing watch import { ref, ...

Design Story: The Security Guard Who Can't Remember License Plates

<br />In order to manage the vehicles enteri...