使用map函数为GoogleMapReact批量添加标记失败求助
解决GoogleMapReact中map生成标记不渲染的问题
我一眼就发现了代码里的一个关键错误,这应该就是标记无法渲染的核心原因!
问题根源:坐标属性写错了
在你通过map生成FontAwesomeIcon的代码里,lng属性的值被错误地设置成了纬度值:
return <FontAwesomeIcon icon={faHome} size={"2x"} key={index} listing={listing} lat={listing.coordinates.lat} lng={listing.coordinates.lat} />
这里的lng={listing.coordinates.lat}明显是笔误,正确的写法应该是lng={listing.coordinates.lng}。
GoogleMapReact的子组件必须依赖正确的lat(纬度)和lng(经度)属性来定位标记,当两个属性值完全相同时,标记会被定位到一个无效的地理坐标点,自然就无法在地图上显示出来。
修正后的代码片段
render() { const {center, zoom} = this.props; const listingPins = this.props.testList.map((listing, index) => { console.log(listing); if (listing.coordinates.lat === null || listing.coordinates.lng === null){ return null } else{ // 修正了lng属性的值 return <FontAwesomeIcon icon={faHome} size={"2x"} key={index} listing={listing} lat={listing.coordinates.lat} lng={listing.coordinates.lng} /> } }); console.log("TEST"); console.log(listingPins); return ( <div style={{ height: '100vh', width: '100%' }}> <GoogleMapReact bootstrapURLKeys={{ key: "key" }} center={center} zoom={zoom} > {listingPins} </GoogleMapReact> </div> ); }
额外排查建议
- 检查
console.log(listingPins)的输出,确保数组里包含有效的FontAwesomeIcon元素,而不是全为null(这说明你的过滤逻辑可能把所有有效坐标都排除了); - 尽量避免用
index作为组件的key,如果你的listing对象有唯一ID(比如listing.id),改用这个唯一值作为key,能避免列表动态更新时出现的渲染异常; - 可以给
FontAwesomeIcon添加一个显眼的样式(比如style={{color: 'red', backgroundColor: 'white', padding: '2px'}}),排除图标颜色和地图背景重合导致的“看不见”问题。
内容的提问来源于stack exchange,提问作者justinseo
相关产品推荐
相关产品推荐

