使用React加载异步Google Maps JavaScript API

问题描述 投票:0回答:1

我正在尝试使用react和Google Maps API。

TL:TR =>如何使用google.maps和React

欲望功能:需要在<select>标签中快速加载地图的位置选择代理,选择航点并使用航点渲染地图。我只需要优化航点。

没有反应就很容易了。

现在只需使用硬编码数据(钢铁侠,托尔......),并且有一个纬度,长度为origindestination用于谷歌地图,但我稍后将使用快递从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你想看看。

javascript reactjs asynchronous google-maps-api-3
1个回答
0
投票

你可以这样。

componentDidUpdate() {
    if(!this.state.loadGoogleMap) {
        loadGoogleMap();
    }
}
async loadGoogleMap() {
    await _loadGoogleMap();

    this.setState({ loadGoogleMap: true });
}
© www.soinside.com 2019 - 2024. All rights reserved.