javascriptreactjstypescriptgoogle-mapsgoogle-map-react

"google-map-react" npm package -> onClick event -> incorrect 'lat' and 'lng' values


NOT DUPLICATE BECAUSE: Because I am specifically using the "google-map-react" npm package to handle the Google Maps API I don't believe this is a duplicate question. This is more a question about the "google-map-react" package than the Google Maps API.

The Problem:

The GoogleMapReact component (from the "google-map-react" npm package) is incorrectly detecting the location of click events for some reason. Specifically its "onClick" event object has incorrect lat/lng values. The coordinates are always shifted to the South East (or bottom right) and the error magnitude seems to be related to zoom level... ie. when zoomed out far the error in the lat/lng is many hundreds of kilometers, and reduces as the map is zoomed in. Another way of looking at it is that the coordinates are always shifted on screen by the same x and y pixel amounts.

Note about potential solutions:

I do not know much about the Google Maps API that this package is accessing behind the scenes, and I would prefer a solution that uses the "google-map-react" package so that I can maintain that layer of abstraction over the base Google Maps API.

Context:

I'm using "google-map-react" version 2.1.3.


Solution

  • I found the problem:

    I had a global stylesheet that was applying margin and padding to all "div" elements. The "google-map-react" package wraps the google map in a bunch of div elements, and somehow the padding and margin on those elements was messing up the location/coordinate detection.

    My Solution: On the nearest parent of the "GoogleMapReact" component I added a special class name ('remove-global-div-styling'... but the name is obviously unimportant) and then used the following css to preserve my applications overall styling while removing styling from the "google-map-react" generated divs:

    .remove-global-div-styling div {
         margin: 0;
         padding: 0;
         ...etc (based on whatever unwanted styling is being applied to those divs)
    }
    

    General Solution: If using the "google-map-react" package and experiencing anything like my problem, use the devtools to inspect the divs generated by "google-map-react" and see if there is any unexpected styling being applied to them from elsewhere in your app.