I'm been trying to embeded a google map within a react component with no success. I'm not sure why and tutorials online seem to have outdated versions of react and google maps.
我一直试图在反应组件中嵌入谷歌地图但没有成功。我不确定为什么和在线教程似乎有过时版本的反应和谷歌地图。
My component below. The HTML document was taken from google maps documentation.
我的组件如下。 HTML文档来自谷歌地图文档。
import React from 'react'
import scriptLoader from 'react-async-script-loader'
class Gmaps extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
var uluru = {lat: -25.363, lng: 131.044};
this.map = new google.maps.Map(this.refs.map, {
zoom: 4,
center: uluru
})
}
render() {
return (
<div>
<h3>My Google Maps Demo</h3>
<div id="map" ref="map"></div>
<script>
{function initMap() {
var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}}
</script>
</div>
)
}
}
export default scriptLoader(
['https://maps.googleapis.com/maps/api/js?key=APIKEY']
) (Gmaps)
Apparently I need to use react ref
to load the map, but not too sure how.
显然我需要使用react ref加载地图,但不太确定如何。
Thanks for the help.
谢谢您的帮助。
1 个解决方案
#1
0
Source from here
来自这里
class Gmaps extends React.Component {
...
componentDidMount() {
// Connect the initMap() function within this class to the global window context,
// so Google Maps can invoke it
window.initMap = this.initMap;
// Asynchronously load the Google Maps script, passing in the callback reference
loadJS('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap')
}
initMap() {
map = new google.maps.Map(this.refs.map.getDOMNode(), { ... });
}
render() {
return (
<div>
...
<div ref="map" style="height: '500px', width: '500px'"><⁄div>
<⁄div>
);
}
})
function loadJS(src) {
var ref = window.document.getElementsByTagName("script")[0];
var script = window.document.createElement("script");
script.src = src;
script.async = true;
ref.parentNode.insertBefore(script, ref);
}
#1
0
Source from here
来自这里
class Gmaps extends React.Component {
...
componentDidMount() {
// Connect the initMap() function within this class to the global window context,
// so Google Maps can invoke it
window.initMap = this.initMap;
// Asynchronously load the Google Maps script, passing in the callback reference
loadJS('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap')
}
initMap() {
map = new google.maps.Map(this.refs.map.getDOMNode(), { ... });
}
render() {
return (
<div>
...
<div ref="map" style="height: '500px', width: '500px'"><⁄div>
<⁄div>
);
}
})
function loadJS(src) {
var ref = window.document.getElementsByTagName("script")[0];
var script = window.document.createElement("script");
script.src = src;
script.async = true;
ref.parentNode.insertBefore(script, ref);
}