React Native Map从State加载Marker图标技术咨询
给React Native Marker匹配对应图标方案
很简单,咱们只需要把markers里商户的分类和markerIcons里的图标key对应上,就能给每个Marker加载专属图标了,我给你一步步拆解:
1. 先确保markerIcons的结构正确
首先你的markerIcons里要以商户分类作为key,值是提前用require导入的图标资源(React Native里不能动态拼接require路径,所以必须预先导入好):
this.state = { width : Dimensions.get('window').width, height : Dimensions.get('window').height, initialPosition: { latitude: 48.866667, // 注意你原代码里拼错了latitiude,改成latitude longitude: 2.333333, latitudeDelta:LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA }, // 示例:key是商户分类,值是对应图标 markerIcons: { coffee: require('./assets/coffee-shop.png'), restaurant: require('./assets/restaurant.png'), pharmacy: require('./assets/pharmacy.png') }, // markers里每个商户要带category字段,和上面的key对应 markers: [ { id: 1, latitude: 48.86, longitude: 2.32, title: "街角咖啡店", category: "coffee" // 对应markerIcons里的coffee }, { id: 2, latitude: 48.87, longitude: 2.34, title: "法式餐厅", category: "restaurant" // 对应markerIcons里的restaurant } ], };
注意:你原state里的latitiude拼写错误,已经改成正确的latitude了,避免地图定位出问题~
2. 在render里遍历Markers并匹配图标
不用再用Object.keys遍历啦,直接遍历markers数组,每个Marker的icon属性就取markerIcons里对应分类的图标,还可以加个默认图标防止找不到对应分类的情况:
render() { const { markers, markerIcons, initialPosition } = this.state; return ( <MapView style={{ flex: 1, width: this.state.width, height: this.state.height }} initialRegion={initialPosition} > {/* 遍历markers数组生成Marker */} {markers.map(marker => ( <MapView.Marker key={marker.id} // 必须加唯一key coordinate={{ latitude: marker.latitude, longitude: marker.longitude }} title={marker.title} // 匹配对应图标,找不到就用默认图标 icon={markerIcons[marker.category] || require('./assets/default-marker.png')} /> ))} </MapView> ); }
3. 额外注意事项
- 所有图标资源的路径要确保正确,比如
./assets/xxx.png是相对于当前组件文件的路径; - 如果你的
markers里的分类字段不是category,改成你实际用的字段名就行,比如type、businessType; - 要是图标显示大小不合适,可以用
Image组件包裹图标,再通过style调整尺寸,然后把这个Image作为Marker的icon属性值:icon={ <Image source={markerIcons[marker.category] || require('./assets/default-marker.png')} style={{ width: 30, height: 30 }} /> }
这样每个商户Marker就能加载到对应的图标啦!
内容的提问来源于stack exchange,提问作者E.D
相关产品推荐
相关产品推荐

