React-google-maps: map is not displaying in browser; no error in console

Created on 11 Jan 2016  Â·  51Comments  Â·  Source: tomchentw/react-google-maps

I am trying to integrate google maps in my application; I created a component just like you provided and called it with a route but it doesnt shows map as I needed.

My Map Component:

    import {default as React, Component} from "react";
    import {default as update} from "react-addons-update";

    import {default as canUseDOM} from "can-use-dom";
    import {default as _} from "lodash";

    import {GoogleMapLoader, GoogleMap, Marker} from "react-google-maps";

    import {triggerEvent} from "react-google-maps/lib/utils";



     class Mapping extends Component {

         state = {
             markers: [{
                 position: {
                     lat: 25.0112183,
                     lng: 121.52067570000001,
                 },
                 key: "Taiwan",
                 defaultAnimation: 2
             }]
         };

         constructor (props, context) {
             super(props, context);
             this.handleWindowResize = _.throttle(this.handleWindowResize, 500);
         }

         componentDidMount () {
             if (!canUseDOM) {
                 return;
             }
                 window.addEventListener("resize", this.handleWindowResize);
                 }

        componentWillUnmount () {
        if (!canUseDOM) {
            return;
        }
        window.removeEventListener("resize", this.handleWindowResize);
    }

    handleWindowResize () {
        console.log("handleWindowResize", this._googleMapComponent);
        triggerEvent(this._googleMapComponent, "resize");
    }

    /    *
 *     This is called when you click on the map.
     * Go and try click now.
     */
        handleMapClick (event) {
        var {markers} = this.state;
        markers = update(markers, {
            $push: [
                {
                    position: event.latLng,
                    defaultAnimation: 2,
                    key: Date.now()// Add a key property for: http://fb.me/react-warning-keys
                },
            ],
        });
        this.setState({ markers });

        if (3 === markers.length) {
            this.props.toast(
                "Right click on the marker to remove it",
                "Also check the code!"
            );
        }
    }

    handleMarkerRightclick (index, event) {
        /*
         * All you modify is data, and the view is driven by data.
         * This is so called data-driven-development. (And yes, it's now in
         * web front end and even with google maps API.)
         */
        var {markers} = this.state;
        markers = update(markers, {
            $splice: [
                [index, 1]
            ],
        });
        this.setState({ markers });
    }

    render () {
            return (
           <GoogleMapLoader
                containerElement={
          <div
            {...this.props}
            style={{
              height: "100%"
            }}
          />
        }
                googleMapElement={
          <GoogleMap
            ref={(map) => (this._googleMapComponent = map) && console.log(map.getZoom())}
            defaultZoom={3}
            defaultCenter={{lat: -25.363882, lng: 131.044922}}
            onClick={this.handleMapClick}>
                {this.state.markers.map((marker, index) => {
              return (
                <Marker
                  {...marker}
                  onRightclick={this.handleMarkerRightclick.bind(this, index)} />
              );
            })}
          </GoogleMap>
        }
                />
        );
    }
}
export default Mapping;

Most helpful comment

i found out that converting height and width's values from percentage to pixels worked for me.

All 51 comments

I also cannot get a map to be rendered into the browser. This is what my component looks like:

export default
class notFound extends Component {

    render() {

        return (
            $(GoogleMapLoader, {
                containerElement: div({style: {height: '100%', width: '100%'}}),
                googleMapElement: $(GoogleMap, {
                    ref: map => console.log(map),
                    defaultCenter: {lat: -33.93, lng: 18.868}
                })
            })
        )
    }
}

I further noticed in html generated that few divs are created and in base div's style, i removed 'position:absolute', then it started showing google logo and Terms of use link at the bottom of page; just like any other integration of maps. But my map area is still not showing

Also the examples work perfectly, but extracting them out into my application produces deprecated errors and results in no map showing.

i found out that converting height and width's values from percentage to pixels worked for me.

I did this and can now see the google logo and terms of use, but the map area is grey. Also clicking or dragging within the component triggers errors and breaks the component

Google maps API will initialize on the DOM defined by containerElement. You have to make sure the containerElement will have height & width when rendered on the page.

this does not solve the problem. Maps get rendered as an empty grey box

Still no when setting containerElement={<div style={{width: 200, height: 200}} />}?

{width: 200, height: 200} results in an empty grey box. Clicking or dragging on the box generates Uncaught TypeError: Cannot read property 'x' of undefined

