React函数式组件中实现点击react-google-maps添加多标记
实现点击Google Maps添加多标记的解决方案
核心思路
通过React的useState钩子管理标记坐标数组,在地图点击事件中捕获经纬度并更新数组,最终遍历数组渲染所有标记。
完整代码实现
import { useState } from 'react'; import { LoadScript, GoogleMap, Polyline, MarkerF } from '@react-google-maps/api'; const MapComponent = () => { const mapKey = '你的Google Maps API密钥'; // 地图初始中心点,根据需求修改 const center = { lat: 39.9042, lng: 116.4074 }; // 维护路径点与标记的数组,支持初始值 const [trucks, setTrucks] = useState([]); return ( <div> <LoadScript googleMapsApiKey={mapKey}> <GoogleMap mapContainerStyle={{ width: '100%', height: '85vh', }} center={center} zoom={19} onClick={(ev) => { // 捕获点击位置的经纬度 const newMarker = { lat: ev.latLng.lat(), lng: ev.latLng.lng() }; // 以不可变方式更新数组,添加新标记 setTrucks(prev => [...prev, newMarker]); }} > <Polyline path={trucks} geodesic={true} options={{ strokeColor: "blue", strokeOpacity: 0.5, // 修正原代码错误:透明度取值范围为0-1 strokeWeight: 4, }} /> {/* 遍历数组渲染所有标记 */} {trucks?.map((point, idx) => ( <MarkerF key={`marker-${point.lat}-${point.lng}-${idx}`} // 用坐标+索引生成稳定key position={point} /> ))} </GoogleMap> </LoadScript> </div> ); }; export default MapComponent;
关键说明
- 状态管理:使用
useState维护标记数组,每次点击通过展开运算符创建新数组,保证React状态的不可变性。 - 事件处理:从地图点击事件对象
ev中提取latLng属性,转换为Google Maps要求的坐标对象格式。 - 渲染优化:避免直接使用索引作为
key,结合经纬度生成更唯一的key,防止组件渲染异常。 - 参数修正:原代码中
strokeOpacity:5不符合API规范,改为0-1之间的合理值(示例为0.5)。
内容的提问来源于stack exchange,提问作者Aayush Bhatt
相关产品推荐
相关产品推荐

