3

I'm using React and I want to use a package which can only retrieved as an URL. In HTML it's easy to import using the script tag, but how to import to a JavaScript file?

What I want is to convert this

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>

into something like this

import 'https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true'
Jason Watkins
  • 3,766
  • 1
  • 25
  • 39
Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64

1 Answers1

1

Based on your comment when you import it directly in your html:

It throws an error which says that the objects of the script aren't defined

I think the best approach here is to not try to import the js in another js file, but use the React google maps library instead, so you don't go through these hacks.

Try it and let us know.

The reason for this answer is that, even if you get the script working by adding another js file into your own js file, google maps api js will do more things that will give you trouble and issues in React (like the one you are having right now), and these issues have already been solved by this library.

Have a read at the official documentation to see if it works for you.

Example

There is a good tutorial and very basic example using this library here.

Example of using latitude and longitude (taken from this tutorial):

const GoogleMapExample = withGoogleMap(props => (
   <GoogleMap
     defaultCenter = { { lat: 40.756795, lng: -73.954298 } }
     defaultZoom = { 13 }
   >
   </GoogleMap>
));
return(
   <div>
     <GoogleMapExample
       containerElement={ <div style={{ height: `500px`, width: '500px' }} /> } 
       mapElement={ <div style={{ height: `100%` }} /> }
     />
   </div>
);

Alternative library

Alternatively, you could use this library, as it is another react library for rendering google maps.

google-map-react

You can also follow this tutorial with this library.

These libraries have plenty of supporters and stars, meaning that you can always count on updates and helpful information.

c-chavez
  • 7,237
  • 5
  • 35
  • 49