-1

Many web APIs can be used by adding the script tag to the head:

<html lang="en">
<head>
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
</head>
<body>
  <div id="root" style="height: 100%"></div>
</body>
</html>

But when using libs like React and new features like ES6 this seems out of place. As in lets keep things modular -- the import should be close to the code that uses it.

How can we do the same, but in an ES6 file?

I was thinking of fetching it like this:

var request = require('request');
request('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places', function (error, response, body) {
  if (!error && response.statusCode == 200) {
     ...
  }
})

What should be done with what is returned? Append it to the head?

Update:

Error: ReferenceError: google is not defined

Am I loading the script at the wrong time?

const loadScript = (src) => {
  const script = document.createElement("script")
  script.type = "text/javascript"
  script.src = src
  document.getElementsByTagName("head")[0].appendChild(script)
}


class Geosuggest extends React.Component {

  constructor(props) {
    super(props)
    loadScript('https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places')
  }

  componentWillMount() {
    this.autocompleteService = new google.maps.places.AutocompleteService();
  }

}
BAR
  • 15,909
  • 27
  • 97
  • 185
  • 4
    You'd do it exactly the same way, ES6 doesn't change the way scripts are added in HTML. – adeneo Jun 15 '16 at 18:25
  • I mean do it all in JS. – BAR Jun 15 '16 at 18:31
  • Uhm, then you'd insert a script tag with JS? You can't get cross-origin resources with clientside JS, and there doesn't seem to be much point in getting it on the serverside? You seem to be using `require`, which implies some implentation of Require.js ? – adeneo Jun 15 '16 at 18:33
  • So you want to re-invent the wheel because it "seems out of place"? Is there an actual problem being addressed here? – Scott Hunter Jun 15 '16 at 18:33
  • ' insert a script tag with JS' That makes sense, was missing the obvious. Scott, when using a fractal project structure, it is very much out of place to put code needed for one component in an html file way outside of that component's directory scope. – BAR Jun 15 '16 at 18:35
  • Are you talking about the `import` keyword? Because you can't use external URLs like that. See http://stackoverflow.com/q/34607252/215552. Basically, there is no spec for how to load script files. You need to look at Require.js or System.js or one of those. – Heretic Monkey Jun 15 '16 at 18:41
  • @MikeMcCaughan Would be fantastic if we could do that.. But no. – BAR Jun 15 '16 at 18:42

2 Answers2

1

http://jsfiddle.net/doktormolle/7cu2f/

html:

<div id="map_canvas" style="height:200px"></div>

javascript:

function loadScript(src, callback) {

  var script = document.createElement("script");
  script.type = "text/javascript";
  if (callback) script.onload = callback;
  document.getElementsByTagName("head")[0].appendChild(script);
  script.src = src;
}


loadScript('http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialize',
  function() {
    log('google-loader has been loaded, but not the maps-API ');
  });


function initialize() {

  log('maps-API has been loaded, ready to use');
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map_canvas'),
    mapOptions);
}

function log(str) {
  document.getElementsByTagName('pre')[0].appendChild(document.createTextNode('[' + new Date().getTime() + ']\n' + str + '\n\n'));
}
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
0

react-helmet to the rescue!

class Geosuggest extends React.Component {
  componentWillMount() {
    this.autocompleteService = new google.maps.places.AutocompleteService();
  }
}

const wrap = () => <div>
  <Helmet script={[{"src": GoogleMapsApiUrl}]}/>
  <Geosuggest />
</div>

export default wrap
BAR
  • 15,909
  • 27
  • 97
  • 185