1. 程式人生 > >微信小程式---高德地圖API

微信小程式---高德地圖API

本文章介紹微信小程式呼叫高德地圖API的過程,使用高德定位功能做演示。

微信小程式目前支援百度地圖、高德地圖、騰訊地圖。用法可以說是基本完全一樣,本文章以高德為例,簡單說一下他們的區別,高德地圖精度應該是最準確的,畢竟本來就是做地圖出生的。百度地圖的精度目前較高德而言,還是要稍稍欠缺一點,但是他的附近商家那些要比高德好一點。而關於騰訊地圖,暫時來說還是隻能表示呵呵,希望越來越好吧。
1.既然本章是介紹微信小程式如何使用高德地圖API,那麼第一件事肯定是進入高德地圖開放平臺(https://lbs.amap.com/)。此處需要註冊,登入。
2.完成登陸後,進入控制檯,在左邊側邊欄裡點選 應用管理->我的應用-> 建立新應用,會生成一個key,這個key在後面將會用到。記住繫結服務選擇 微信小程式
3.登入微信開發者平臺,在伺服器域名設定裡將高德地圖的域名設定好
在這裡插入圖片描述


4.在你的專案中新建一個目錄libs,將amap-wx.js檔案放入此目錄裡(amap-wx.js下載地址:https://lbs.amap.com/api/wx/download,解壓出來會有兩個檔案,此處只需要一個),結果如下:
在這裡插入圖片描述
5.在libs目錄下建立配置檔案config.js,寫入第二步獲取的key,例如
在這裡插入圖片描述,高德api配置到這兒就結束了,以下是我呼叫高德實現定位的demo

JS部分:

var amapFile = require(’…/…/libs/amap-wx.js’); //引入高德js
var config = require(’…/…/libs/config.js’); //引用我們的配置檔案
Page({
data: {
markers: [],
latitude: ‘’,
longitude: ‘’,
textData: {}
},
onLoad: function () {
var that = this;
var key = config.Config.key;
var myAmapFun = new amapFile.AMapWX({ key: key });
myAmapFun.getRegeo({
iconPath: “…/…/img/marker.png”,
iconWidth: 22,
iconHeight: 32,
success: function (data) {
console.log(data);
var marker = [{
id: data[0].id,
latitude: data[0].latitude,
longitude: data[0].longitude,
iconPath: data[0].iconPath,
width: data[0].width,
height: data[0].height
}]
that.setData({
markers: marker
});
that.setData({
latitude: data[0].latitude
});
that.setData({
longitude: data[0].longitude
});
that.setData({
textData: {
name: data[0].name,
desc: data[0].desc
}
})
},
fail: function (info) {
// wx.showModal({title:info.errMsg})
}
})
}
})

WXML部分:

{{textData.name}} {{textData.desc}}

WXSS部分:

.map_container{
position: absolute;
top: 0;
bottom: 80px;
left: 0;
right: 0;
}
.map{
width: 100%;
height: 100%;
}
.map_text{
position: absolute;
left: 0;
right: 0;
bottom: 0px;
height: 80px;
background: #fff;
padding: 0 15px;
}
text{
margin: 5px 0;
display: block;
font-size:12px;
}
.h1{
margin: 15px 0;
font-size:15px;
}

此頁面大概長這樣:
在這裡插入圖片描述

PS:
高德地圖官方開發指南地址 https://lbs.amap.com/api/wx/guide/create-project/config-project
我的小程式demo地址 https://github.com/Yxiaogg/vioShop