reactjs - 如何在反应中获得对谷歌地图标记的dom节点的引用?
问题描述
使用 google-maps-react npm 包,我可以获得对地图 dom 节点的引用,如下所示:
loadMap() {
const maps = this.props.google.maps;
const mapRef = this.refs.map; <---- ref set in render function on dom node
const node = ReactDOM.findDOMNode(mapRef); <--- the dom node
...
this.map = new maps.Map(node, mapConfig);
this.mapRef = mapRef;
}
这很简单,因为 mapref 是在 render 方法中设置的:
render() {
return (
<div style={{ height: mapHeight }} ref="map">
...
然后用于设置node
,然后用于新建地图。
我将如何使用地图的标记来做到这一点?标记不需要创建 dom 节点,因此我无法获得标记的引用。
this.marker = new google.maps.Marker({someOptions}); <----- no dom node needed
我想这样做是因为我需要根据我的 redux 存储中的某个值动态更改标记的图标。我曾尝试通过道具更改图标(见下文),但它以某种方式阻止图标标记可拖动,即使可拖动设置为 true。
return (
<Marker
key={foo}
position={latLngPos}
icon={ active ? activeIcon : defaultIcon }
draggable={true}
onDragstart={() => { return this.handleMapMarkerDragStart();}}
onDragend={() => { return this.handleMapMarkerDrop();}}
/>);
我怀疑事情很奇怪,因为要让谷歌的地图 api 与 react 一起工作,组件必须处理实际的 dom 节点而不是虚拟 dom 节点。
对此的任何见解将不胜感激。
解决方案
关于
我想这样做是因为我需要根据我的 redux 存储中的某个值动态更改标记的图标。我曾尝试通过道具更改图标(见下文),但它以某种方式阻止图标标记可拖动,即使可拖动设置为 true。
以下示例演示了如何:
- 将标记设置为可拖动
- 为每个标记设置自定义图标
例子
const handleDragEnd = (props, marker, event) => {
console.log(event.latLng);
};
const defaultIcon =
"http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png";
const activeIcon =
"http://maps.google.com/mapfiles/kml/pushpin/pink-pushpin.png";
const MapWrapper = props => {
return (
<div className="map-container">
<Map
google={props.google}
className={"map"}
zoom={4}
initialCenter={{ lat: -24.9923319, lng: 135.2252427 }}
>
{props.places.map((place, i) => {
const active = i % 2 === 0;
return (
<Marker
icon={active ? activeIcon : defaultIcon}
key={place.id}
position={{ lat: place.lat, lng: place.lng }}
draggable={true}
onDragend={handleDragEnd}
/>
);
})}
</Map>
</div>
);
};
注意:
Marker
组件onDragstart
目前在库中不支持事件监听器google-maps-react
,但可以直接附加到 Google Maps Marker 对象
推荐阅读
- bash - 如何在 bash 中测试变量是否为关联数组?
- python - 如何将for循环更改为while循环
- python - 将 pandas DataFrame() 插入 MySQL 表会引发 ProgrammingError
- java - 无法使用 Java Spring 完成发布
- spring - 如何在spring data jpa派生查询中使用带有嵌入字段的order by子句?
- docker - 无法访问 kubernetes nodeport 服务
- reactjs - 如何制作更小的单选按钮
- blockchain - 你如何访问区块链的原始公共数据,然后从中读取交易账本?
- typescript - 为什么 Typescript 交集只在对象上表现得像联合?
- node.js - 警告:收到 `value` 属性的 NaN。如果这是预期的,请将值转换为字符串。多部分形式的输入