Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google maps in react

We tried unsuccessfully to have google maps embedded in our app. The autocomplete field has not been a problem but we tried to insert the map the same way and something went wrong.

We use react 0.12 and we create a component for the autocomplete field.

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;
like image 610
LucaG Avatar asked Apr 09 '15 07:04

LucaG


1 Answers

try with this code:

component:

    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;

then to show it in a page:

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

css:

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

this works for me

like image 173
Francesca Avatar answered Sep 21 '22 18:09

Francesca