0

First of all I need to apologize because my question(problem) is a bit confusing. Understand that I should simplify my code so that everyone knows what's going on, but I just can't do it this time.

I got a Google Map in my React project. Sometimes it works, sometimes it doesn't. So what make it works? Nothing, but just waiting for it. Sometimes it takes less than a minute, the longest I've been waiting for is 5 minutes by far.

So after the map has been shown and if I delete caches and history, the map won't be working again (for a short while). It just shows a blank page.

This is the way how I coded:

Add a source link to link the Google Map in the bottom of the index.html, with just the API key but no callback in the url.

<script src="https://maps.googleapis.com/maps/api/js?key={MY KEY HERE}" async defer></script>

And in the Contact page, where the map should be shown, I defined a Google Map object in the componentDidMount() section.

const google = window.google;

componentDidMount(){

    var mapOptions = {
        // zoom, center, styles, etc go here
    }

    var mapElement = document.querySelector("#map")

    var map = new google.maps.Map(mapElement, mapOptions)
}

The problem is mentioned above, it takes too much time to load(wait). Even worst, even the map has been shown, if I refresh the page, it could goes blank.

I did think about defining the Google Map object in the componentWillMount(), but before it mount, there is no element for me to select as defining a Google Map need a dom element anyway.

I did also think of creating a div with display:none style and load the map on the home page, but that doesn't make sense at all.

Another solution I tried is to create a script element in the compoentDidMount() section, setAttribue to put the link with a callback function in the element, and then append it to the body, but this doesn't work either.

Do you know why is this happening and how to solve this?

My site: https://kennytesting.000webhostapp.com/interior

The contact page on the site: https://kennytesting.000webhostapp.com/interior/contacts

Sorry for asking a loooong question again.

  • Error message: maps of undefined <-- not really helpful

  • It works fine when using the localhost, but not using a normal server.

Kenny
  • 153
  • 1
  • 1
  • 9

1 Answers1

0

It appears to be split second problem, where if window.google; isn’t ready, then your mount fails because new google.maps.LatLng won’t load. I get this error:

react-dom.production.min.js:151 TypeError: Cannot read property 'maps' of undefined
    at t.value (Map.js:23)

I would find a way of waiting for Google Maps to load then triggering the creation. Possibly look at How can I check whether Google Maps is fully loaded? using an event.

Zoe Edwards
  • 12,999
  • 3
  • 24
  • 43