Reputation: 11
I’m using @vis.gl/react-google-maps in my web app, and I’ve applied CSS zoom on the element to adjust the UI for smaller screens. While the UI scaling looks good, it’s messing up my Google Maps interactions. Specifically, the map’s click events (onClick) and polygon drawing tools return incorrect latLng values — the location I click on the map doesn’t match the coordinates I receive.
For example, my CSS looks like this:
body {
zoom: 0.65;
}
When I click on a point on the map, the e.detail.latLng I get is way off.
Here’s my map component:
import { APIProvider, Map } from '@vis.gl/react-google-maps';
const MyMap = () => {
const handleMapClick = (e: google.maps.MapMouseEvent) => {
if (!e.detail.latLng) return;
const { lat, lng } = e.detail.latLng;
console.log('Lat:', lat(), 'Lng:', lng());
};
return (
<APIProvider apiKey={process.env.VITE_GOOGLE_MAPS_API_KEY}>
<Map
onClick={handleMapClick}
style={{ width: '100vw', height: '100vh' }}
defaultZoom={5}
defaultCenter={{ lat: 40.7128, lng: -74.006 }}
/>
</APIProvider>
);
};
export default MyMap;
please check this live sandbox https://codesandbox.io/p/sandbox/pfnvz9 for a live example, try to change zoom slider and try to click on the map to draw a marker! try with zoom:100% and < 100%
What I’ve tried:
Wrapping the map in a non-zoomed container — didn’t work.
Adjusting lat and lng based on the CSS zoom level — also didn’t fix the offset.
My question:
Is there a way to fix Google Maps' event projection when using CSS zoom on the body or any parent element?
Can I calculate a corrected latLng based on the zoom level?
Thanks in advance — I’m open to any workaround or solution!
Upvotes: 0
Views: 15
Reputation: 11
I have found a workaround for this by compensating the zoom in the map container by setting the zoom CSS property of the map to 100 / zoom
, check live example here: https://codesandbox.io/p/devbox/quiet-fog-forked-yqdd6z
<Map
defaultCenter={{ lat: 40.7128, lng: -74.006 }}
defaultZoom={12}
gestureHandling={"greedy"}
reuseMaps
disableDefaultUI
mapTypeId={"hybrid"}
nClick={handleMapClick}
style={{ width: "100%", height: "600px", zoom: 100 / zoom }}
>
{marker && (
<Marker position={{ lat: marker.lat, lng: marker.lng }} />
)}
</Map>
Upvotes: 0