-
Notifications
You must be signed in to change notification settings - Fork 925
Expand file tree
/
Copy pathwithGoogleMap.jsx
More file actions
93 lines (79 loc) · 2.56 KB
/
withGoogleMap.jsx
File metadata and controls
93 lines (79 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* global google */
import _ from "lodash"
import warning from "warning"
import invariant from "invariant"
import { getDisplayName } from "recompose"
import PropTypes from "prop-types"
import React from "react"
import { MAP } from "./constants"
export function withGoogleMap(BaseComponent) {
const factory = React.createFactory(BaseComponent)
class Container extends React.PureComponent {
static displayName = `withGoogleMap(${getDisplayName(BaseComponent)})`
static propTypes = {
containerElement: PropTypes.node.isRequired,
mapElement: PropTypes.node.isRequired,
}
static childContextTypes = {
[MAP]: PropTypes.object,
}
state = {
map: null,
}
handleComponentMount = _.bind(this.handleComponentMount, this)
getChildContext() {
return {
[MAP]: this.state.map,
}
}
componentWillMount() {
const { containerElement, mapElement } = this.props
invariant(
!!containerElement && !!mapElement,
`Required props containerElement or mapElement is missing. You need to provide both of them.
The \`google.maps.Map\` instance will be initialized on mapElement and it's wrapped by\
containerElement.\nYou need to provide both of them since Google Map requires the DOM to\
have height when initialized.`
)
}
handleComponentMount(node) {
if (this.state.map || node === null) {
return
}
warning(
`undefined` !== typeof google,
`Make sure you've put a <script> tag in your <head> element to load Google Maps JavaScript API v3.
If you're looking for built-in support to load it for you, use the "async/ScriptjsLoader" instead.
See https://github.com/tomchentw/react-google-maps/pull/168`
)
// https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map
const map = new google.maps.Map(node, this.props.googleMapSettings)
this.setState({ map })
}
render() {
const { containerElement, mapElement, ...restProps } = this.props
const { map } = this.state
if (map) {
return React.cloneElement(
containerElement,
{},
React.cloneElement(mapElement, {
ref: this.handleComponentMount,
}),
<div>{factory(restProps)}</div>
)
} else {
return React.cloneElement(
containerElement,
{},
React.cloneElement(mapElement, {
ref: this.handleComponentMount,
}),
<div />
)
}
}
}
return Container
}
export default withGoogleMap