daily-share icon indicating copy to clipboard operation
daily-share copied to clipboard

高德地图初探(2021-01-28)

Open yaogengzhu opened this issue 4 years ago • 0 comments

import React, { useEffect, useRef, useState } from 'react'
import { createUseStyles } from 'react-jss'
import AMapLoader from '@amap/amap-jsapi-loader'
import zhizhen from '@/assets/images/zhizhen.png'

const styles = createUseStyles({
    content: {
        position: 'relative',
        width: '100%',
        height: '100%',
    },
    zhizhen: {
        position: 'absolute',
        top: '50%',
        left: '50%',
        width: '20px',
        height: '32px',
        marginLeft: '-10px',
        marginTop: '-25px',
        zIndex: 11,

        '& > img': {
            width: '100%',
            height: '100%'
        }
    }
})

export const MapC: React.FC = () => {
    const classes = styles()
    const [position, setPosition] = useState('')
    const [address, setAddress] = useState('')
    const mapRef: any = useRef()
    const geolocationRef: any = useRef()
    const geocoderRef: any = useRef()

    useEffect(() => {
        initMap()
        return () => {
            mapRef.current.destroy()
        }
    }, [])

    const mapMove = (e: any) => {
        if (mapRef.current) {
            console.log(mapRef.current, 'mapRef.current')
            const center = mapRef.current.getCenter() // 获取当前地图级别
            console.log(center.toString().split(','))
            geocoderRef.current.getAddress(center.toString().split(','), function(status: any, result: any) {
                if (status === 'complete' && result.info === 'OK') {
                    console.log(result.regeocode)
                    setAddress(result.regeocode.formattedAddress.split('区')[1])
                }
            })
            setPosition(center.toString())
            // mapRef.current.getCity(function(res: any) {
            //     console.log(res)
            // })

        }
        // 调用 geolocationRef.current
    }

    // 地图初始化
    const initMap = () => {
        AMapLoader.load({
            key: "b12200a099d1ff027ced85bd115ee8f3",
            "version": "1.4.15",
            "plugins": [],
        }).then((AMap) => {
            const map = new AMap.Map('container', {
                resizeEnable: true
            })
            mapRef.current = map
            AMap.plugin(['AMap.ToolBar', 'AMap.Driving', 'AMap.Geolocation', 'AMap.Geocoder'], function () {// 异步同时加载多个插件
                geocoderRef.current = new AMap.Geocoder()
                const geolocation = new AMap.Geolocation({
                    // 是否使用高精度定位,默认:true
                    // enableHighAccuracy: true,
                    // 设置定位超时时间,默认:无穷大
                    timeout: 10000,
                    // 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)
                    buttonOffset: new AMap.Pixel(10, 20),
                    //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
                    zoomToAccuracy: true,
                    //  定位按钮的排放位置,  RB表示右下
                    buttonPosition: 'RB',
                })
                geolocationRef.current = geolocation

                geolocation.getCurrentPosition(function (status: string, result: any) {
                    if (status === 'complete') {
                        onComplete(result)
                    } else {
                        onError(result)
                    }
                })
                map.addControl(geolocation)
                AMap.event.addListener(geolocation, 'complete', onComplete)
                AMap.event.addListener(geolocation, 'error', onError)
                function onComplete(data: any) {
                    // data是具体的定位信息
                    console.log(data)
                }

                function onError(data: any) {
                    // 定位出错
                    console.log(data)
                }

            })
            map.on('mapmove', mapMove)
        })


    }

    return (
        <div id="container" className={classes.content}>
            <div className={classes.zhizhen}>
                <img src={zhizhen} alt="" />
            </div>
        </div>
        // <div>
        //     <div>移动中心点:{position}</div>
        //     <div>当前地址:{ address }</div>
        // </div>
    )
}

yaogengzhu avatar Jan 28 '21 11:01 yaogengzhu