Valentin Baltadzhiev
Valentin Baltadzhiev

Reputation: 195

ReactJS google maps component won't rerender

I am writing a web app that allows you to enter an address and renders a map with the directions from the given address to 4 other (hard-coded for now) addresses. Everything works fine, until I want to enter a new address and refresh the map

I am using tomchentw/react-google-maps library to get the directions and render the map

Here is my code:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { compose, withProps, withPropsOnChange, withState, lifecycle } from     "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
DirectionsRenderer,
} from "react-google-maps";

const MapWithADirectionsRenderer = compose(
withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `500px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
}),        
withScriptjs,
withGoogleMap,
lifecycle({
    componentDidMount() {
        this.setState({
            newDirections: [],
        });

        let destinations = ['Imperial College', '123 Aldersgate Street', '17 Moorgate', 'Spitafields Market']

        const DirectionsService = new google.maps.DirectionsService();

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[0],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[1],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions1: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[2],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions2: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[3],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions3: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });
    }      
})
)(props =>
<GoogleMap
    defaultZoom={7}
    defaultCenter={new google.maps.LatLng(51.435341, -0.131116)}
>
    {props.directions && <DirectionsRenderer directions={props.newDirections[0]} />}
    {props.directions1 && <DirectionsRenderer directions={props.newDirections[1]} />}
    {props.directions2 && <DirectionsRenderer directions={props.newDirections[2]} />}
    {props.directions3 && <DirectionsRenderer directions={props.newDirections[3]} />}

</GoogleMap>
);

class AddressForm extends React.Component {
constructor(props) {
    super(props);
    this.state = { value: '' };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
    this.setState({ value: event.target.value });
}

handleSubmit(event) {

    let targetAddress = this.state.value;
    ReactDOM.render(<MapWithADirectionsRenderer origin={targetAddress} destination='Imperial College' />, document.getElementById('mapplace'));
    event.preventDefault();

}

render() {
    return (
        <form onSubmit={this.handleSubmit}>
            <label>
                Address:
                <input type="text" value={this.state.value} onChange={this.handleChange} />
            </label>
            <input type="submit" value="submit" />
        </form>
    );
}
}

registerServiceWorker();


ReactDOM.render(<AddressForm />, document.getElementById('formplace'));

Upon load the user sees only the component rendered. After an address is entered and the form is submitted the map gets displayed properly. However, when I enter a new address and resubmit the form, the map doesn't rerender.

Is there something I am missing?

Upvotes: 3

Views: 1738

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59378

You might be looking for the function componentDidUpdate which is run after any updating occurs, componentDidMount will only be called once after the first render.

I would propose the following list of changes:

a) introduce a separate function to draw routes:

 drawRoutes() {
        let destinations = ['Imperial College', '123 Aldersgate Street', '17 Moorgate', 'Spitafields Market']
        const DirectionsService = new google.maps.DirectionsService();
        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[0],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[1],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions1: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[2],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions2: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[3],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions3: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });
    }

b) set the initial state:

  componentWillMount() {
       this.setState({
                newDirections: [],
       });
   }

c) draw routes:

componentDidMount() {
        this.drawRoutes();
}

d) redraw routes if address has been changed

componentDidUpdate(prevProps, prevState) {
     if (prevProps.origin !== this.props.origin) {
          this.setState({
              directions: null,
              directions1: null,
              directions2: null,
              directions3: null,
              newDirections: []
         });
         this.drawRoutes();
     }
}

Demo

Upvotes: 1

Related Questions