天地图开发者平台没有如高德,百度地图平台那样提供微信小程序JS API,那么我们应该如何把天地图引入微信小程序地图开发项目呢?
这里提供两种思路来解决微信小程序中应用天地图问题。
目录
在微信小程序中有request请求和map原生组件,并结合天地图Web服务API,我们现在就要利用它们来做事情。
第一步:我们来写两个天地图request专用请求。
在app.js文件globalData对象中保存两个天地图相关参数。
tmapWebUrl:'https://api.tianditu.gov.cn/',//天地图weburl
tkey:'你自己审请的TK',//天地图key
我们在utils文件夹中新建tmapApiRequest.js文件,并保存它们。
// 天地图webapi 接收返回JSON
const requestTMapApi = (obj, resolve, reject) => {
wx.request({
url: app.globalData.tmapWebUrl+obj[0],
method: 'GET',
data: Object.assign({},obj[1],{tk:app.globalData.tkey}),
header: {
'content-type': 'application/json' // 默认值
},
complete(res) {
if (res.statusCode == 200 && (res.data.status == "0" || res.data.status.infocode == 1000 )) {
return resolve(res.data)
}else return reject(res)
}
})
}
// 天地图webapi 接收返回XML
const requestTMapXML = (obj, resolve, reject) => {
wx.request({
url: app.globalData.tmapWebUrl+obj[0],
method: 'GET',
data: Object.assign({},obj[1],{tk:app.globalData.tkey}),
header: {
'content-type': 'application/json' // 默认值
},
complete(res) {
if (res.statusCode == 200) {
return resolve(res.data)
}else return reject(res)
}
})
}
第二步:在需要用到地图功能的项目页面中(如:map.wxml),准备微信小程序Map原生组件。
<map id="map" longitude="{{longitude}}" bindregionchange="regionchange" latitude="{{latitude}}" scale="14" markers="{{markers}}" bindmarkertap="makertap" polyline="{{polylines}}"></map>
第三步:在需要用到地图功能的项目页面中(如:map.js),调用天地图Web服务API获取我们想要的地图数据。
如:地名搜索V2.0
- 1.1 行政区划区域搜索服务
- 1.2 视野内搜索服务
- 1.3 周边搜索服务
- 1.4 多边形搜索服务
- 1.5 数据分类搜索服务
- 1.6 普通搜索服务
- 1.7 统计搜索服务
- 2.1 返回信息码
const app = getApp();
const tmapApiRequest= require("../../utils/tmapApiRequest");
tmapApiRequest.requestTMapApi(["v2/search",{postStr:{'keyWord':'北京',level:12,queryType:1,count:10,show:2,mapBound:"-180,-90,180,90"},type:'geocode'}],(data)=>{
if(data.pois && data.pois.length != 0){
data.pois.forEach((n,m)=>{
n.location = gcoord.transform(n.lonlat.split(","),gcoord.WGS84,gcoord.GCJ02).join(",")
})
this.setData({
tips: data.pois
});
}
},()=>{common.showToast("定位失败!")})
这里请注意:天地图坐标系是WGS84,微信小程序Map组件坐标系是GCJ02,它们是不同坐标系,所以需要进行坐标系转换操作,这里采用Gcoord.js插件来解决坐标系之间的转换关系。
如:逆地理编码查询
wx.getLocation({
type: 'wgs84',
success(res){
tmapApiRequest.requestTMapApi(["geocoder",{postStr:{'lon':res.longitude,lat:res.latitude,ver:1},type:'geocode'}],function(data){
that.setData({
"city":data.result.addressComponent.city,
"province":data.result.addressComponent.province,
"address":data.result.addressComponent.address
})
},function(){common.showToast("定位失败!")})
}
})
这是用微信小程序web-view组件来嵌入外部H5页面的能力来实现天地图功能。
<web-view url='你的H5地址?参数' bindmessage='getMessage'></web-view>
外部H5页面中完全引入天地图网页JS API来实现(JavaScript API 4.0)。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="keywords" content="天地图"/>
<title>天地图-地图API</title>
<script type="text/javascript" src="http://api.tianditu.gov.cn/api?v=4.0&tk=您的密钥"></script>
<style type="text/css">body,html{width:100%;height:100%;margin:0;font-family:"Microsoft YaHei"}#mapDiv{width:100%;height:400px}input,b,p{margin-left:5px;font-size:14px}</style>
<script>
var map;
var zoom = 12;
function onLoad() {
map = new T.Map('mapDiv', {
projection: 'EPSG:4326'
});
map.centerAndZoom(new T.LngLat(116.40769, 39.89945), zoom);
var DrivingRoute = new T.DrivingRoute(map)
DrivingRoute.search(new T.LngLat(116.40769, 39.89945),new T.LngLat(117.40769, 39.89945))
DrivingRoute.setSearchCompleteCallback((res)=>{
console.log(res)
console.log(res.getPlan(0).getPath())
})
}
</script>
</head>
<body onLoad="onLoad()">
<div id="mapDiv"></div>
</body>
</html>
微信小程序向H5页面通信:在web-view组件属性src链接?带参数,在H5页面中通过window.location.href或window.location.search获取参数值。
H5页面向微信小程序通信:在H5页面中引入
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script>
wx.miniProgram.postMessage({ data: 'foo' })
wx.miniProgram.navigateBack()
</script>
微信小程序中通过bindmessage方法接收H5页面传递过来的数据。