zoukankan      html  css  js  c++  java
  • taro3.x: h5地图兼容组件封装

    taro Map组件不兼容H5

    地图父组件:

    import React, { useEffect, useMemo, useRef, useState } from 'react'
    import Taro, { getCurrentInstance, useReady } from '@tarojs/taro'
    import { View, Text } from "@tarojs/components"
    import classnames from 'classnames'
    import find from 'lodash/find'
    
    import useNavData from '@hooks/useNavData'
    import SurroundMap from '@/components/surroundmap'
    import SurroundMapH5 from '@/components/surroundmaph5'
    import { SURROUND_TABS, ISurroundTab } from '@constants/house'
    import './index.scss'
    
    const houseSurround = () => {
        const params: any = getCurrentInstance().router?.params
        const currentTab: any = find(SURROUND_TABS, { type: params.type }) || {}
        const title = params.title
        const latitude = params.latitude
        const longitude = params.longitude
        const { contentHeight } = useNavData()
        const [tab, setTab] = useState<ISurroundTab>(currentTab)
        const ref = useRef<any>({})
    
        useReady(() => {
            Taro.setNavigationBarTitle({ title: title || '周边及配套' })
        })
    
        useEffect(() => {
            ref.current.updateTabMarkers && ref.current.updateTabMarkers(tab)
        }, [tab])
    
        const handleTabChange = (item: ISurroundTab) => {
            if (item.type === tab.type) {
                return
            }
            setTab(item)
        }
    
        const getMapInstance = useMemo(() => {
            return IS_H5 ?
                <SurroundMapH5
                    title={title}
                    latitude={latitude}
                    longitude={longitude}
                    ref={ref}
                /> :
                <SurroundMap
                    title={title}
                    b_latitude={latitude}
                    b_longitude={longitude}
                    ref={ref}
                />
        }, [])
    
        return (
            <View className="surround">
                <View className="surround-wrapper" style={{ height: `${contentHeight}px` }}>
                    {getMapInstance}
                    <View className="surround-tabs">
                        {
                            SURROUND_TABS.map((item: any, index: number) => (
                                <View
                                    key={index}
                                    onClick={() => handleTabChange(item)}
                                    className={classnames('tabs-item', tab.type === item.type && 'actived')}
                                >
                                    <Text className={classnames('iconfont', item.icon)}></Text>
                                    <Text className="text">{item.name}</Text>
                                </View>
                            ))
                        }
                    </View>
                </View>
            </View>
        )
    }
    
    export default houseSurround

    H5:组件需要在html文件引入百度地图插件

    import React, { forwardRef, useImperativeHandle } from 'react'
    import { useReady } from '@tarojs/taro'
    import { View } from "@tarojs/components"
    
    import { ISurroundTab } from '@/constants/house'
    import './index.scss'
    
    interface IProps {
        title: string
        latitude: number
        longitude: number
    }
    let map: any = null
    let local: any = null
    let circle: any = null
    let point: any = null
    let options: any = {}
    let icon_path: string = ''
    let searchResult: any[] = []
    
    const SurroundMapH5 = (props: IProps, ref: any) => {
        const { BMap } = window as any
        const { title, latitude, longitude } = props
    
        /**初始化地图参数 */
        useReady(() => {
            map = new BMap.Map("h5mapcontainer")
            point = new BMap.Point(longitude, latitude)
            map.centerAndZoom(point, 15)
            // 设定1000米圆形范围
            circle = new BMap.Circle(point, 1000, {
                fillColor: "blue",
                strokeWeight: 1,
                fillOpacity: 0.1,
                strokeOpacity: 0.1
            })
            map.addOverlay(circle)
            options.pageCapacity = 10
            options.renderOptions = { map, autoViewport: false, selectFirstResult: false }
            options.onSearchComplete = (results: any) => {
                searchResult = results && results.Hr
            }
            /**这里添加Marker覆盖LocalSearch默认的icon */
            options.onMarkersSet = () => {
                map.clearOverlays()
                map.addOverlay(circle)
                const myIcon: any = new BMap.Icon(icon_path, new BMap.Size(48, 72))
                myIcon.setImageSize(new BMap.Size(36,54))
                let marker: any = null
                searchResult.forEach(function (item: any) {
                    marker = new BMap.Marker(item.point)
                    marker.setIcon(myIcon)
                    map.addOverlay(marker)
                })
                setCenterLabel()
            }
            local = new BMap.LocalSearch(map, options)
            setCenterLabel()
        })
    
        const updateTabMarkers = (tab: ISurroundTab) => {
            icon_path = `https://static.fczx.com/www/assets/mini/${tab.type}.png`
            searchLocalNearby(tab.name)
        }
    
        useImperativeHandle(ref, () => (
            { updateTabMarkers }
        ), [])
    
        /**设置地图中心点标签 */
        const setCenterLabel = () => {
            const labelTemplate = '<div class="surround-bubble">' +
                '<p>' + title + '</p>' +
                '<div class="triangle-down"></div>' +
                '</div>'
            const centerLabel = new BMap.Label(labelTemplate, {
                position: point,
                offset: new BMap.Size(-45, -40)
            })
            centerLabel.setStyle({
                height: "35px", //高度
                border: "0",  //
                backgroundColor: "rgba(17, 164, 60, .9)",
                borderRadius: "4px",
                cursor: "pointer"
            })
            map.addOverlay(centerLabel)
        }
    
        const searchLocalNearby = (keymaps: string) => {
            local && local.searchNearby(keymaps, point, 1000)
        }
    
        return (
            <View className="h5-map" id="h5mapcontainer"></View>
        )
    }
    
    export default React.memo(forwardRef(SurroundMapH5))

    小程序组件:

    import React, { forwardRef, useImperativeHandle, useState } from 'react'
    import { View, Map } from "@tarojs/components"
    import QQMapWX from 'qqmap-wx-jssdk'
    import { ISurroundTab } from '@/constants/house'
    import { bMapTransQQMap, QQ_MAP_KEY } from '@utils/map'
    
    import './index.scss'
    
    interface IParamProps {
        title: string
        b_latitude: number
        b_longitude: number
    }
    
    const SurroundMap = (props: IParamProps, ref: any) => {
        const [markers, setMarkers] = useState<any[]>([])
        const mapsdk = new QQMapWX({ key: QQ_MAP_KEY })
        const { latitude, longitude } = bMapTransQQMap(props.b_latitude, props.b_longitude)
    
        const houseMarker = {
            latitude: latitude,
            longitude: longitude,
             30,
            height: 30,
            iconPath: 'https://static.fczx.com/www/assets/mini/location.png',
            callout: {
                content: props.title,
                color: '#fff',
                fontSize: 14,
                borderWidth: 2,
                borderRadius: 5,
                borderColor: '#11a43c',
                bgColor: '#11a43c',
                padding: 8,
                display: 'ALWAYS',
                textAlign: 'center'
            }
        }
    
        useImperativeHandle(ref, () => (
            {
                updateTabMarkers: updateTabMarkers
            }
        ), [])
    
        const updateTabMarkers = (tab: ISurroundTab) => {
            if (tab.name) {
                mapsdk.search({
                    keyword: tab.name,
                    location: { latitude, longitude },
                    success: (result: any) => {
                        const surroundMarkers: any[] = []
                        for (const item of result.data) {
                            surroundMarkers.push({
                                latitude: item.location.lat,
                                longitude: item.location.lng,
                                 24,
                                height: 36,
                                iconPath: `https://static.fczx.com/www/assets/mini/${tab.type}.png`,
                                callout: {
                                    content: `${item.title}
    ${item.address}`,
                                    color: '#333',
                                    fontSize: 14,
                                    borderWidth: 2,
                                    borderRadius: 5,
                                    borderColor: '#fff',
                                    padding: 8,
                                    display: 'BYCLICK'
                                }
                            })
                        }
                        setMarkers([houseMarker, ...surroundMarkers])
                    }
                })
            } else {
                setMarkers([houseMarker])
            }
        }
        return (
            <View className="mini-map">
                <Map
                    id="surroundMap"
                    className="surround-map"
                    latitude={latitude}
                    longitude={longitude}
                    markers={markers}
                >
                </Map>
            </View>
        )
    }
    
    export default React.memo(forwardRef(SurroundMap))
  • 相关阅读:
    iOS网络编程开发-数据加密
    iOS网络编程开发GET请求和POST请求
    iOS网络编程开发—HTTP协议
    iOS网络编程开发—网络编程基础
    iOS多线程技术—自定义NSOperation
    iOS多线程技术—NSOperation用法
    大家一起和snailren学java-(一)对象导论
    大家一起和snailren学java-(序)
    Hadoop 2.7.0模拟分布式实验环境搭建[亲测]
    LeetCode:103Binary Tree Zigzag Level Order Traversal
  • 原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/14451401.html
Copyright © 2011-2022 走看看