uniapp 利用map標簽 開發(fā)地圖定位和搜索關鍵字查詢功能

話不多說進入正題

簡單實用地圖

<template>
    <view class="content">
        <view >
            <view class="page-section page-section-gap">
              <map
                id="myMap"
                style="width: 100%; height: 280px;"
                :latitude="latitude"
                :longitude="longitude"
                :markers="markers"
                show-location
              ></map>
            </view>
        </view>
    </view>
</template>
<script>
    export default {
        onLoad() {
        },
        //相關配置參數(shù)
        data() {
        
          return {
              // 初始化的中心位置
                latitude: 23.099994,
                longitude: 113.324520,
                // 標記點
                markers: [{
                            id: 1,
                            latitude: 23.099994,
                            longitude: 113.324520,
                            name: 'T.I.T 創(chuàng)意園'
                        }],
          }
        
        },
        methods:{
        }
    }
</script>

<style>
    .page-section-gap{
      box-sizing: border-box;
      padding: 0 30rpx;
    }
    
    .page-body-button {
      margin-bottom: 30rpx;
    }
</style>

效果!


在這里插入圖片描述

想要地圖初始化的時候位置顯示為當前定位

<template>
    <view class="content">
        <view >
            <view class="page-section page-section-gap">
              <map
                id="myMap"
                style="width: 100%; height: 280px;"
                :latitude="latitude"
                :longitude="longitude"
                :markers="markers"
                show-location
              ></map>
            </view>
        </view>
    </view>
</template>

<script>
    var self ,mapCtx
    export default {
        onLoad() {
            self = this
            // 獲取當前map
            mapCtx =  wx.createMapContext('myMap')
            self.getAuthorizeInfo()
        },
        //相關配置參數(shù)
        data() {
        
          return {
              // 初始化的中心位置
                latitude: 23.099994,
                longitude: 113.324520,
                // 標記點
                markers: [{
                            id: 1,
                            latitude: 23.099994,
                            longitude: 113.324520,
                            name: 'T.I.T 創(chuàng)意園'
                        }],
          }
        
        },
        
        methods:{
            // 位置授權
             getAuthorizeInfo(){
                          uni.authorize({
                              scope: 'scope.userLocation',
                              success() { // 允許授權
                                  self.getLocationInfo();
                              },
                              fail(){    // 拒絕授權
                                  self.openConfirm();
                                  console.log("你拒絕了授權,無法獲得周邊信息")
                              }
                          })
                      },
                      // 獲取地理位置
            getLocationInfo(){  
                          uni.getLocation({
                              type: 'wgs84',
                              success (res) {
                                  console.log(res,"當前位置");
                                  // 移動到當前位置
                                 self.toLocation(res)
                                 self.latitude = res.latitude;
                                 self.longitude = res.longitude;
                              }
                          });
                      },
                      // 再次獲取授權
                      // 當用戶第一次拒絕后再次請求授權
            openConfirm(){
                          uni.showModal({
                              title: '請求授權當前位置',
                              content: '需要獲取您的地理位置,請確認授權',
                              success: (res)=> {
                                  if (res.confirm) {
                                      uni.openSetting();// 打開地圖權限設置
                                  } else if (res.cancel) {
                                      uni.showToast({
                                          title: '你拒絕了授權,無法獲得周邊信息',
                                          icon: 'none',
                                          duration: 1000
                                      })
                                  }
                              }
                          });
             },
             toLocation:function(obj){
                 // 改變地圖中心位置
                mapCtx.moveToLocation(obj)
                // 移動標記點并添加動畫效果
                mapCtx.translateMarker({
                  markerId: 1,
                  autoRotate: true,
                  duration: 100,
                  destination: {
                    latitude:obj.latitude,
                    longitude:obj.longitude,
                  },
                  animationEnd() {
                    console.log('animation end')
                  }
                })
             },
        
        }
    }
</script>

