React Hook + antd design 引入腾讯地图实现

// import TMap from 'TMap';
import React, { useState, useEffect, useRef } from "react"
import { Modal, Button, Input } from 'antd';
import styles from '../index.less';
import Item from "antd/lib/list/Item";
const { Search } = Input;
export default (props) => {
    const [showModal, setshowModal] = useState(props.mapModal);
    const [map, setmap] = useState({});//地图对象
    const [suggestObj, setsuggestObj] = useState({});//储存搜索的内容;
    const [markerObj, setmarkerObj] = useState({});//中心点
    const [searchList, setsearchList] = useState([]);//搜索栏数据
    const [inputVal, setinputVal] = useState();//搜索栏内容
    const [searchObj, setsearchObj] = useState({});
    const [infoWindowList, setinfoWindowList] = useState(Array(10));
    useEffect(() => {
        if (showModal) {
            // 设置初始化
            const map = new TMap.Map(document.getElementById('container'), {
                center: new TMap.LatLng('纬度','经度'),
                zoom: 15,
                noClear: false,
            });
            // 设置搜索
            const searchItem = new TMap.service.Search({ pageSize: 10 });
            const suggest = new TMap.service.Suggestion({
                // 新建一个关键字输入提示类
                pageSize: 10, // 返回结果每页条目数
                region: 'XX城市', // 限制城市范围
                regionFix: true, // 搜索无结果时是否固定在当前城市
            });
            const marker = new TMap.MultiMarker({
                map: map,
                geometries: [],
            });

            let geocoder = new TMap.service.Geocoder();
            // 点击页面获取地点
            map.on('click', (event) => {
                console.log(event);
                marker.updateGeometries([
                    {
                        id: '1', // 点标注数据数组
                        position: event.latLng,
                    },
                ]);
                // 地址逆解析
                geocoder
                    .getAddress({ location: event.latLng }) // 将给定的坐标位置转换为地址
                    .then((result) => {
                        console.log(result);
                        // 显示搜索到的地址
                    });
            })
            setmap(map);
            setsuggestObj(suggest);
            setmarkerObj(marker);
            setsearchObj(searchItem)
        }
    }, [showModal]);

    // 点击搜素时,显示红点
    const onSearchVal = (e) => {
        const keyword = e;
        if (!keyword) return;
        infoWindowList.forEach((infoWindow) => {
            infoWindow.close();
        });
        infoWindowList.length = 0;
        markerObj.setGeometries([]);
        searchObj
            .searchRectangle({
                keyword: e,
                bounds: map.getBounds(),
            })
            .then(result => {
                result.data.forEach((item, index) => {
                    let geometries = markerObj.getGeometries();
                    // 设置展示窗口
                    let infoWindow = new TMap.InfoWindow({
                        map: map,
                        position: item.location,
                        content: `<h3>${item.title}</h3><p>地址:${item.address}</p><p>电话:${item.tel}</p>`,
                        offset: { x: 0, y: -50 },
                    });
                    infoWindow.close();

                    infoWindowList[index] = infoWindow;
                    geometries.push({
                        id: String(index),
                        position: item.location,
                    });
                    markerObj.updateGeometries(geometries);
                    markerObj.on('click', (e) => {
                        infoWindowList[Number(e.geometry.id)].open();
                    });
                });
                setinfoWindowList(infoWindowList)
            })


    }
    // 监听input框
    const onChangeInput = (e) => {
        const keyword = e.target.value;
        if (!keyword) {
            setsearchList([])
            return
        };
        suggestObj
            .getSuggestions({ keyword: keyword, location: map.getCenter() })
            .then(res => {
                setsearchList(res.data)
            })
    }

    // 点击li显示地址
    const suggestItem = (item) => {
        infoWindowList.forEach((infoWindow) => {
            infoWindow.close();
        });
        infoWindowList.length = 0;

        markerObj.setGeometries([]);
        markerObj.updateGeometries([
            {
                id: '0', // 点标注数据数组
                position: item.location,
            },
        ]);
        let infoWindow = new TMap.InfoWindow({
            map: map,
            position: item.location,
            content: `<h3>${item.title}</h3><p>地址:${item.address}</p>`,
            offset: { x: 0, y: -50 },
        });
        infoWindowList.push(infoWindow);
        setinfoWindowList(infoWindowList)
        map.setCenter(item.location);
        markerObj.on('click', (e) => {
            infoWindowList[Number(e.geometry.id)].open();
        });
        setinputVal(item.title)
        setsearchList([])
    }
    return (
        <Modal title="设置热搜地点" visible={props.mapModal} width={900}>
            <div id="container" className='text'></div>
            <div className={styles.panel}>
                <Search
                    placeholder="请输入搜索内容"
                    enterButton="搜索"
                    size="large"
                    onSearch={onSearchVal}
                    onChange={onChangeInput}
                    value={inputVal}
                />
                <ul className={styles.suggestionList}>
                    {
                        searchList.map(item => {
                            return <li onClick={() => suggestItem(item)} key={item.id}>{item.title}<span className={styles.item_info}>{item.address}</span></li>
                        })
                    }
                </ul>
            </div>
        </Modal>
    )
}

样式部分

/* 地图搜索 */
.panel{
    position: absolute;
    width: 300px;
    top: 30px;
    top: 100px;
    left: 30px;
    z-index: 9999;
}

.suggestionList{
    list-style: none;
    padding: 0 5px 10px;
    margin: 0;
    background: #fff;
    li{
        list-style: none;
        margin-top: 2px;
        background-color: #f6f6f6;
        text-decoration: none;
        font-size: 14px;
        color: black;
        display: block;
        cursor: pointer;
        padding: 0 10px;
        .item_info {
            font-size: 12px;
            color: grey;
        }
    }
    li a:hover:not(.header) {
        background-color: #eee;
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值