显然,它是由于在页面上多次加载 Google Maps API 时发生冲突而发生的。您可能已经使用withScriptjs
加载 Google Maps API,如下所示:
export const MyMapComponent = compose(
withScriptjs,
withGoogleMap
)(props => {
return (
<GoogleMap googleMapURL={props.googleMapsUrl} defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
<Marker position={{ lat: -34.397, lng: 150.644 }} />
</GoogleMap>
)
});
关键是,一旦提供了语言,就会重新创建组件,这反过来又会导致再次加载 Google Maps API。不支持这种情况,并且通常会在控制台中显示以下错误:
您已在此页面上多次包含 Google Maps API。这可能会导致意外错误。
为防止此类冲突,可以清除 Google Maps API
window.google.maps = {};
在加载另一种语言的 API 之前。
下面的示例演示了如何处理这种情况,特别是:
- 为当前语言加载的 Google Maps API 存储到缓存中
- 如果已根据所选语言加载了 Google Maps API,则将从缓存中重新存储该 API,否则将清除该 API 并再次加载
例子:
/*global google*/
import React from "react";
import { compose, withProps } from "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker
} from "react-google-maps";
const key = "AIzaSyDurZQBXjtSzKeieXwtFeGe-jhZu-HEGQU";
export const MyMapComponent = compose(
withScriptjs,
withGoogleMap
)(props => {
return (
<GoogleMap googleMapURL={props.googleMapsUrl} defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
<Marker position={{ lat: -34.397, lng: 150.644 }} />
</GoogleMap>
)
});
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
language: 'en',
nextLanguage: null,
googleMapsUrl: `https://maps.googleapis.com/maps/api/js?key=${key}&language=en`,
cacheMaps: {}
};
}
handleChange(e) {
this.setState({ nextLanguage: e.target.value });
}
changeGoogleMapsLanguage = () => {
this.setState({ googleMapsUrl: `https://maps.googleapis.com/maps/api/js?key=${key}&language=${this.state.nextLanguage}` });
this.setState({ language: this.state.nextLanguage });
let cacheMaps = { ...this.state.cacheMaps }
cacheMaps[this.state.language] = window.google.maps;
this.setState({ cacheMaps });
if (this.state.nextLanguage in cacheMaps) {
window.google.maps = cacheMaps[this.state.nextLanguage]; //load Maps API from cache
console.log("Loading from cache..");
}
else {
window.google.maps = {}; //clear Maps components
}
}
render() {
return (
<div>
<input type="text" id="language" defaultValue={this.state.language} onChange={this.handleChange.bind(this)} />
<button id="localization-button" onClick={this.changeGoogleMapsLanguage.bind(this)} >Change Language</button>
<MyMapComponent googleMapURL={this.state.googleMapsUrl}
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
key={this.state.googleMapsUrl}
/>
</div>
)
}
}