想找任何关于百度地图REACT 的东西,有大神不吝啬赐给我的吗?
百度地图,任何关于百度地图
pasturn
#4
我之前项目里有用到百度地图,可以讲一下。
首先是加载:我这里是直接在html里异步加载了百度地图
<script src="http://api.map.baidu.com/api?v=2.0&ak=你的AK&callback=init" type="text/javascript"></script>
回调方法init不用管。但是不能去掉,不然无法正常异步加载百度地图的js。
本来在npm看到一个react-baidu-map,看了一下代码,不太适合自己项目的使用场景,但是有一些参考价值,于是就自己写了一个组件,主要功能是通过父组件的输入框输入地址自动调用地图接口自动搜索经纬度并在地图上进行标注,同时返回经纬度到父组件的输入框里:
import React from 'react'
const BaiduMap = React.createClass({
getInitialState(){
return {
map: null,
point: null,
}
},
getDefaultProps(){
return {
id: 'location',
storeAddress: '',
mapArea: '',
ak: null
}
},
componentWillReceiveProps(nextProps){
if (nextProps.storeAddress !== this.props.storeAddress || nextProps.mapArea !== this.props.mapArea) {
this.addressToPoint(nextProps)
}
if (!nextProps.storeAddress && !nextProps.mapArea && nextProps.storeAddress !== this.props.storeAddress) {
this.setState({
map: this.createBMap(this.props.id)
});
}
},
componentDidMount() {
this.setState({
map: this.createBMap(this.props.id)
});
},
createBMap(id){
let map = new BMap.Map(id);
let point = new BMap.Point(116.404, 39.915);
map.addControl(new BMap.NavigationControl());
map.centerAndZoom(point, 10);
map.enableScrollWheelZoom();
function setLocal(result) {
const cityName = result.name;
map.setCenter(cityName);
}
let myCity = new BMap.LocalCity();
myCity.get(setLocal);
return map
},
addressToPoint(nextProps){
const {onSelect} = this.props;
const { map } = this.state;
const marker = this.marker;
map.clearOverlays();
let myPoint = new BMap.Geocoder();
myPoint.getPoint(nextProps.mapArea + nextProps.storeAddress, function (poi) {
map.centerAndZoom(poi, 17);
map.addOverlay(marker(poi));
onSelect(poi)
}, nextProps.mapArea)
},
marker(poi){
let marker = new BMap.Marker(poi);
marker.setAnimation(BMAP_ANIMATION_BOUNCE);
return marker
},
render(){
return (
<div id={this.props.id} {...this.props}></div>
)
}
});
BaiduMap.propTypes = {
id: React.PropTypes.string,
mapArea: React.PropTypes.string,
storeAddress: React.PropTypes.string
};
export default BaiduMap
1 Like