代码之家  ›  专栏  ›  技术社区  ›  rakitin

如何在react中获取对google地图标记的dom节点的引用?

  •  0
  • rakitin  · 技术社区  · 6 年前

    使用google map s 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;
    }
    

    render() {
      return (
        <div style={{ height: mapHeight }} ref="map">
        ... 
    

    然后用来设置 node 然后用来更新地图。

    用地图标记怎么做?标记不需要创建dom节点,因此无法获取对标记的引用。

     this.marker = new google.maps.Marker({someOptions});  <----- no dom node needed
    

    我想这样做是因为我需要根据redux存储中的某个值动态更改标记的图标。我试过通过道具来改变图标(见下文),但它以某种方式阻止了图标标记的可拖动性,即使draggable设置为true。

         return (
          <Marker 
            key={foo} 
            position={latLngPos}
            icon={ active ? activeIcon : defaultIcon }
            draggable={true}
            onDragstart={() => { return this.handleMapMarkerDragStart();}} 
            onDragend={() => { return this.handleMapMarkerDrop();}} 
          />);
    

    我怀疑事情有点奇怪,因为要让google的maps api与react一起工作,组件必须处理实际的dom节点,而不是虚拟的dom节点。

    如果您对此有任何了解,我们将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Vadim Gremyachev    6 年前

    关于

    我想这样做是因为我需要动态地更改 基于我的redux商店中的某个值的标记。我试过改变 图标通过道具(见下文),但它以某种方式阻止了图标 即使draggable设置为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 component onDragstart 事件 此刻的听众 google-maps-react 图书馆,但可能是

    Demo

    推荐文章