我正在尝试使用react和Google Maps API。
TL:TR =>如何使用google.maps
和React
欲望功能:需要在<select>
标签中快速加载地图的位置选择代理,选择航点并使用航点渲染地图。我只需要优化航点。
没有反应就很容易了。
现在只需使用硬编码数据(钢铁侠,托尔......),并且有一个纬度,长度为origin
和destination
用于谷歌地图,但我稍后将使用快递从Azure获取此信息。航点也将来自数据库。
问题在于反应我不能使用Google对象,因为它不存在,因为它被加载到全局范围async。所以这个new google.maps.Map
不起作用。
试试这个npm包load-google-maps-api
,但仍然没有运气。
很长的解释,那么当您需要的信息可能发生变化时,如何使用Maps JavaScript API及其在react应用程序中的所有功能。
例如,我不能这样做,因为在选择代理之前我不知道该中心。使用<script>
,它将作为回调执行
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
我的代码在这里https://github.com/adrianwix/GoogleMapApi你想看看。
你可以这样。
componentDidUpdate() {
if(!this.state.loadGoogleMap) {
loadGoogleMap();
}
}
async loadGoogleMap() {
await _loadGoogleMap();
this.setState({ loadGoogleMap: true });
}