在React中使用google-map-react库获取拖动标记的位置,可以通过以下步骤实现:
GoogleMapReact
组件。useState
钩子函数来创建状态变量。GoogleMapReact
组件中,使用onChildMouseDown
和onChildMouseUp
事件处理函数来监听标记的拖动操作。onChildMouseDown
事件处理函数中,获取当前标记的位置信息,并将其存储到状态变量中。onChildMouseUp
事件处理函数中,获取标记的最终位置信息,并更新状态变量中的位置信息。下面是一个示例代码:
import React, { useState } from 'react';
import GoogleMapReact from 'google-map-react';
const MapWithMarker = () => {
const [markerPosition, setMarkerPosition] = useState({ lat: 0, lng: 0 });
const handleMarkerMouseDown = (event) => {
// 获取标记的初始位置信息
const { lat, lng } = event;
setMarkerPosition({ lat, lng });
};
const handleMarkerMouseUp = (event) => {
// 获取标记的最终位置信息
const { lat, lng } = event;
setMarkerPosition({ lat, lng });
};
return (
<div style={{ height: '400px', width: '100%' }}>
<GoogleMapReact
defaultCenter={{ lat: 0, lng: 0 }}
defaultZoom={10}
onChildMouseDown={handleMarkerMouseDown}
onChildMouseUp={handleMarkerMouseUp}
>
<Marker
lat={markerPosition.lat}
lng={markerPosition.lng}
/>
</GoogleMapReact>
</div>
);
};
const Marker = () => (
<div style={{ width: '20px', height: '20px', backgroundColor: 'red' }} />
);
export default MapWithMarker;
在上述代码中,我们创建了一个MapWithMarker
组件,其中包含一个GoogleMapReact
组件和一个自定义的Marker
组件。通过onChildMouseDown
和onChildMouseUp
事件处理函数,我们可以获取标记的位置信息,并将其存储到markerPosition
状态变量中。
请注意,上述代码中没有提及任何特定的腾讯云产品或链接地址,因为在React中获取拖动标记的位置与云计算品牌商无关。这是一个前端开发的问题,与云计算平台无关。
领取专属 10元无门槛券
手把手带您无忧上云