Last active
November 17, 2017 12:33
-
-
Save r3-yamauchi/f8b229f80f9c8f716e8619889ae77d95 to your computer and use it in GitHub Desktop.
Google Pickerを使って場所(緯度・経度)を選択させる https://blog.r3it.com/google-picker-map-81ad931d5bd0
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
import React, { Component } from "react"; | |
import PropTypes from "prop-types"; | |
import loadScript from "load-script"; | |
let scriptLoadingStarted = false; | |
export default class GoogleChooser extends React.Component { | |
static propTypes = { | |
children: PropTypes.node, | |
onChange: PropTypes.func, | |
createPicker: PropTypes.func | |
}; | |
static defaultProps = { | |
onChange: () => { } | |
}; | |
constructor(props) { | |
super(props); | |
this.onApiLoad = this.onApiLoad.bind(this); | |
this.onChoose = this.onChoose.bind(this); | |
} | |
componentDidMount() { | |
if (this.isGoogleReady()) { | |
this.onApiLoad(); | |
} else if (!scriptLoadingStarted) { | |
scriptLoadingStarted = true; | |
loadScript("https://apis.google.com/js/api.js", this.onApiLoad); | |
} | |
} | |
onApiLoad() { | |
window.gapi.load("picker"); | |
} | |
onChoose() { | |
if (!this.isGoogleReady() || !this.isGooglePickerReady()) { | |
return null; | |
} | |
this.createPicker(); | |
} | |
isGoogleReady() { | |
return Boolean(window.gapi); | |
} | |
isGooglePickerReady() { | |
return Boolean(window.google.picker); | |
} | |
createPicker() { | |
const picker = new window.google.picker.PickerBuilder() | |
.addView(google.picker.ViewId.MAPS) | |
.setLocale("ja") | |
.setCallback(this.props.onChange) | |
.build() | |
.setVisible(true); | |
} | |
render() { | |
return ( | |
<div onClick={this.onChoose}> | |
{ | |
this.props.children ? | |
this.props.children : | |
<button>Pickerを開く</button> | |
} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment