谷歌地图在反应

Google maps in react

本文关键字:谷歌地图      更新时间:2023-09-26

我们试图在应用程序中嵌入谷歌地图,但没有成功。自动完成字段不是问题,但我们试图以同样的方式插入地图,结果出现了问题。

我们使用react 0.12,并为自动完成字段创建一个组件。

var Geocomplete = React.createClass({
   componentDidMount: function() {
       var inputOptions = {componentRestrictions: {country: 'it'}};
       new google.maps.places.Autocomplete(
           document.getElementById('searchTextField'),
           inputOptions);
   },
   buttonClick: function() {
       alert(this.refs.searchField.getDOMNode().value);
   },
   //         <div id="map-canvas"></div>
   render: function() {
       return (
           <div>
               <label htmlFor="searchTextField">
               Please Insert an address:
               </label>
               <br/>
               <input ref='searchField' id="searchTextField" type="text" size="50"/>
               <br/>
               <button onClick={this.buttonClick}>Submit</button>
               <br />
           </div>
           );
   }
});

module.exports = Geocomplete;

尝试使用以下代码:

组件:

    var GoogleMap = React.createClass({
    getDefaultProps: function () {
        return {
            initialZoom: 6,
            mapCenterLat: 53.5333,
            mapCenterLng: -113.4073126
        };
    },
    componentDidMount: function (rootNode) {
        var mapOptions = {
                center: this.mapCenterLatLng(),
                zoom: this.props.initialZoom
            },
            map = new google.maps.Map(this.getDOMNode(), mapOptions);
        var marker = new google.maps.Marker({position: this.mapCenterLatLng(), title: 'Hi', map: map});
        this.setState({map: map});
    },
    mapCenterLatLng: function () {
        var props = this.props;
        return new google.maps.LatLng(props.mapCenterLat, props.mapCenterLng);
    },
    render: function () {
        return (
            <div className='map-gic'></div>
            );
    }
});
module.exports = GoogleMap;

然后在页面中显示:

   <GoogleMap mlat="55.0000" mlong="-113.0000"/>

css:

.map-gic {
  height: 300px;
  width: 100%;
}

这对我有效

我发现了更简单的实现。选中此项:https://github.com/BrodaNoel/devseverywhere/blob/master/src/pages/AnalyticsPage/AnalyticsPage.jsx#L227它使用的是google-map-react npm包。