Last active
March 5, 2021 07:57
-
-
Save solace/edfade8f48ce03de5ef9a1221e1c26b2 to your computer and use it in GitHub Desktop.
Updating map bounds using react-google-maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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>); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I refactored the rebuildMarkers as commented here.