微信小程序之地图组件使用。

2,862 views

WXML代码。

<map id=”map4select”
longitude=”{{longitude}}”latitude=”{{latitude}}”
markers=”{{markers}}”
scale=”20″
style=”width:{{map_width}}px;height:{{map_height}}px”
bindregionchange=”regionchange”
controls=”{{controls}}”>
</map>

app.js代码。

App({
onLaunch: function () {
//调用API从本地缓存中获取数据
var logs = wx.getStorageSync(‘logs’) || []
logs.unshift(Date.now())
wx.setStorageSync(‘logs’, logs)
}
, getUserInfo: function (cb) {
var that = this
if (this.globalData.userInfo) {
typeof cb == “function” && cb(this.globalData.userInfo)
} else {
//调用登录接口
wx.login({
success: function () {
wx.getUserInfo({
success: function (res) {
that.globalData.userInfo = res.userInfo
typeof cb == “function” && cb(that.globalData.userInfo)
}
})
}
})
}
}
//get locationInfo
, getLocationInfo: function (cb) {
var that = this;
if (this.globalData.locationInfo) {
cb(this.globalData.locationInfo)
} else {
wx.getLocation({
type: ‘gcj02’, // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
success: function (res) {
that.globalData.locationInfo = res;
cb(that.globalData.locationInfo)
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
}
}
, globalData: {
userInfo: null
, locationInfo: null
}
})

JS代码。

//index.js
//获取应用实例
const app = getApp()
Page({
data: {
motto: ‘欢迎光临沙子第一个微信小程序’,
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse(‘button.open-type.getUserInfo’),
map_width: 380
, map_height: 380
},
//事件处理函数
bindViewTap: function() {
wx.navigateTo({
url: ‘../logs/logs’
})
},
onLoad: function () {
var that = this;
// 获取定位,并把位置标示出来
app.getLocationInfo(function (locationInfo) {
console.log(‘map’, locationInfo);
that.setData({
longitude: locationInfo.longitude
, latitude: locationInfo.latitude
, markers: [
{
id: 0
, iconPath: “/pages/images/ic_position.png”
, longitude: locationInfo.longitude
, latitude: locationInfo.latitude
, width: 30
, height: 30
}
]
})
})
//set the width and height
// 动态设置map的宽和高
wx.getSystemInfo({
success: function (res) {
console.log(‘getSystemInfo’);
console.log(res.windowWidth);
that.setData({
map_width: res.windowWidth
, map_height: res.windowWidth
, controls: [{
id: 1,
iconPath: ‘/pages/images/ic_location.png’,
position: {
left: res.windowWidth / 2 – 8,
top: res.windowWidth / 2 – 16,
width: 30,
height: 30
},
clickable:false
}]
})
}
})
}
//获取中间点的经纬度,并mark出来
, getLngLat: function () {
var that = this;
this.mapCtx = wx.createMapContext(“map4select”);
this.mapCtx.getCenterLocation({
success: function (res) {
that.setData({
longitude: res.longitude
, latitude: res.latitude
, markers: [
{
id: 0
, iconPath: “/pages/images/ic_position.png”
, longitude: res.longitude
, latitude: res.latitude
, width: 30
, height: 30
}
]
})
}
})
}
, regionchange(e) {
// 地图发生变化的时候,获取中间点,也就是用户选择的位置
if (e.type == ‘end’) {
this.getLngLat()
}
}
, markertap(e) {
console.log(e)
}
})

 

 

 

如果您觉得这篇文章对您有帮助,欢迎继续关注本站!!!我要赞助本站>>>

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注