<style>
    .page-section-gap{
      box-sizing: border-box;
      padding: 0 30rpx;
    }
    
    .page-body-button {
      margin-bottom: 30rpx;
    }
</style>

效果


在這里插入圖片描述

(ps:注意獲取定位要設置權限 開啟位置接口配置)


在這里插入圖片描述

在進一步實現(xiàn)點擊地圖上的 poi點事位置標記點移動到該點
利用到 map的 bindpoitap事件 點擊地圖poi點時觸發(fā),(ps:此事件需要在真機調試下查看效果)
<template>
    <view class="content">
        <view >
            <view class="page-section page-section-gap">
              <map
                id="myMap"
                style="width: 100%; height: 280px;"
                :latitude="latitude"
                :longitude="longitude"
                :markers="markers"
                 @poitap = "poitap"
                show-location
              ></map>
            </view>
        </view>
    </view>
</template>

<script>
    var self ,mapCtx
    export default {
        onLoad() {
            self = this
            // 獲取當前map
            mapCtx =  wx.createMapContext('myMap')
            self.getAuthorizeInfo()
        },
        //相關配置參數(shù)
        data() {
        
          return {
              // 初始化的中心位置
                latitude: 23.099994,
                longitude: 113.324520,
                // 標記點
                markers: [{
                            id: 1,
                            latitude: 23.099994,
                            longitude: 113.324520,
                            name: 'T.I.T 創(chuàng)意園'
                        }],
          }
        
        },
        
        methods:{
            // 位置授權
             getAuthorizeInfo(){
                          uni.authorize({
                              scope: 'scope.userLocation',
                              success() { // 允許授權
                                  self.getLocationInfo();
                              },
                              fail(){    // 拒絕授權
                                  self.openConfirm();
                                  console.log("你拒絕了授權,無法獲得周邊信息")
                              }
                          })
                      },
                      // 獲取地理位置
            getLocationInfo(){  
                          uni.getLocation({
                              type: 'wgs84',
                              success (res) {
                                  console.log(res,"當前位置");
                                  // 移動到當前位置
                                 self.toLocation(res)
                                 self.latitude = res.latitude;
                                 self.longitude = res.longitude;
                              }
                          });
                      },
                      // 再次獲取授權
                      // 當用戶第一次拒絕后再次請求授權
            openConfirm(){
                          uni.showModal({
                              title: '請求授權當前位置',
                              content: '需要獲取您的地理位置,請確認授權',
                              success: (res)=> {
                                  if (res.confirm) {
                                      uni.openSetting();// 打開地圖權限設置
                                  } else if (res.cancel) {
                                      uni.showToast({
                                          title: '你拒絕了授權,無法獲得周邊信息',
                                          icon: 'none',
                                          duration: 1000
                                      })
                                  }
                              }
                          });
             },
             toLocation:function(obj){
                 // 改變地圖中心位置
                mapCtx.moveToLocation(obj)
                // 移動標記點并添加動畫效果
                mapCtx.translateMarker({
                  markerId: 1,
                  autoRotate: true,
                  duration: 100,
                  destination: {
                    latitude:obj.latitude,
                    longitude:obj.longitude,
                  },
                  animationEnd() {
                    console.log('animation end')
                  }
                })
             },
             // 
            poitap: function(e){
                console.log(e,"poitap")
                var obj = e.detail
                self.toLocation(obj)
            },
        
        }
    }
</script>

<style>
    .page-section-gap{
      box-sizing: border-box;
      padding: 0 30rpx;
    }
    
    .page-body-button {
      margin-bottom: 30rpx;
    }
</style>

