我正在编写一个 Web 应用程序,允许您输入地址并呈现地图,其中包含从给定地址到其他 4 个(目前是硬编码(地址的方向。一切正常,直到我想输入新地址并刷新地图
我正在使用tomchentw/react-google-maps库来获取方向并渲染地图
这是我的代码:
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'));
加载时,用户只能看到渲染的组件。输入地址并提交表单后,地图将正确显示。但是,当我输入新地址并重新提交表单时,地图不会重新渲染。
我错过了什么吗?
您可能正在寻找在进行任何更新后运行的函数componentDidUpdate
,componentDidMount
在第一次渲染后只会调用一次。
我建议以下修改清单:
a( 引入一个单独的函数来绘制路线:
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( 设置初始状态:
componentWillMount() {
this.setState({
newDirections: [],
});
}
c( 绘制路线:
componentDidMount() {
this.drawRoutes();
}
d( 如果地址已更改,则重绘路由
componentDidUpdate(prevProps, prevState) {
if (prevProps.origin !== this.props.origin) {
this.setState({
directions: null,
directions1: null,
directions2: null,
directions3: null,
newDirections: []
});
this.drawRoutes();
}
}
演示