Reputation: 146
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.
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.
Thanks for the help.
Upvotes: 1
Views: 4916
Reputation: 1478
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);
}
Upvotes: 1