實現(xiàn)搜索功能 此功能需要用到 騰訊地圖 提供的 api(這個功能很多 也比較好用 在這里就不詳細列舉了 管興趣的可以看一下 騰訊地圖
1,申請開發(fā)者密鑰(key):申請秘鑰
2,開通webserviceAPI服務:控制臺 ->key管理 -> 設置(使用該功能的key)-> 勾選webserviceAPI -> 保存
(小程序SDK需要用到webserviceAPI的部分服務,所以使用該功能的KEY需要具備相應的權限)

在這里插入圖片描述

3,下載微信小程序JavaScriptSDK,微信小程序JavaScriptSDK v1.2
導入SDK
下載后解壓,將里面的 qqmap-wx-jssdk.js 文件拷貝到項目里面。然后在需要的頁面導入。

var QQMapWX = require('../../common/qqmap/qqmap-wx-jssdk.min.js');

引用方法

const QQMapWX = new qqmapsdk({
    key: '在騰訊位置服務申請的key'
});

我這里只用了 關鍵詞搜索的 方法 search 當然方法還有很對看自己的具體需求(微信小程序JavaScript SDK 方法介紹)
下面上完整代碼

<template>
    <view class="content">
        <view class="top">
            <input type="text" placeholder="請輸入魚塘地址" :value="searchKey" @input="search"/>
            <scroll-view scroll-y="true" class="option" v-show="IsOption">
                <view class='column_item' v-for='(item,index) in data' :key='index' @click="tapOption(item)" >{{item.title}}</view>
            </scroll-view>
        </view>
        <view >
            <view class="page-section page-section-gap">
              <map
                id="myMap"
                style="width: 100%; height: 280px;"
                :latitude="latitude"
                :longitude="longitude"
                :markers="markers"
                :covers="covers"
                 @poitap = "poitap"
                show-location
              ></map>
            </view>
        </view>
    </view>
</template>

<script>
    // 引入SDK核心類
    var QQMapWX = require('../../common/qqmap/qqmap-wx-jssdk.min.js');
    var qqmapsdk;
    var self;
    export default {
        data() {
            return {
                data:[],
                IsOption:false,
                searchKey:"",
                
                latitude: '',
                longitude:'',
                    markers: [{
                      id: 1,
                      latitude: 23.099994,
                      longitude: 113.324520,
                      name: 'T.I.T 創(chuàng)意園'
                    }],
                    covers: [{
                      latitude: 23.099994,
                      longitude: 113.344520,
                      iconPath: '/image/location.png'
                    }, {
                      latitude: 23.099994,
                      longitude: 113.304520,
                      iconPath: '/image/location.png'
                    }],
            }
        },
        onLoad() {
            self = this
            self.mapCtx = wx.createMapContext('myMap')
            self.getAuthorizeInfo()
                 // 實例化API核心類
                 qqmapsdk = new QQMapWX({
                            key: 'WS3BZ-QUFEO-TNEW5-S2RZ6-QVQI6-PJFWY'
                        });
                    
        },
        methods: {
                bindChange:function(e){
                    console.log(e)
                },
                // 搜索框
                  search:  function(e){
                    console.log(e)
                    self.searchKey = e.detail.value
                    var location = self.latitude+","+ self.longitude
                     self.mapSearch(self.searchKey,location).then(res => {
                                self.data = res.data
                                if(self.searchKey && self.data.length){
                                    self.IsOption = true
                                }else{
                                    self.IsOption = false
                                }
                                
                            },error => {
                                // self.$api.msg('請求失敗')
                                // console.log(error,"aaaaaaaaaaa");
                        })
                    
                },
                tapOption:function(item){
                    self.searchKey = item.title
                    self.IsOption = false
                    self.data = []
                    var obj = {}
                    obj.latitude = item.location.lat;
                    obj.longitude = item.location.lng;
                    // console.log(item,"danji",obj)
                    self.toLocation(obj)
                },
                toLocation:function(obj){
                    self.mapCtx.moveToLocation(obj)
                    self.mapCtx.translateMarker({
                      markerId: 1,
                      autoRotate: true,
                      duration: 100,
                      destination: {
                        latitude:obj.latitude,
                        longitude:obj.longitude,
                      },
                      animationEnd() {
                        console.log('animation end')
                      }
                    })
                },
                // 
                 mapSearch:function(keyword,location){
                console.log(keyword,location,"keyword,location")
                    let promise = new Promise(function(resolve, reject) {
                        // 調用接口
                              qqmapsdk.search({
                                    keyword: keyword,//搜索關鍵詞
                                    location:location ,  //設置周邊搜索中心點
                                  success: function (res) {
                                     resolve(res)
                                  },
                                  fail: function (res) {
                                     reject(res)
                                  }
                          });
                    })
                    return promise
                      
                },
                // 位置授權
                 getAuthorizeInfo(){
                              uni.authorize({
                                  scope: 'scope.userLocation',
                                  success() { // 允許授權
                                      self.getLocationInfo();
                                  },
                                  fail(){    // 拒絕授權
                                      self.openConfirm();
                                      console.log("你拒絕了授權,無法獲得周邊信息")
                                  }
                              })
                          },
                          // 獲取地理位置
                getLocationInfo(){  
                              uni.getLocation({
                                  type: 'wgs84',
                                  success (res) {
                                      console.log(res,"當前位置");
                                     self.toLocation(res)
                                     self.latitude = res.latitude;
                                     self.longitude = res.longitude;
                                            // uni.openLocation({
                                            //     latitude: latitude,
                                            //     longitude: longitude,
                                            //     success: function () {
                                            //         console.log('success');
                                            //     }
                                            // })
                                  }
                              });
                          },
                  
                          // 再次獲取授權
                          // 當用戶第一次拒絕后再次請求授權
                openConfirm(){
                              uni.showModal({
                                  title: '請求授權當前位置',
                                  content: '需要獲取您的地理位置,請確認授權',
                                  success: (res)=> {
                                      if (res.confirm) {
                                          uni.openSetting();// 打開地圖權限設置
                                      } else if (res.cancel) {
                                          uni.showToast({
                                              title: '你拒絕了授權,無法獲得周邊信息',
                                              icon: 'none',
                                              duration: 1000
                                          })
                                      }
                                  }
                              });
                 },
                 
                 
                 
                 
                 poitap: function(e){
                    console.log(e,"poitap")
                    var obj = e.detail
                    self.searchKey = obj.name
                    // this.$api.msg(e)
                    self.toLocation(obj)
                 },
                 getCenterLocation: function () {
                    this.mapCtx.getCenterLocation({
                      success: function(res){
                        console.log(res.longitude)
                        console.log(res.latitude)
                      }
                    })
                  },
                // 下一步
                Next:function(){
                    uni.navigateTo({
                      url: './addFishpond2'
                    })  
                },
                // 取消刪除
                Cancel:function(){
                    
                },
        }
    }
</script>

<style>
    .content {
        background-color: #F1F1F1;
        overflow: hidden;
        min-height: 100vh;
        color: #646464;
        font-size:40rpx ;
    }
    .top>input{
        height: 88rpx;
        width: 524rpx;
        margin: 40rpx auto 0;
        padding:0 40rpx;
        border: solid 2rpx #BEBEBE;
    }
    .option{
        max-height: 300rpx;
        width: 100%;
    
        line-height: 60rpx;
        position: fixed;
        top: 128rpx;
        z-index: 99999;
    }
    .column_item{
        padding:0 40rpx;
        height: 60rpx;
        width: 524rpx;
        overflow: hidden;
        margin:0rpx auto;
        background-color: #fff;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .column_item:active{
        background-color: #8F8F94;
    }
    
    .page-section-gap{
      box-sizing: border-box;
      /* padding: 0 30rpx; */
      margin: 30rpx auto;
      width: 600rpx;
    }
    
</style>

效果


在這里插入圖片描述

實現(xiàn)了簡答的搜索 感覺搜索方面不太智能 有好的建議的地方大家可以交流一下

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容