如何加载谷歌地图api< script>在我的反应应用程序只有当它是必需的? [英] How to load the google maps api <script> in my react app only when it is required?
问题描述
我想尝试使用google maps API来显示地图,但我想知道是否有更好的方法来加载< script>
标记,而不是放置它在我的index.html中。
I want to try and use the google maps API to show a map but I'm wondering if there's a better way to load the <script>
tag than putting it in my index.html.
我希望脚本只在进入 / map
路线。所以,我想将它从 index.html
中移除并动态加载。不过,我也想确保如果它已经被加载,我不会尝试再次加载它。
I would like for the script to load only when I go to the /map
route. So, I would want to remove it from my index.html
and load it dynamically. However, I also want to make sure that if its already been loaded that I don't try and load it again.
我不确定是否有库来处理这个问题。到目前为止我尝试过的(但失败)是创建一个 loadScript
函数,它附加一个< script>
到实际的dom并为其指定一个键,因此在这种情况下'google-maps
。
I'm not sure if there is a library to handle this. What I've tried so far (but failed) is to create a loadScript
function which appends a <script>
to the actual dom and assigns it a key so in this case 'google-maps
.
谢谢
Thanks
推荐答案
最近的项目。我使用了 react-async-script-loader 组件。
This is what I make it working in my recent project. I used react-async-script-loader component.
import React from 'react'
import scriptLoader from 'react-async-script-loader'
@scriptLoader(['https://maps.googleapis.com/maps/api/js?key=your-key'])
export default class Maps extends React.Component {
constructor(props){
super(props);
this.map = null;
}
componentWillReceiveProps ({ isScriptLoaded, isScriptLoadSucceed }) {
if (isScriptLoaded && !this.props.isScriptLoaded) { // load finished
if (isScriptLoadSucceed) {
this.map = new google.maps.Map(this.refs.map, {
center: {lat: 10.794234, lng: 106.706541},
zoom: 20
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
this.map.setCenter(pos);
const marker = new google.maps.Marker({
position: pos,
map: this.map,
title: 'Hello World!'
});
}, () => {
console.log('navigator disabled');
});
} else {
// Browser doesn't support Geolocation
console.log('navigator disabled');
}
}
else this.props.onError()
}
}
render(){
return (
<div>
<div ref="map" style={{height: '80%', width: '100%'}}></div>
{ !this.map && <div className="center-md">Loading...</div> }
</div>
)
}
}
这篇关于如何加载谷歌地图api< script>在我的反应应用程序只有当它是必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!