Skip to content

Instantly share code, notes, and snippets.

@solace
Last active March 5, 2021 07:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solace/edfade8f48ce03de5ef9a1221e1c26b2 to your computer and use it in GitHub Desktop.
Save solace/edfade8f48ce03de5ef9a1221e1c26b2 to your computer and use it in GitHub Desktop.
Updating map bounds using react-google-maps
/* Only the necessary information to address
* https://github.com/tomchentw/react-google-maps/issues/183#issuecomment-220705977
* has been included here.
*
* YMMV.
*/
import React from 'react';
// Need these to muck around with bounds
import { fitBounds } from 'google-map-react/utils';
import LatLng from 'google-map-react/lib/utils/lib_geo/lat_lng.js';
import LatLngBounds from 'google-map-react/lib/utils/lib_geo/lat_lng_bounds.js';
class Map extends React.Component {
constructor(props) {
super(props);
// State used for the map component
// You will probably want to build your markers here too on init (see rebuildMarkers)
this.state = {
center: {lat: this.props.defaultCenter.lat, lng: this.props.defaultCenter.lng},
zoom: this.props.defaultZoom,
bounds: new LatLngBounds()
};
}
componentWillReceiveProps(nextProps) {
if (nextProp.coords) {
this.rebuildMarkers(nextProp.coords);
}
}
rebuildMarkers(coords) {
let newBounds = new LatLngBounds();
// foreach coord
// 1. build your marker
// 2. update your bounds to include the new point
newBounds.extend(new LatLng(newLat, newLng));
// end
this.setState(/* update marker and bounds */);
}
onBoundsChange({zoom, center}) {
let state = {};
// We've been updating the bounds when we rebuild the markers, so use that to update the
// map bounds.
if (this.state.bounds) {
const geoService = this.refs.map.geoService_;
const fit = fitBounds(
{nw: this.state.bounds.getNorthWest(), se: this.state.bounds.getSouthEast()},
{width: geoService.getWidth(), height: geoService.getHeight()}
);
// re-centre
state = {
center: fit.center,
zoom: fit.zoom
};
} else {
state = {
center,
zoom
};
}
this.setState(state);
}
render() {
return (<div>
<GoogleMap
ref="map"
options={mapOptions}
zoom={this.state.zoom}
center={this.state.center}
onChange={this.onBoundsChange}>
{markers}
</GoogleMap>
</div>);
}
}
@davidpelayo
Copy link

That's actually so undetermined nor well documented how to reproduce the behaviour.

@davidpelayo
Copy link

I refactored the rebuildMarkers as commented here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment