一直忘記更精耐,直接上代碼狼速。
一點碎碎念
雖然還有一些功能實現(xiàn)沒有發(fā)出來,但是后續(xù)應(yīng)該不會再更新原生天地圖API的內(nèi)容了卦停,主要有以下原因:
1向胡、以前的代碼寫的很亂,整理起來比較頭疼(真想給去年的自己一拳)惊完。
2僵芹、這些內(nèi)容都是接觸前端地圖框架之前為了完成需求所琢磨的原生天地圖API用法,在那個時候我屬于是懂點GIS但是不知道有WebGIS框架小槐,所以其實屬于比較笨的方法拇派。
3、對于要求用到天地圖的項目凿跳,我建議還是使用一個前端WebGIS框架件豌,引入天地圖作為底圖,再通過框架去實現(xiàn)各種需求控嗜。
<script setup>
import {onMounted, ref} from "vue";
var marker = null
var map
const currentLngLat = ref([1114.51444, 22.114514])
const locateInfo = ref('')
//直接定義infoWin的內(nèi)容以及樣式
const infoWinContent = ref(" \<div class='infoWin''>\ " +
" \<div class='infoWin-deg' style='left:266px ;rotate: 90deg '></div>\ "+
" \<div class='infoWin-deg' style='top: 178px ;rotate: 270deg'></div>\ "+
" \<div class='infoWin-deg'></div>\ "+
" \<div class='infoWin-title'>所選地點詳情</div>\ "+
"\<div class='infoWin-body' style='margin:10px 0;height: 80px '>\ " +
" \<div id='info' class='info-r'> " +
" \</div>\ " +
"\<div id='infoBtn' class='info-button' >\ " +
"查看選址信息" +
"\</div>\ " +
"\</div>\ " +
" \</div>\ "
)
onMounted(() => {
init();
});
const init = () => {
//這里T指向天地圖對象
var T = window.T
//初始化地圖茧彤,創(chuàng)建一個新的地圖實例
map = new T.Map("mapDiv","EPSG:4326")
map.setMapType(window.TMAP_HYBRID_MAP )
map.centerAndZoom(new T.LngLat(114.51444, 22.114514), 13)
//創(chuàng)建坐標拾取組件,并設(shè)置回調(diào)函數(shù)疆栏,該組件會將拾取到的坐標點傳給回調(diào)函數(shù)
var cp = new T.CoordinatePickup(map, {callback: handChoose})
//啟用坐標拾取功能
cp.addEvent()
}
const handChoose = (lnglat) => {
//手動標點功能
if (marker){
map.removeOverLay(marker)
}
currentLngLat.value = [lnglat.lng.toFixed(6),lnglat.lat.toFixed(6)]
marker = new T.Marker(T.LngLat(currentLngLat.value[0], currentLngLat.value[1]));
map.addOverLay(marker)
getDetailLocation(currentLngLat.value[0],currentLngLat.value[1])
openInfoWin(currentLngLat.value)
}
const getDetailLocation = (lnglat_lng, lnglat_lat) => {
axios({
url: "https://api.tianditu.gov.cn/geocoder",
methods: 'post',
params: {
tk: 'YOUR_TOKEN',
type: "geocode",
postStr: "{'lon':" + lnglat_lng + ",'lat':" + lnglat_lat + ",'ver':1}"
}})
.then(
(data) => {
let addressdata = data.data
//保存地址信息
locateInfo.value = addressdata.result.formatted_address;
},
)
.catch(
(error) => {
alert("獲取失敗");
}
)
}
const openInfoWin = (lnglat) => {
//綁定信息窗口
if (infoWin){
infoWin.closeInfoWindow()
}
infoWin = new T.InfoWindow();
infoWin.setLngLat(lnglat)
infoWin.setContent(infoWinContent.value)
marker.openInfoWindow(infoWin)
setTimeout(()=>{
//將地址信息顯示在span上
let e = document.getElementById('info')
e.append(locateInfo.value)
document.getElementById('infoBtn').onclick = function () {
//點擊事件
showAddressInfo()
};
},500)
}
const showAddressInfo = () => {
console.log('showAddressInfo')
}
</script>