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,
width: 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,
width: 24,
height: 36,
iconPath: `https://static.fczx.com/www/assets/mini/${tab.type}.png`,
callout: {
content: `${item.title}\n${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))

浙公网安备 33010602011771号