Noushad PP Noushad PP - 25 days ago 7
React JSX Question

How to calculate a map LatLngBound from center and zoom manually?

I'm trying to render Google map using react-google-maps.
I get the users current location using

geolocation.navigator
function before the map is fully loaded, but I need to calculate the bounds of the map using the location of the user as the center and a preset zoom level , say , 5.
How can I achieve this ?

Answer

The easiest way would be to set the default zoom to 5 on the Google Maps component:

<GoogleMap
  ref="map"
  defaultZoom={5}
  defaultCenter={{ lat: -25.363882, lng: 131.044922 }}
>

defaultCenter is the user's location in this format.

and then get the bounds like this:

let map = this.refs.map;
let bounds = map.getBounds();

let geoBounds = {
  swLat: bounds.getSouthWest().lat(),
  swLng: bounds.getSouthWest().lng(),
  neLat: bounds.getNorthEast().lat(),
  neLng: bounds.getNorthEast().lng(),
};
Comments