1. 程式人生 > >小程式獲取地理位置(經緯度以及選擇附近位置)

小程式獲取地理位置(經緯度以及選擇附近位置)

html部分

<view>  
    <button bindtap="getLocal" wx:if="{{isLocal}}" bindtap="getLocal">獲取位置</button>
    <button open-type='openSetting' bindopensetting="handleSetting" wx:else>授權獲取</button>
    <viwe>經度:{{longitude}}</viwe>  
    <view>緯度:{{latitude}}</view>  
   
</view>

js部分


Page({

    data: {
        isLocal: true,
        longitude: '',
        latitude: ''
    },
    onLoad: function (options) {
       
    },
    getLocal(){
        let that = this;
        wx.getSetting({
            success: (res)=>{
                if (!res.authSetting['scope.userLocation']){
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success: (res)=>{
                            that.showLocal();
                            that.setData({
                                isLocal: true
                            })
                        },
                        fail: (err)=>{
                            that.setData({
                                isLocal: false
                            })
                        }
                    })
                }else{
                    that.showLocal();
                }
            }
        })
    },
    showLocal(){
        var that = this;
        wx.getLocation({
            type: 'wgs84',
            success: function (res) {
                let latitude = res.latitude
                let longitude = res.longitude
                that.setData({
                    latitude, 
                    longitude
                })
                //在手機中開啟微信的騰訊地圖並標記點
                wx.openLocation({
                    latitude: latitude,
                    longitude: longitude,
                    scale: 28
                })
            }
        })
        // wx.chooseLocation({
        //     success: function(res) {
        //         console.log(res)
        //     }
        // })
    },
    handleSetting(){
        var that = this;
        wx.getSetting({
            success: (res)=>{
                if (!res.authSetting['scope.userLocation']){
                    console.log(1)
                    wx.showModal({
                        title: '提示',
                        content: '不授權將無法獲得位置',
                        showCancel: false
                    })
                    that.setData({
                        isLocal: false
                    })
                }else{
                    wx.showModal({
                        title: '提示',
                        content: '位置授權成功',
                        showCancel: false
                    })
                    that.setData({
                        isLocal: true
                    })
                }
            }
        })
    }

})

注意選附近的位置是註釋的那一段 res 返回值

name 位置名稱
address 詳細地址
latitude 緯度,浮點數,範圍為-90~90,負數表示南緯。使用 gcj02 國測局座標系
longitude 經度,浮點數,範圍為-180~180,負數表示西經。使用 gcj02 國測局座標系