@tomchentw Any idea what could be causing this? I would like to use this library in my application.

Could you provide a minimal repository that I could reproduce?

Sorry I should of posted an update here. I got it to work properly by placing it within another div that was position: absolute; and had width and height set to 100%, and then additionally setting the style on the containerElement prop to height: 100%;. Without the outer div, the component completely breaks.

Hmmm, that's weird. I'll make sure to create an example without height: 100%

It's possible that I'm just doing something weird. I'll try create a bare, fresh environment tomorrow and give it another test if I get time.

Same issue - map area is grey, only terms and google logo.
It hapens when i try render map in invisible area.

I got mine working by fiddling with its containers. Can't remember exactly what I did but I think it needed an outer container with position absolute and a width and height set

not sure if this helps, but i was having the same issue re: gray map with only the google logo. used this and got it working: https://github.com/tomchentw/react-google-maps/issues/161#issuecomment-160827083

Should I close this issue?

Yes I think so

On 20 Feb 2016, at 7:24 AM, Tom Chen [email protected] wrote:

Should I close this issue?

—
Reply to this email directly or view it on GitHub.

Can't really say that it is easy to integrate your component out-of-the-box. Even when I use an outer container with an absolute position still have the grey box issue.

Had a similar problem. Adding zoom & center props helped in my case.

We're going to look into this shortly. In the meantime, feel free to submit a minimal repository that can fully reproduce this error so that anyone can try to help out. Thanks.

Feel free to submit a gif to demonstrate the behaviour.

We're also looking for maintainers. Involve in #266 to help strengthen our community!

HI, This is not related to react. Im trying https://developers.google.com/maps/documentation/javascript/examples/marker-simple in a simple html and I get this grey box.
Somebody have a minimal example that works!!
THanks!

I had the same issue, change the height '100%' to '500px' and it fixed it

Thanks @ansgarm, adding zoom & center props helped me as well.

Just to let you know 6.0.0 is released on npm beta tag now. We also have a new demo page. Feel free to try it:
https://tomchentw.github.io/react-google-maps/

I have a similar issue with seeing the google logo and only a grey box.

But the interesting thing is that the map appears when I resize the window!

Is that happening with anyone else?

I think this is related to gmap library because I tried simple html + gmap example without react and I have a similar problem : grey box. This error was fixed moving divs in my html.

Maybe a simplest example of html + gmap without react could help to determine the problem.

I've had a similar issue happen as well. It's somehow related to the CSS / styling. When I change the CSS the map sometimes will simply not load (the entire DOM tree will be gone, so it's not just "not appearing", it's literally not part of the document).

In all of these cases I have been working with a map inside of a element. I've been able to work around it always, but it is odd. I don't need this to be fixed, but leaving this comment here in case anyone experiences something similar.

I also want to add that the network request to Google Maps completes in these cases as well (I see the response come in via the Dev Tools), so that part is working.

EDIT: I now see that some users actually mention the solution to the issue above, but just to make it clear for others, your map element, especially the top level <div> that it is part of, needs to have a defined height. Sometimes height: 100% is enough to take care of this, but other times, especially if you are doing weird stuff with tables, you might need to define a specific pixel height. Check out this link for more things that could be going wrong from the Google Maps API side: https://developers.google.com/maps/documentation/javascript/tutorial#Troubleshooting.

I'm having the same issue as @zkdzegede. Also, when I resize the page, the center is completely off.

Anyone have a possible solution ?

I was also having the same issue as @zkdzegede. Fixed it by adding default width and height to the containerElement prop of the ScriptLoader component which I'm using:

<ScriptjsLoader
        hostname={'maps.googleapis.com'}
        pathname={'/maps/api/js'}
        query={{
          key: 'the-api-key',
          language: 'en',
          libraries: 'geometry,drawing,places,visualization',
          v: '3',
        }}

        loadingElement={
          <div>{'Loading'}</div>
        }

        containerElement={
          <div style={{height: 400, width: 600}}></div>
        }

        googleMapElement={
          <GoogleMap
            defaultZoom={5}
            defaultCenter={{lat: -25.363882, lng: 131.044922}}
          >
            <Marker {...this.props.markerProps} />
          </GoogleMap>
        }
      />

@aaj works!!
In my case I used (whitout tomchentw-react-google-maps library)

