如何实现谷歌地图javascript api与reactjs集成?

时间:2016-02-18 07:31:43

标签: javascript html google-maps google-maps-api-3 reactjs

使用reactjs,我可以显示法线贴图,而无需任何额外的功能。但是,如果我尝试添加任何额外的组件,例如"放置搜索框",它就无法使用我的代码。它抛出一个错误(" SearchBox Undefined")。有没有办法做这个集成部分?

这是我的代码,

var DirectionMap = React.createClass({
  getDefaultProps: function () {
      return {
          initialZoom: 8,
          mapCenterLat: 43.6425569,
          mapCenterLng: -79.4073126,
      };
  },
  componentDidMount: function (rootNode) {
      var mapOptions = {
          center: this.mapCenterLatLng(),
          zoom: this.props.initialZoom
      },
      map = new google.maps.Map(this.getDOMNode(), mapOptions);
      // Create the search box and link it to the UI element.
      var input = document.getElementById('pac-input');
      var searchBox = new google.maps.places.SearchBox(input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
      var markers = [];
      var marker = new google.maps.Marker({position: this.mapCenterLatLng(), title: 'Hi', map: map});
      searchBox.addListener('places_changed', function() {
        var places = searchBox.getPlaces();

        if (places.length == 0) {
          return;
        }
        markers.forEach(function(marker) {
          marker.setMap(null);
        });
        markers = [];
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function(place) {
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };

        // Create a marker for each place.
        markers.push(new google.maps.Marker({
          map: map,
          icon: icon,
          title: place.name,
          position: place.geometry.location
        }));

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      map.fitBounds(bounds);
      });
      this.setState({map: map});
  },
  mapCenterLatLng: function () {
      var props = this.props;
      return new google.maps.LatLng(props.mapCenterLat, props.mapCenterLng);
  },
  render: function () {
      return (
        <div className="embed-item-elem">
          <input id="pac-input" className="controls" type="text" placeholder="Search Box" />
        </div>
      );
  }
});

1 个答案:

答案 0 :(得分:0)

此行看起来对我无效:

return (
        <div className="embed-item-elem">
          <input id="pac-input" className="controls" type="text" placeholder="Search Box" />
        </div>
      );

你不应该把它当作一串HTML来处理,即

return ('
        <div className="embed-item-elem">
          <input id="pac-input" className="controls" type="text" placeholder="Search Box" />
        </div>
      ');