我是一个相对较新的ReactJS学习者,我试图显示您使用ReactJS输入的地址的Google地图。当我点击有效地址的提交按钮时,我得到一个奇怪的外观,我有window.alert消息告诉我,我得到了我期望的纬度和长度: 我也在控制台中遇到这些消息,我读过这些消息是因为React与DOM交互的方式并不是Google所期望的。
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<style>
.map-gic {
height: 500px;
width: 500px
}
body{
width: 500px;
height: 500px;
}
</style>
<title>Hello React</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key="></script>
</head>
<body>
<div id="content" style="height:500px; width:500px; position: absolute;">
</div>
<script type="text/jsx">
var apiKey = "";
var AddressForm = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var address = React.findDOMNode(this.refs.address).value.trim();
if (!address) {
// handle errors
}
this.props.onAddressSubmit(address);
},
render: function() {
return (
<form className="address" onSubmit={this.handleSubmit}>
<input type="text" placeholder="enter address" ref="address"/>
<input type="submit" value="Post" />
</form>
);
}
});
var AddressBox = React.createClass({
getInitialState: function () {
return {lat: 0, lng: 0};
},
displayMap: function(address) {
var fixedAddress = address.trim().replace(" ","+");
var request = "https://maps.googleapis.com/maps/api/geocode/json?address=" + fixedAddress + "&key=" + apiKey;
$.ajax({
url: request,
dataType: 'json',
type: 'GET',
data: address,
success: function(data) {
var location = data["results"][0]["geometry"]["location"];
//window.alert("lat is " + location["lat"] + ", and lng is " + location["lng"]);
this.setState({lat: location["lat"], lng: location["lng"]});
}.bind(this),
error: function(xhr, status, err) {
console.error(status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<div className="addressBox">
<h1>Look up an address to see its location</h1>
<AddressForm onAddressSubmit={this.displayMap}/>
<GoogleMap lat={this.state.lat} lng={this.state.lng}/>
</div>
);
}
});
var GoogleMap = React.createClass({
componentDidUpdate: function() {
var lat = this.props.lat;
var lng = this.props.lng;
window.alert("lat is " + lat + ", and lng is " + lng);
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(this.getDOMNode(), mapOptions);
},
render: function() {
return(
<div className='map-gic'></div>
);
}
});
React.render(
<AddressBox/>,
document.getElementById('content')
);
</script>
</body>
</html>
注意:我已经取出了我的API密钥,因为我不确定是否应该分享它。
总结:
谢谢!