javascriptgoogle-maps

Google Map: Uncaught ReferenceError: google is not defined


I'm working on a google map script which is throwing up this error. The issue is in this line:

var map = new google.maps.Map(document.getElementById('google-map'), {

Corresponding HTML snippet is:

<!-- Google Maps -->
    <div id="google-map"></div>

I've seen few questions which propose solutions to this problem but I havent really understood most of them: asynchronously loading the script or having a developer API key.
I'm just looking for a solution to what the issue really is and preferably a logical explanation to what the problem is.

Edit 1: The link the API is missing. I have added that and the error has gone but still the map doesnt show up. ( Please note that I've used PHP to divide the code into segments. )


Solution

  • I ran your script, and it seems like the following error is very common.

    Uncaught TypeError: Cannot read property 'offsetWidth' of null

    I found this question: Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null with answers suggesting that the error is because of not rendering the map div before the js script runs.

    Try:

    <script>
    /* Your location */
    function initialize () {
        var locations = [
            ['IIIT Hyderabad, Gachibowli, Hyderabad <span>Head Office</span>', 17.444792, 78.348310, 1]
        ];
    
        /* Map initialize */
        var mapCanvas = document.getElementById('google-map');
        var mapOptions = {
            zoom: 10,
            center: new google.maps.LatLng(17.444792, 78.348310),
            panControl: false,
            zoomControl: true,
            scaleControl: false,
            mapTypeControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            }
        var map = new google.maps.Map(mapCanvas, mapOptions);
        }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    

    This only calls the script after the page has loaded. I ran it and it works for me.