joywok-material-components
Version:
<h1 align="center"> Joywok Material Components </h1>
431 lines (422 loc) • 17.6 kB
JavaScript
/**
组件说明:
输入参数:detail_address 或者 详细地址 name(如:北京市石景山区老山街道老山西街老山西街7号院)。
detail_address 是一个对象
{
longitude:经度,
latitude:纬度,
province:省,
city:市,
district:区/县
street:街道
image:图片id
location:地图定位位置 如:融科创意中心A座
location_name:地图定位建筑物名称 如:八角东街181号
}
如经纬度有值,地图通过经纬度显示定位点。如果没有传入经纬度,那么就通过详细地址反查经纬度,查到经纬度后再做定位渲染
输出参数:给到外层一个对象,对象中含有 如下信息:
{
detail_address: {
longitude:经度,
latitude:纬度,
province:省,
city:市,
district:区/县
street:街道
image:图片id
location:地图定位位置 如:融科创意中心A座
location_name:地图定位建筑物名称 如:八角东街181号
},
name:self.state.name,
aois:self.state.aois,
}
*/
import React,{ Component }from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { connect } from 'dva';
import request from './../utils/request';
import {Input,Modal,message} from 'antd';
import Button from './../button/index';
import Tip from './../tips/aloneTip'
require('./style/Index.css');
class MapContainer extends Component{
constructor(props) {
super(props);
this.state = Object.assign({},{
loading:true,
detail_address:{},
name:'',
lang:'zh',
key:'544c827260b7a6b6712093039958f873',
},props.data,props)
this.time = null;
}
fetchAddress(lng,lat){
let self = this;
let location = lng+','+lat;
this.geocoder_zh = new AMap.Geocoder({
lang:'zh',
extensions:"all"
});
this.geocoder_en = new AMap.Geocoder({
lang:'en',
extensions:"all"
});
message.destroy();
// message.loading('正在获取相关数据…')
// message.loading('正在获取数据…')
message.loading(i18n('label.portal.event.get.mapdata'))
this["geocoder_"+this.state.lang].getAddress([lng,lat], function(status, result) {
message.destroy();
if (status === 'complete' && result.info === 'OK') {
console.log('result---',result)
// result为对应的地理位置详细信息
let data = Object.assign({}, {
longitude: lng,
latitude: lat,
province: result.regeocode['addressComponent']['province'],
city: result.regeocode['addressComponent']['city'],
district: result.regeocode['addressComponent']['district'],
street: result.regeocode['addressComponent']['township'],
image: '',
location: result.regeocode['aois'].length!=0?result.regeocode['aois'][0].name:"",
location_name: result.regeocode['pois'].length!=0?result.regeocode['pois'][0].address:""
})
self.setState({
detail_address: data,
aois:result.regeocode['aois'],
pois:result.regeocode['pois'],
name:result.regeocode['formattedAddress']
})
}
})
}
save(){
let self=this;
let {lang,aois,pois}=this.state;
if(aois&&aois[0] || pois&&pois[0]){
// message.loading('正在获取地址数据…');
message.loading(i18n('label.portal.event.get.address.data'));
AMap.plugin('AMap.PlaceSearch', function () {
var placeSearch = new AMap.PlaceSearch({
lang : lang=='zh'?"en":"zh_cn"
})
// 对应的POI ID
var poiid = aois&&aois[0]?aois[0]['id']:pois[0]['id']
placeSearch.getDetails(poiid, function(status, result) {
message.destroy();
if (status === 'complete' && result.info === 'OK') {
// 查询成功时,result即为对应的POI详情
let resData=result.poiList&&result.poiList.pois[0];
let detailAddress=self.state.detail_address;
let curLangData={
name: detailAddress['location'],
address: detailAddress['location_name'],
latitude: detailAddress['latitude'],
longitude: detailAddress['longitude'],
"type": "geo"
}
let curLangD={
name:resData&&resData['name'],
address:resData&&resData['address'],
latitude: detailAddress['latitude'],
longitude: detailAddress['longitude'],
"type": "geo"
}
let detailData={};
if(lang=="zh"){
detailData['zh']=curLangData;
detailData['en']=curLangD;
}else{
detailData['en']=curLangData;
detailData['zh']=curLangD;
}
self.props.events.emit('save',{
name:self.state.name,
aois:self.state.aois,
detail_address:self.state.detail_address,
detailData:detailData
});
self.props.events.emit('cancel');
}
})
})
}else{
self.props.events.emit('cancel');
}
}
combineMapPlugin(){
let self = this;
self.map.plugin([ 'AMap.ToolBar','AMap.Autocomplete','AMap.PlaceSearch'], function () {
self.map.addControl(new AMap.ToolBar({
lang:self.state.lang
}));
self.auto = new AMap.Autocomplete({
input: "tipinput",
lang:self.state.lang
});
self.map.addControl(self.auto);
var placeSearch = new AMap.PlaceSearch({
map: self.map,
lang:self.state.lang
}); //构造地点查询类
self.map.addControl(placeSearch);
function select(e) {
if(e.poi['id'].length==0){
// message.error('没有获取到搜索的位置',2);
// message.error('未找到您搜索的位置',2);
message.error(i18n('label.event.noposition'),2);
return
}
self.map.setZoom(15);
self.map.panTo([e.poi['location']['lng'],e.poi['location']['lat']]);
clearTimeout(self.time);
self.time = setTimeout(function(){
self.combineMapLocation(e.poi['location']['lng'],e.poi['location']['lat'])
self.fetchAddress(e.poi['location']['lng'],e.poi['location']['lat']);
},200)
}
AMap.event.addListener(self.auto, "select", select);
self.map.on('click', function(e){
clearTimeout(self.time);
self.time = setTimeout(function(){
self.combineMapLocation(e['lnglat']['lng'],e['lnglat']['lat'])
self.fetchAddress(e['lnglat']['lng'],e['lnglat']['lat']);
},200)
});
self.map.on('dblclick',function(){
clearTimeout(self.time);
})
if(typeof(self.marker)!='undefined'){
self.map.remove(self.marker);
}
if(self.state.name && self.state.name.length!=0){
self.marker = new AMap.Marker({
lang:self.state.lang,
// position: self.state.address.streetNumber.location && self.state.address.streetNumber.location.length!=0?self.state.address.streetNumber.location.split(','):self.state.aois[0].location.split(','),
offset: new AMap.Pixel(-12, -33)
});
self.map.add(self.marker);
}
});
}
combineMapLocation(lng,lat){
let self = this;
if(typeof(self.marker)!='undefined'){
self.map.remove(self.marker);
}
// lat: 39.911534 lng: 116.403458
self.marker = new AMap.Marker({
lang:self.state.lang,
position: [lng,lat],
offset: new AMap.Pixel(-12, -33),
});
self.map.add(self.marker);
}
componentDidMount(){
let self = this;
var script=document.createElement('script');
script.type="text/javascript";
// script.src='https://webapi.amap.com/maps?v=1.4.15&key=0dfc4d46208fc4478eadb34410fba73b&plugin=AMap.Geocoder,AMap.ToolBar,AMap.Autocomplete,AMap.PlaceSearch';
script.src='https://webapi.amap.com/maps?v=1.4.15&key='+this.state.key+'&plugin=AMap.Geocoder,AMap.ToolBar,AMap.Autocomplete,AMap.PlaceSearch';
script.class='hahaha'
document.body.appendChild(script);
script.onload = function(){
self.setState({loading:false});
self.init_map();
}
}
init_map(){
let self = this;
let longitude = self.state.detail_address.longitude;
let latitude = self.state.detail_address.latitude;
let data = self.props.data.detail_address;
// 有经纬度,就用经纬度渲染。没有经纬度,就通过详细地址获取经纬度后再做渲染
let errormsg = ''
if(longitude&&latitude&&longitude!=""&&latitude!=""){
self.map = new AMap.Map('map-container', {
animateEnable:true,
resizeEnable: true, //是否监控地图容器尺寸变化
zoom:15, //初始化地图层级
center: [longitude,latitude], //初始化地图中心点
lang:self.state.lang
});
self.combineMapPlugin();
self.combineMapLocation(longitude,latitude);
self.fetchAddress(longitude,latitude);
}else if(self.props.data.name=="" && (data.province=='' && data.city=="" && data.district=='') || (JSON.stringify(data.province)=="{}"&&JSON.stringify(data.city)=="{}"&&JSON.stringify(data.district)=="{}")){
self.map = new AMap.Map('map-container', {
animateEnable:true,
resizeEnable: true, //是否监控地图容器尺寸变化
zoom:15, //初始化地图层级
lang:self.state.lang
});
AMap.plugin('AMap.CitySearch', function () {
var citySearch = new AMap.CitySearch({lang:self.state.lang})
citySearch.getLocalCity(function (status, result) {
if (status === 'complete' && result.info === 'OK') {
// 查询成功,result即为当前所在城市信息
self.combineMapPlugin();
// self.combineMapLocation(data.position.lng,data.position.lat);
// self.fetchAddress(data.position.lng,data.position.lat);
}else{
// errormsg = '没有获取到当前城市';
// message.error('没有获取到当前城市',2);
// message.error('未获取到当前城市信息',2);
message.error(i18n('label.portal.event.nocity'),2);
return
}
})
})
if(longitude.length==0 && latitude.length==0){
AMap.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位,默认:true
// timeout: 10000, //超过10秒后停止定位,默认:5s
// buttonPosition:'RB', //定位按钮的停靠位置
buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
// zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
GeoLocationFirst:true
});
console.log("geolocation::::",geolocation.getCurrentPosition())
self.map.addControl(geolocation);
// geolocation.getCurrentPosition();
geolocation.getCityInfo();
AMap.event.addListener(geolocation, 'complete', onComplete)
AMap.event.addListener(geolocation, 'error', onError);
function onComplete(data){
self.combineMapPlugin();
self.combineMapLocation(data.position.lng,data.position.lat);
self.fetchAddress(data.position.lng,data.position.lat);
}
function onError(error){
console.log(error,'这个是什么啊');
message.error(error&&error.message,2);
return
}
})
}
}else{
let keywords;
if((data.province.name&&data.province.name!="") || (data.province&&data.province!="")){
// keywords = (data.province.name ? data.province.name : data.province) + (data.city.name=="市辖区" || data.city.length==0 ? "" : (data.city.name ? data.city.name : data.city)) + (data.district.name ? data.district.name : data.district) + (data.street ? data.street : data.township);
keywords = self.props.data.name!='' ? self.props.data.name : data.province.name + (data.city.name=="市辖区" ? "" : data.city.name) + data.district.name + data.street
}else{
keywords = self.props.data.name
}
// console.log("keywords::::",keywords)
AMap.plugin('AMap.Geocoder', function() {
var geocoder = new AMap.Geocoder({
city: self.props.data.name.split('市')[0] || self.props.data.name.split('省')[0] || self.props.data.name.split('自治区')[0],
lang:self.state.lang
})
// 使用geocoder做地理/逆地理编码 根据详细地址查询经纬度,根据经纬度渲染点标记
geocoder.getLocation(keywords, function(status, result) {
if (status === 'complete' && result.info === 'OK') {
// result中对应详细地理坐标信息
console.log(result,'asdasdasdasda');
if(result.geocodes&&result.geocodes.length>0){
let geocode = result.geocodes[0];
// console.log("geocode::::",geocode)
if(geocode.location){
self.map = new AMap.Map('map-container', {
animateEnable:true,
resizeEnable: true, //是否监控地图容器尺寸变化
zoom:15, //初始化地图层级
center: [geocode.location.lng,geocode.location.lat],//初始化地图中心点,
lang:self.state.lang
});
// console.log('result:',geocode.location.lng,geocode.location.lat);
self.combineMapPlugin();
self.combineMapLocation(geocode.location.lng,geocode.location.lat);
self.fetchAddress(geocode.location.lng,geocode.location.lat);
}else{
// message.error('没有找到相应的经纬度',2);
// message.error('未找到相应的经纬度',2);
message.error(i18n('label.portal.event.nolanglan'),2);
return
}
}
}
console.log(status,'asdasdas');
})
})
}
}
cancel(){
this.props.events.emit('cancel');
$(".amap-sug-result").addClass('hide');
}
render(){
let self = this;
let newName = self.props.data.detail_address.province.name + (self.props.data.detail_address.city.name=="市辖区" ? "" : self.props.data.detail_address.city.name) + self.props.data.detail_address.district.name + self.props.data.detail_address.street;
return (<div className="jw-map">
<div className="jw-map-w">
{
this.state.loading?"":<div className="jw-map-search">
<Input placeholder={i18n('label.biportal-placeholder')} id="tipinput"/>
</div>
}
{
this.state.loading?<div className="jw-map-loading-c"><div className="jw-map-loading"></div></div>:<div className="jw-map-c" id="map-container"></div>
}
</div>
<div className="jw-map-footer">
<div className="jw-map-btns">
<Button className="jw-map-btn-cancel" onClick={(e)=>this.cancel(e)}>{i18n('btn.cancel')}</Button>
<Button className="jw-map-btn-save" onClick={(e)=>this.save(e)}>{i18n('btn.ok')}</Button>
</div>
<div className="jw-map-address">
{/* <div className="jw-map-address-tip">详细地址:</div> */}
<div className="jw-map-address-tip">{i18n('label.console.iam.dAddress')}:</div>
<div className="jw-map-address-value ellipsis" title={ this.state.name && this.state.name.length!=0 ? this.state.name: (newName=='NaN' ? '' : newName)}>{
this.state.name && this.state.name.length!=0 ? this.state.name: (newName=='NaN' ? '' : newName)
}</div>
</div>
</div>
</div>)
}
}
class Map extends Component{
constructor(props) {
super(props);
}
countTop() {
let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
if (this.container.height() < clientHeight) {
$('#' + this.props.containerId).css({
top: (clientHeight - this.container.height()) / 2 + 'px'
})
} else {
}
}
render(){
let modalData = this.props.modal || {};
let modal = _.extend({},{
width:modalData&&modalData.width?modalData.width:'700px',
destroyOnClose:true,
getContainer:()=>document.getElementById(this.props.containerId),
title:null,
visible:true,
footer:null,
onCancel:(e)=>this.props.close(e),
ref:"modal",
maskClosable: false
},modalData);
let customClass = modal.customClass || '';
return (<div className={"dialog-c "+customClass} id={this.props.containerId}>
<Modal {...modal}>
<MapContainer {...this.props.data} events={this.props.events}></MapContainer>
</Modal>
</div>)
}
componentDidMount() {
let self = this;
let datas = this.props.modal || {};
let container = ($('#' + this.props.containerId));
this.container = container;
}
}
export default Map;