UNPKG

9.99 kBMarkdownView Raw
1## GoogleMap API
2
3### parameters
4
5#### apiKey (string) (_Deprecated use bootstrapURLKeys_)
6
7Google maps api key.
8
9#### bootstrapURLKeys (object)
10
11Example:
12
13```javascript
14<GoogleMap
15 bootstrapURLKeys={{
16 key: API_KEY,
17 language: 'ru',
18 region: 'ru',
19 ...otherUrlParams,
20 }}
21>
22```
23
24#### defaultCenter (array or object)
25
26`[lat, lng]` or `{ lat: lat, lng: lng}`
27Default lat/lng at which to center the map - changing this prop throws a warning
28
29#### center (array or object)
30
31`[lat, lng]` or `{ lat: lat, lng: lng}`
32Lat/lng at which to center the map
33
34#### defaultZoom: (number)
35
36Default map zoom level - changing this prop throws a warning
37
38#### zoom (number)
39
40Map zoom level
41
42#### hoverDistance (number)
43
44Default: 30
45
46#### margin (array)
47
48In onChange callback, gives you a marginBounds argument property, where lat lng will be shifted using margin you have set. For example, you could use a simple check pointInRect to not show Markers near map bounds.
49
50#### debounced (bool)
51
52Default: true
53
54#### layerTypes (string[])
55
56You can add some "layers" for map like a
57[traffic](https://developers.google.com/maps/documentation/javascript/examples/layer-traffic) or
58[transit](https://developers.google.com/maps/documentation/javascript/examples/layer-transit)
59
60```javascript
61layerTypes={['TrafficLayer', 'TransitLayer']}
62```
63
64### callbacks
65
66#### options (func|object)
67
68Set map options such as controls positions / styles, etc.
69
70Example:
71
72```javascript
73createMapOptions: function (maps) {
74 return {
75 panControl: false,
76 mapTypeControl: false,
77 scrollwheel: false,
78 styles: [{ stylers: [{ 'saturation': -100 }, { 'gamma': 0.8 }, { 'lightness': 4 }, { 'visibility': 'on' }] }]
79 }
80 }
81
82 <GoogleMap options={createMapOptions} ... />
83```
84See "Custom map options example" in Examples below for a further example.
85See full options at [Google Maps Javascript API docs](https://developers.google.com/maps/documentation/javascript/controls#ControlOptions)
86
87#### onClick (func)
88
89```
90({ x, y, lat, lng, event })
91```
92
93The `event` prop in args is the outer div onClick event, not the gmap-api 'click' event.
94
95Example:
96
97 ```javascript
98 _onClick = ({x, y, lat, lng, event}) => console.log(x, y, lat, lng, event)
99 // ES5 users
100 function _onClick(obj){ console.log(obj.x, obj.y, obj.lat, obj.lng, obj.event);}
101
102 <GoogleMap onClick={_onClick} ... />
103 ```
104
105#### onBoundsChange (func) (_Deprecated use onChange_)
106
107```
108({ center, zoom, bounds, marginBounds })
109```
110```
111[lat, lng] = center;
112[topLat, leftLng, bottomLat, rightLng] = bounds;
113```
114
115#### resetBoundsOnResize (bool)
116
117When true this will reset the map bounds if the parent resizes.
118
119Default: false
120
121#### onChildClick (func)
122
123#### onChildMouseEnter (func)
124
125#### onChildMouseLeave (func)
126
127#### onZoomAnimationStart (func)
128
129#### onDrag ((map) => void)
130
131#### onDragEnd ((map) => void)
132When the map stops moving after the user drags. Takes into account drag inertia.
133
134#### onZoomAnimationEnd (func)
135
136#### onMapTypeIdChange (func)
137When the user changes the map type (HYBRID, ROADMAP, SATELLITE, TERRAIN) this fires
138
139#### distanceToMouse (func)
140
141#### googleMapLoader (func)
142
143#### onGoogleApiLoaded (func)
144Directly access the maps API - *use at your own risk!*
145
146#### onTilesLoaded (func)
147This function is called when the visible tiles have finished loading.
148
149```javascript
150<GoogleMap onGoogleApiLoaded={({map, maps}) => console.log(map, maps)} />
151```
152
153To prevent warning message add _yesIWantToUseGoogleMapApiInternals_ property to GoogleMap
154
155```javascript
156<GoogleMap onGoogleApiLoaded={({map, maps}) => console.log(map, maps)}
157 yesIWantToUseGoogleMapApiInternals
158 />
159 ```
160
161#### overlayViewDivStyle (object)
162
163Add custom style to `div` (marker container element) created by OverlayView, for example: `{pointerEvents: 'none'}`.
164
165## Child Component API
166
167### parameters
168
169#### lat (number)
170Latitude to place the marker component
171
172#### lng (number)
173Longitude to place the marker component
174
175#### $hover (bool) [automatic]
176GoogleMap passes a $hover prop to hovered components. To detect hover it an uses internal mechanism, explained in x_distance_hover example
177
178Example:
179```javascript
180render() {
181 const style = this.props.$hover ? greatPlaceStyleHover : greatPlaceStyle;
182
183 return (
184 <div style={style}>
185 {this.props.text}
186 </div>
187 );
188 }
189 ```
190
191
192## Utility functions
193
194#### fitBounds (func)
195 Use fitBounds to get zoom and center.
196
197Example:
198
199```javascript
200import { fitBounds } from 'google-map-react/utils';
201
202const bounds = {
203 nw: {
204 lat: 50.01038826014866,
205 lng: -118.6525866875
206 },
207 se: {
208 lat: 32.698335045970396,
209 lng: -92.0217273125
210 }
211};
212
213// Or
214
215const bounds = {
216 ne: {
217 lat: 50.01038826014866,
218 lng: -118.6525866875
219 },
220 sw: {
221 lat: 32.698335045970396,
222 lng: -92.0217273125
223 }
224};
225
226const size = {
227 width: 640, // Map width in pixels
228 height: 380, // Map height in pixels
229};
230
231const {center, zoom} = fitBounds(bounds, size);
232```
233
234#### tile2LatLng (func)
235
236#### latLng2Tile (func)
237
238#### getTilesIds (func)
239
240## Tips
241
242### My map doesn't appear
243
244Make sure the container element has width and height. The map will try to fill the parent container, but if the container has no size, the map will collapse to 0 width / height.
245
246### Positioning a marker
247
248Initially any map object has its top left corner at lat lng coordinates. It's up to you to set the object origin to 0,0 coordinates.
249
250Example (centering the marker):
251
252```javascript
253const greatPlaceStyle = {
254 position: 'absolute',
255 transform: 'translate(-50%, -50%)'
256}
257```
258
259```javascript
260render() {
261 return (
262 <div style={greatPlaceStyle}>
263 {this.props.text}
264 </div>
265 );
266}
267```
268
269### Rendering in a modal
270
271If at the moment of GoogleMap control created, a modal has no size (width,height=0) or/and not displayed, the simple solution is to add something like this in render:
272
273```javascript
274render() {
275 return this.props.modalIsOpen
276 ? <GoogleMap />
277 : null;
278}
279```
280
281### Adding a SearchBox
282
283```javascript
284import React from 'react';
285import ReactDOM from 'react-dom';
286
287export default class SearchBox extends React.Component {
288 static propTypes = {
289 placeholder: React.PropTypes.string,
290 onPlacesChanged: React.PropTypes.func
291 }
292 render() {
293 return <input ref="input" {...this.props} type="text"/>;
294 }
295 onPlacesChanged = () => {
296 if (this.props.onPlacesChanged) {
297 this.props.onPlacesChanged(this.searchBox.getPlaces());
298 }
299 }
300 componentDidMount() {
301 var input = ReactDOM.findDOMNode(this.refs.input);
302 this.searchBox = new google.maps.places.SearchBox(input);
303 this.searchBox.addListener('places_changed', this.onPlacesChanged);
304 }
305 componentWillUnmount() {
306 // https://developers.google.com/maps/documentation/javascript/events#removing
307 google.maps.event.clearInstanceListeners(this.searchBox);
308 }
309}
310```
311
312You will need to preload the google maps API, but `google-map-react` checks if the base api is already loaded,
313and if so, uses it, so it won't load a second copy of the library.
314
315```html
316<script type="text/javascript" src="https://maps.google.com/maps/api/js?libraries=places"></script>
317```
318
319### Override the default minimum zoom
320
321*WARNING*: Setting this option can break markers calculation, causing no homeomorphism between screen coordinates and map.
322
323You can use the `minZoom` custom option to prevent our minimum-zoom calculation:
324
325```javascript
326function createMapOptions() {
327 return {
328 minZoom: 2,
329 };
330}
331```
332
333### Define touch device behavior of scrolling & panning for the map
334
335Google Maps provides control over the behavior of touch based interaction with the map.
336For example, on mobile devices swiping up on the map might mean two things: Scrolling the container or panning the map.
337To resolve this ambigiuity, you can use the custom map option `gestureHandling` to get the required behavior.
338
339```javascript
340function createMapOptions() {
341 return {
342 gestureHandling: 'greedy' // Will capture all touch events on the map towards map panning
343 }
344}
345```
346
347The default setting is `gestureHandling:auto` which tries to detect based on the page/content sizes if a `greedy` setting is best (no scrolling is required) or `cooperative` (scrolling is possible)
348
349For more details see the [google documentation](https://developers.google.com/maps/documentation/javascript/interaction) for this setting.
350
351### Heatmap Layer
352
353To use the heatmap layer, add `heatmapLibrary={true}` to add the visualizations library, and provide the data&configuration for the heatmap in `heatmap` as props.
354
355The typescript interface for the heatmap prop is as follows:
356```typescript
357interface heatmapProp {
358 positions: {
359 lat: Number;
360 lng: Number;
361 weight?: Number;
362 }[];
363 options: {
364 radius?: number;
365 opacity?: number;
366 /* other options directly from Google Heatmaps API */
367 };
368}
369```
370
371#### Example [Demo](https://google-map-react.github.io/google-map-react-examples/heatmap)
372
373```javascript
374<GoogleMapReact
375 bootstrapURLKeys={{ key: [YOUR_KEY] }}
376 zoom={zoom}
377 center={center}
378 heatmapLibrary={true}
379 heatmap={{data}}
380 >
381 {markers}
382 </GoogleMapReact>
383```
384
385#### Important Note
386
387If you have multiple `GoogleMapReact` components in project and you want to use heatmap layer so provide `heatmapLibrary={true}` for all `GoogleMapReact` components so component will load heatmap library at the beginning with google map api.
388
389### Localizing the Map
390
391This is done by setting bootstrapURLKeys.[language](https://developers.google.com/maps/documentation/javascript/localization#Language) and bootstrapURLKeys.[region](https://developers.google.com/maps/documentation/javascript/localization#Region). Also notice that setting region to 'cn' is required when using the map from within China, see [google documentation](https://developers.google.com/maps/documentation/javascript/localization#GoogleMapsChina) for more info. Setting 'cn' will result in use of the specific API URL for China.