I am loading a map from react-google-maps-api, and then based on the current zoom & center point, we calculate the radius of the map to retrieve items within the "viewable" area of the map. However, the radius being calculated seems to be larger than the visible area.
I have referenced some existing SO threads including this, this, this.
Our map is initialized like:
<GoogleMap
id="live-view-map"
mapContainerStyle={{ width: 'inherit', height: 'inherit' }}
center={userLocation} // denver, co for reference
options={{
disableDefaultUI: true,
clickableIcons: false,
fullscreenControl: false,
zoomControl: true,
}}
zoom={13}
onLoad={onLoad}
onTilesLoaded={() => {
dispatch({ type: ACTIONS.SET_MAP_LOADED, payload: true });
}}
onDragEnd={handleDrag}
onZoomChanged={handleZoomChanged}
onUnmount={() => {
dispatch({ type: ACTIONS.SET_LATLNG, payload: null });
dispatch({ type: ACTIONS.SET_MAP, payload: null });
dispatch({ type: ACTIONS.SET_MAP_LOADED, payload: false });
}}
>
// items from endpoint get rendered as markers here
</GoogleMap>
My current get radius is comparing the NE corner & SW corner to determine the smaller distance from center:
const getRadius = (): number | null => {
const bounds = state.mapInstance?.getBounds();
if (!bounds) return null;
// computeDistanceBetween returns meters
const neRadius = google.maps.geometry.spherical.computeDistanceBetween(
bounds.getCenter(),
bounds.getNorthEast()
);
const swRadius = google.maps.geometry.spherical.computeDistanceBetween(
bounds.getCenter(),
bounds.getSouthWest()
);
const radius = neRadius <= swRadius ? neRadius : swRadius;
return Number((radius * 0.000621371).toFixed(2));
};
The radius is returning as 6.39 miles. However, the map visible region is for sure around 3.5miles. I thought the radius formula was perhaps incorrect, but I feel confident it's OK. So I am wondering if there's something wrong with the map visible region?
The black circle is the “radius” calculated from the bounds of google. This function is the same whether we use a custom function to calc radius or the google API maps.geometry.spherical.computeDistanceBetween. The red circle is the same radius value above, but divided by 2 (i had a theory that it’s like diameter instead?). The red circle just about fits the initial map zoom level. (screenshot is zoomed out to capture both circles)
What am I doing wrong?