<div>
    <div id="gmap_container" style={{width: 500, height: 500}} ></div>
</div>

But I need a dynamic size :s

This works:
style={{width: '100%', height: '100%'}}

I searched on the web and found this post which I is exactly problem I have right now. Can someone please explain how to solve this .

I've tried all the suggestions in this post but still cannot render the map.

The example work when I do them in a testing environment but fails when I integrate with my application.

I also notice the map does not center properly.

I had so much trouble getting the map to show and none of the answers above worked for me, so I'm posting this solution hoping it would solve y'all hours of playing around!

I think because I'm using a dialog and a map in that dialog I had to do some extra steps:

This is my dialog in HTML <div id="modal-create" class="modal fade" role="dialog">

in that I have the map <div id="map"></div>

for a css style I have this #map{ height: 300px; } change the height to whatever you want, for me it helped to have a set px height and not a %

I added a dom listener in my doucment.ready

google.maps.event.addDomListener(window, 'load', initMap);

and my initMap() is as follows

function initMap() {

        navigator.geolocation.getCurrentPosition(function(position) {
            var mapCanvas = document.getElementById('map');
            var mapOptions = {
                center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(mapCanvas, mapOptions)

            $('#modal-create').on('shown.bs.modal', function () {
                google.maps.event.trigger(map, "resize");
            });

        });

really hope this works for you whomever you are <3

Please refer to Getting Help section in the README (or #469).

Add style={{width: '100%', height: '100%'}} to all the parents elements of google map, including body and html.

Encountered the same error for completely different reasons.
I had forgotten to remove this.onMarkerRightClick = this.onMarkerRightClick.bind(this); from the constructor while the method definition was deleted.
There was no error message in the console.
This lead to an entirely grey screen. Removing the obsolete bind solved the issue.

Try this out it may help
If you have signed up of an API key on the Google API Console:

Add the following script tag in index.html

<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

the issue is not related to the react-google-map. the container element of the map needs to have an height specified. it will not render anything if height is set to a percentage. so you could either set the containerElement a fix height or the better solution would be wrap the map component inside another div and give it a fix height.so your render looks something like this

return (
      <div className={st.mapWrapper}>
          <AsyncGoogleMap
            googleMapURL={ googleMapURL }
            loadingElement={ <div style={ { height: "100%" } } /> }
            containerElement={ <div style={ { height: "100%" } } /> }
            mapElement={ <div style={ { height: "100%" } } /> }
            markers={ this.state.markers }
            onMarkerClick={ this.handleMarkerClick }
            onMarkerClose={ this.handleMarkerClose }
          />
      </div>
    );

and in your styles

.mapWrapper {
    position: relative;
    display: block;
    height: 350px; //give a height in px or in vh NOT a percentage value
    width: 100%;
}

Just to complement, I was having an issue with Safari not rendering the map (It was working fine in Chrome). I had a min-height: 850px in the outer div. I then changed it to height: 850px and worked.

Later on, I wanted to make it proportional to the screen size and changed to height: 100%, but it didn't work on Safari again (good on Chrome though).

Finally, I changed to height: 100vh, and worked on both browsers 👍

For the issue that @zkdzegede mentioned with the map not working unless the window was resized, adjusting the styling did not work for me. I was able to correct the issue by assigning the mapComponent in the componentDidMount() function instead of where I was originally assigning it. I guess the issue is that the map was loaded before the component was fully loaded. Hope this can help someone else in the future.

I was having this problem and after much frustration, I figured out that the coordinates I was testing it with had the lat and lng flipped. Guess I was sending it unmappable coordinates. Just another possible solution to throw into the mix here. You can see what was rendering for me below with the bad coordinates...

screen shot 2018-02-06 at 5 09 39 pm

I also encountered a similar issue. But it's all gray, there is no google logo or any other stuff. No errors. It turned out I use the map in two different component, one of them passing "zoom" property from parent but the other doesn't. Once I fixed this and it worked. Help this could help.

We had this issue too, but the same exact map loads perfectly on other pages. Setting parent height and other fixes here did not work. For some reason cloning the exact page where it was working, then reloading all of our content into that page worked perfectly. No clue what the difference is between the cloned page and a new page- ALL the settings are exactly the same as far as I can tell.

Loading the shortcode into a new page or post gives us this container DIV which does not load the map (Div is empty, Google logo showing, but map buttons and appearance broken)
<div id="custom-mapping-google-map-1" style="overflow: hidden; height: 300px">

Loading the shortcode into a cloned page or post gives us this DIV with all the working map code inside
<div id="custom-mapping-google-map-0" style="overflow: hidden; height: 300px; position: relative;">....</div>

Hopefully this helps someone!

Add these

I had similar issue , all did was add this

agm-map{ height: 800px; width: 100% ; }
in the style and it worked

Hello, recently I struggled with the "grey area" map issue, and the solution from @ansgarm worked: initializing with a center and a zoom rendered map tiles.

With react-google-maps v9.4.5

Set zoom props works for me.

@Climber22
The repo of this project is unmaintained more than a year, and we had build new version https://www.npmjs.com/package/@react-google-maps/api

We had rewrite it to TypeScript, and updating it frequently: https://github.com/JustFly1984/react-google-maps-api/tree/master/packages/react-google-maps-api
You can enjoy autocomplete.

You can see our docs: https://react-google-maps-api-docs.netlify.com/

Also a lot of examples: https://react-google-maps-api-gatsby-demo.netlify.com/ https://github.com/JustFly1984/react-google-maps-api/tree/master/packages/react-google-maps-api-gatsby-example/src/examples

The bundle size is much smaller: https://bundlephobia.com/result?p=@react-google-maps/api

Our Spectrum community: https://spectrum.chat/react-google-maps
Our Slack channel: https://join.slack.com/t/react-google-maps-api/shared_invite/enQtODc5ODU1NTY5MzQ4LTBiNTYzZmY1YmVjYzJhZThkMGU0YzUwZjJkNGJmYjk4YjQyYjZhMDk2YThlZGEzNDc0M2RhNjBmMWE4ZTJiMjQ

Enjoy!

https://localhost:8000
AIzaSyAIEIUwCGFxj7LQoJP7f1uIjrdW_caZ5dg

http://localhost:3000
AIzaSyDGoMq24FaPFSVxKgMeXE5fkJw0JkdQ7i8

https://react-google-maps-api-gatsby-demo.netlify.com/
AIzaSyC3kkfcd1XTail_ft8YEoNto49NKOmFhWo

http://localhost:9001
AIzaSyCakXXwZ_CyPggaQBrYmbw5QhgGUcoMD_E

export const googleMapKey = 'AIzaSyCakXXwZ_CyPggaQBrYmbw5QhgGUcoMD_E'
export default googleMapKey

http://localhost:6060
AIzaSyCgkbHxXpGlShz9Doj6dhbnXR59v-G8bO0


@JustFly1984 :
I am using @react-google-maps, the map initially loaded good, i have changed the latitude and longitude using onClick event in GoogleMap using state, after that the map displaying empty screen, can u pls help me?

import React, { Component } from 'react';
import { GoogleMap, LoadScript } from '@react-google-maps/api';

const containerStyle = {
width: '400px',
height: '400px',
margin: 'auto',
padding: '200px',
};

export default class Index extends Component {
constructor(props) {
super(props);
this.state = {
lat: 0,
lng: 0,
};
}

showLocation = (position) => {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
};

errorHandler = (err) => {
if (err.code === 1) {
alert('Error: Access is denied!');
} else if (err.code === 2) {
alert('Error: Position is unavailable!');
}
};

componentDidMount() {
if (navigator.geolocation) {
let options = { timeout: 60000 };
navigator.geolocation.getCurrentPosition(
this.showLocation,
this.errorHandler,
options,
);
} else {
alert('Sorry, browser does not support geolocation!');
}
}

onMapClick = (value) => {
console.log('e', value);
this.setState({
lat: value.ab.x,
lng: value.ab.y,
});

};

render() {
return (

mapContainerStyle={containerStyle}
center={{ lat: this.state.lat, lng: this.state.lng }}
zoom={10}
onClick={this.onMapClick}
>
{/* Child components, such as markers, info windows, etc. */}
<>


);
}
}

Screenshot 2020-07-29 at 7 18 29 PM

Was this page helpful?
0 / 5 - 0 ratings

Related issues

johnantoni picture johnantoni  Â·  3Comments

bossbossk20 picture bossbossk20  Â·  3Comments

0x1bitcrack3r picture 0x1bitcrack3r  Â·  3Comments

MrSaints picture MrSaints  Â·  3Comments

wayofthefuture picture wayofthefuture  Â·  3Comments