先看效果
1.引入脚本
<script type="text/javascript" src="http://api.tianditu.gov.cn/api?v=4.0&tk=key"></script>
2.html部分
<div class="form-group"><label class="col-sm-3 control-label">选取坐标</label><div class="col-sm-9"><div id="container" class="map"></div><div class="search" style="z-index: 999; opacity: 0.6;"><input id="complete" type="text" placeholder="输入您要定位的地址" style="width:70%;"/><button type="button" class="btn" onClick="localsearch.search(document.getElementById('complete').value,7)">搜索</button>@*<div class="list-group"> 此处用到 Bootstrap<button type="button" class="list-group-item">Cras justo odio</button></div>*@</div></div></div>
3.js部分 初始化地图中心点 搜索对象 点击地图事件
var autocomplete;
var localsearch;
var tianditumap;function ontiandituLoaded() {// 初始化天地图地图tianditumap = new T.Map('container', {projection: 'EPSG:3785'})// 中心点和初始化级别// 如果是编辑设备, 则设置原站点的坐标为中心点, 否则不设置, 默认//if (g_info.isEdit === true) { alert("zj"); alert(g_info.LONG); map.centerAndZoom(new T.LngLat(g_info.LONG, g_info.LAT), 12); }//else { alert("bj"); map.centerAndZoom(new T.LngLat(116.40769, 39.89945), 12); }tianditumap.centerAndZoom(new T.LngLat(114.42594, 30.4555), 15);var Searchconfig = {pageCapacity: 5, //每页显示的数量onSearchComplete: localSearchResult //接收数据的回调函数};//创建搜索对象localsearch = new T.LocalSearch(tianditumap, Searchconfig);// 地图点击事件tianditumap.addEventListener("click", (e) => {setLocationInputVal(e.lnglat);});
}
4. js部分 搜索回调方法 和点击定位
function localSearchResult(result) {let obj = result.getPois();if (obj) {//坐标数组,设置最佳比例尺时会用到var zoomArr = [];var divMarker = document.createElement("div");divMarker.className = "list-group";obj.forEach((item) => {var buttont1 = document.createElement("button");buttont1.type = "button";buttont1.className = "list-group-item";buttont1.innerHTML = item.name; //创建标注对象var winHtml = "名称:" + item.name + "<br/>地址:" + item.address;let lnglat = new T.LngLat(item.lonlat.split(",")[0], item.lonlat.split(",")[1]);var marker = new T.Marker(lnglat);//地图上添加标注点tianditumap.addOverLay(marker);//注册标注点的点击事件var markerInfoWin = new T.InfoWindow(winHtml, { autoPan: true });marker.addEventListener("click", function () {marker.openInfoWindow(markerInfoWin);});buttont1.onclick = function () {let markerInfoWin = new T.InfoWindow(winHtml, { autoPan: true });marker.openInfoWindow(markerInfoWin);}divMarker.appendChild(buttont1);zoomArr.push(lnglat);});//显示地图的最佳级别tianditumap.setViewport(zoomArr);document.getElementsByClassName("search")[0].appendChild(divMarker);}
}// 设置坐标输入框数据
function setLocationInputVal(location) {$('#input_long_id').val(location.getLng());$('#input_lat_id').val(location.getLat());
}