我使用https://github.com/tomchentw/react-google-maps。 我需要通过点击按钮来更改我的地图语言。我只能改变一次,例如从ja到ar,但不能改回ja。我怎么能这样做?
<MyMapComponent
key={language}
googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${key}&language=${this.props.language}`}
isMarkerShown
containerElement={
<div style={{ height: '100%' }} />
}
mapElement={
<div style={{ height: '100%' }} />
}
loadingElement={
<div style={{ height: '100%' }} />
}
/>
以下是没有反应http://jsfiddle.net/2AKqM/
的示例对不起我的英文
答案 0 :(得分:0)
显然,这是因为在页面上加载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之前。
以下示例演示了如何处理此方案,特别是:
示例:
/*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>
)
}
}
&#13;