- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将 Google map 添加到 ReactJs Web 应用程序,但没有成功。
我知道有一些 React 组件可以封装 google map ,但它们不适合我的实际需求,所以我必须自己构建一个。我的问题是我不知道如何处理谷歌地图工作所需的脚本标记:<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6maRCH9aI1K0sWA_FRdjIQv9AJgP7aQ0&callback=initMap"
async defer></script>
我一开始把它放在index.html中,但是当我在 chrome devtools 中启动我的应用程序时出现此错误:
Uncaught (in promise)
Hc {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵ at new Hc (https://maps.googleapis.com/m…I1K0sWA_FRdjIQv9AJgP7aQ0&callback=initMap:124:108"}
我尝试过使用fetch()
要获取脚本,请查看它实际上是什么,但它要求 CORS header 并认为我不知道此请求所需的确切参数,我认为这不是解决方案。
最佳答案
正如 @Naismith 所说,该错误是由于 google map 脚本中的 callback=initMap
造成的。因此,要使其工作,您必须像这样实现 initMap
函数:
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
除非您尝试在组件中显示 map ,否则您可以尝试这种方法,为 Google Maps API 创建 Promise,并在 Google Maps API 的(全局)回调函数中解析该 Promise能跑。然后,在组件代码中,您需要等待 promise 得到解决,然后再继续。
class Map extends React.Component {
getGoogleMaps() {
if (!this.googleMapsPromise) {
this.googleMapsPromise = new Promise((resolve) => {
// Add a global handler for when the API finishes loading
window.resolveGoogleMapsPromise = () => {
// Resolve the promise
resolve(google);
// Tidy up
delete window.resolveGoogleMapsPromise;
};
// Load the Google Maps API
const script = document.createElement("script");
const API = 'AIzaSyDbAz1XXxDoKSU2nZXec89rcHPxgkvVoiw';
script.src = `https://maps.googleapis.com/maps/api/js?key=${API}&callback=resolveGoogleMapsPromise`;
script.async = true;
document.body.appendChild(script);
});
}
// Return a promise for the Google Maps API
return this.googleMapsPromise;
}
componentWillMount() {
// Start Google Maps API loading since we know we'll soon need it
this.getGoogleMaps();
}
componentDidMount() {
// Once the Google Maps API has finished loading, initialize the map
this.getGoogleMaps().then((google) => {
const uluru = {lat: -25.366, lng: 131.044};
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: laos
});
const marker = new google.maps.Marker({
position: laos,
map: map
});
});
}
render() {
return (
<div>
<div id="map" style={{width: 600, height: 300}}></div>
</div>
)
}
}
ReactDOM.render(
<Map/>,
document.getElementById('react')
);
关于javascript - ReactJs 外部脚本 - 谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176069/
leaflet:一个开源并且对移动端友好的交互式地图 JavaScript 库 中文文档: https://leafletjs.cn/reference.html 官网(英文): ht
我是一名优秀的程序员,十分优秀!