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 tag than putting it in my index.h
Updates Oct 6, 2019: The example code is still working well, I have just updated them to use non-decorator syntax.
This is what I make it worked in my recent project. I used react-async-script-loader component.
import React from 'react';
import scriptLoader from 'react-async-script-loader';
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 (
{!this.map && Loading...}
);
}
}
export default scriptLoader(['https://maps.googleapis.com/maps/api/js?key=API_KEY'])(Maps);