gpt4 book ai didi

javascript - 在 React 组件中使用 Google Map API

转载 作者:行者123 更新时间:2023-12-04 03:00:38 25 4
gpt4 key购买 nike

我正在为在 React 组件中使用 Google Map API 的方式而苦苦挣扎。我不想用流行的react-google-maps也不是 google-map-react包,而是创建我自己的。

我设法从 React 组件中使用 Google Map API 加载脚本标签。但是,如何从这里操作 Google API?例如,用下面的基本配置初始化 map ?

  map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});

这是我的组件。任何建议表示赞赏!谢谢!

import React, { Component } from 'react';

// Load Google API in script tag and append
function loadScript(src) {
return new Promise((resolve, reject) => {
let script = document.createElement('script');
script.src = src;
script.addEventListener('load', function() {
resolve();
});
script.addEventListener('error', function(e) {
reject(e);
});
document.body.appendChild(script);
});
}
const script = 'https://maps.googleapis.com/maps/api/js?key=MY_API_KEY';

class MyGoogleMap extends Component {
constructor(props) {
super(props);
this.state = {};
}

componentDidMount() {
// first load the script into html
loadScript(script).then(function() {
console.log('SUCCESS');
// Where do I go from here?
});
}
render() {
return <div />;
}
}

export default MyGoogleMap;

最佳答案

我实际上找到了自己的解决方案,所以我分享给任何遇到同样问题的人。

基本逻辑是使用window访问对象google .
因此,在按照问题加载脚本后,我将 map 初始化为:

  initMap = () => {
// 'google' could be accessed from 'window' object
const map = new window.google.maps.Map(
document.getElementById('googleMap'),
{
zoom: 14,
center: { lat: LATITUDE, lng: LONGTITUDE }
}
);
// putting a marker on it
const marker = new window.google.maps.Marker({
position: { lat: LATITUDE, lng: LONGTITUDE },
map: map
});
};

render() {
return (
<div id="googleMap" style={width: WIDTH, height: HEIGHT}/>
);
}


欢迎任何评论:)

关于javascript - 在 React 组件中使用 Google Map API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49530089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com