0

使用 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 节点。

对此的任何见解将不胜感激。

4

1 回答 1

0

关于

我想这样做是因为我需要根据我的 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 对象

演示

于 2018-12-03T13:21:11.097 回答