1. 程式人生 > 其它 >地圖找房功能實現

地圖找房功能實現

importReact,{PureComponent}from'react'
importaxiosfrom'axios' import{Link}from'react-router-dom' import{Toast}from'antd-mobile'
importNavHeaderfrom'../../components/NavHeader' importstylesfrom'./index.module.css'
constBMap=window.BMap letbaseUrl="http://localhost:8080" exportdefaultclassMapextendsPureComponent{
constructor(props){ super(props) this.state={ //小區下的房源列表 houseList:[], isShowList:false } } componentDidMount(){ this.initMap(); }
//初始化地圖 initMap(){ //1獲取當前城市 const{label,value}=JSON.parse(localStorage.getItem('hkzf_city')) //console.log(label,value) //初始化地圖例項 constmap=newBMap.Map('container') this.map=map //設定中心點座標 varmyGeo=newBMap.Geocoder(); //將地址解析結果顯示在地圖上,並調整地圖視野 myGeo.getPoint(label,asyncpoint=>{ if(point){ //初始化地圖 map.centerAndZoom(point,11) //map.addOverlay(newBMap.Marker(point,{title:'北京市海淀區上地10街'})) //新增縮放控制元件 map.addControl(newBMap.NavigationControl()) //新增地圖控制元件 map.addControl(newBMap.ScaleControl()) this.renderOverlays(value) } },label)
//給地圖繫結移動事件隱藏房源列表 map.addEventListener('movestart',()=>{ if(this.state.isShowList){ this.setState({ isShowList:false }) } }) }
asyncrenderOverlays(id){ //開啟loading0表示不需要關閉 Toast.loading('載入中...',0,null,false) //獲取房源資料 constres=awaitaxios.get(`${baseUrl}/area/map?id=${id}`) constdata=res.data.body //console.log(data) const{nextZoom,type}=this.getTypeAndZoom() //關閉loading Toast.hide()
data.forEach(item=>{ //建立覆蓋物 this.createOverlays(item,nextZoom,type) }); }
//獲取地圖級別和型別 getTypeAndZoom(){ //獲取當前地圖級別 constzoom=this.map.getZoom() letnextZoom,type //console.log(zoom) if(zoom>=10&&zoom<12){ //區 nextZoom=13 //circle表示繪製原型覆蓋物 type='circle' }elseif(zoom>=12&&zoom<14){ //鎮 nextZoom=15 //circle表示繪製原型覆蓋物 type='circle' }elseif(zoom>=14&&zoom<16){ //circle表示繪製原型覆蓋物 type='rect' }
return{ nextZoom, type } }
//建立覆蓋物 createOverlays(data,zoom,type){ //為每一條資料建立覆蓋物 const{coord:{latitude,longitude},label:areaName,count,value}=data
//建立座標物件 constarteaPoint=newBMap.Point(longitude,latitude) if(type==='circle'){ //區和鎮 this.createCircle(arteaPoint,areaName,count,value,zoom) }else{ //小區 this.createRect(arteaPoint,areaName,count,value,zoom) } } //區和鎮 createCircle(point,name,count,id,zoom){ constopts={ position:point, offset:newBMap.Size(35,-35) } //設定setContent後,第一個引數為空就行 constlabel=newBMap.Label('',opts) //設定唯一值 label.id=id //設定房源覆蓋物內容 label.setContent(` <divclass="${styles.bubble}"> <pclass="${styles.name}">${name}</p> <p>${count}套</p> </div> `)
//設定樣式 label.setStyle({ cursor:'pointer', border:'0pxsolidrgb(255.0,0)', padding:'0', whiteSpace:'nowrap', fontSize:'12px', color:'rgb(255,255,255)', textAlign:'center' })
//新增單擊事件 label.addEventListener('click',()=>{
//呼叫renderOverlays方法獲取該區域下的房源資料 this.renderOverlays(label.id) //以當前點選的覆蓋物為中心放大地圖 this.map.centerAndZoom(point,zoom); //解決百度js從報錯問題 setTimeout(()=>{ //清除當前覆蓋物資訊 this.map.clearOverlays() }) }) //將文字覆蓋物新增到地圖中 this.map.addOverlay(label) }
//繪製小區覆蓋物 createRect(point,name,count,id,zoom){ constopts={ position:point, offset:newBMap.Size(-50,-28) } //設定setContent後,第一個引數為空就行 constlabel=newBMap.Label('',opts) //設定唯一值 label.id=id //設定房源覆蓋物內容 label.setContent(` <divclass="${styles.rect}"> <spanclass="${styles.housename}">${name}</span> <spanclass="${styles.housenum}">${count}套</span> <iclass="${styles.arrow}"></i> </div> `)
//設定樣式 label.setStyle({ cursor:'pointer', border:'0pxsolidrgb(255.0,0)', padding:'0', whiteSpace:'nowrap', fontSize:'12px', color:'rgb(255,255,255)', textAlign:'center' })
//新增單擊事件 label.addEventListener('click',(e)=>{ //console.log(id) this.getHouseList(id)
//獲取當前被點選項 consttarget=e.changedTouches[0] //console.log(target) //移動到座標中心點 this.map.panBy(window.innerWidth/2-target.clientX, (window.innerHeight-330)/2-target.clientY) }) //將文字覆蓋物新增到地圖中 this.map.addOverlay(label) } //獲取小區房源資料 asyncgetHouseList(id){ //開啟loading0表示不需要關閉 Toast.loading('載入中...',0,null,false) constres=awaitaxios.get(`${baseUrl}/houses?cityId=${id}`) //關閉loading Toast.hide() //console.log(res) this.setState({ houseList:res.data.body.list, isShowList:true }) }
//封裝渲染房屋列表的方法 renderHousesList(){ let{houseList}=this.state if(!houseList.length)return returnhouseList.map(item=>( <divclassName={styles.house}key={item.houseCode}> <divclassName={styles.imgWrap}> <imgclassName={styles.img}src={`${baseUrl}${item.houseImg}`}alt=""/> </div>
<divclassName={styles.content}> <h3className={styles.title}>{item.title}</h3> <divclassName={styles.desc}>{item.desc}</div> </div>
<div> {/*['近地鐵','隨時看房']*/} {item.tags.map((tag,index)=>{ consttagClass='tag'+(index+1) return( <spanclassName={[styles.tag,styles[tagClass]].join('')}key={tag}> {tag} </span> ) })} </div>
<divclassName={styles.price}> <spanclassName={styles.priceNum}>{item.price}</span>元/月 </div> </div> )) }
render(){ return( <divclassName={styles.map}> <divclassName={styles.mapAmNavbar}> <NavHeader>地圖找房</NavHeader> </div> <divid="container"className={styles.container}></div>
{/*房源列表*/} {/*新增styles.show展示房屋列表*/} <div className={[styles.houseList,this.state.isShowList?styles.show:''].join('')}> <divclassName={styles.titleWrap}> <h1className={styles.listTitle}>房屋列表</h1> <LinkclassName={styles.titleMore}to="/home/list"> 更多房源 </Link> </div>
<divclassName={styles.houseItems}> {/*房屋結構*/} {this.renderHousesList()} </div> </div> </div> ) }
} 我是Eric,手機號是13522679763