leaflet + 天地图 实现地图搜索

1. 去天地图的官网 国家地理信息公共服务平台,注册登陆成为开发者

2. 申请一个密钥key,因为无论是 引入地图 或者 使用地名搜索等API 时,调用官网的url都要传参:&tk=你的密钥

 

 

在官网按照提示就可以申请密钥:

 

 

3. 有leaflet.ChineseTmsProviders这个插件,天地图、高德地图、智图地图、谷歌地图,这四种地图直接就能够加载进来。

4. 从网上下载第3条的插件,放到项目中 src/assets/map目录下,在需要地图的文件中引入即可:

- 先在html中添加一个存放地图的div:

 

<div class="map-box">
   <div id="map-container" class="map-container" />
</div>

 

- 引入插件:

 

import '@/assets/map/leaflet.ChineseTmsProviders'

 

 - 引入 leaflet 一系列:

import * as L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import 'proj4leaflet'
import 'leaflet.chinatmsproviders'

- 初始化地图方法:

 

initMap() {
this.map = L.map('map-container', { // leaflet 初始化地图
  minZoom: 4,
  maxZoom: 16,
  attributionControl: false,
  center: this.mapOptions.origin, // 地图初始化时的中心点位置
  zoom: this.mapOptions.initZoom, // 地图初始化时的缩放等级
  zoomControl: false // 默认情况下,是否将 zoom 缩放控件添加到地图中。
})
    this.tileLayer = [
      L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', { // 加载天地图的影像图(卫星图)
        maxZoom: 16,
        minZoom: 4
      })
    ]
    this.tileLayer.map(layer => {
      this.map.addLayer(layer)
    })
    this.map.on('moveend', this.mapMoveEnd.bind(this)) // 移动地图的回调方法
this.map.on('zoomend', this.mapZoomend.bind(this)) // 放大缩小地图的回调方法
}

 

 

leaflet.ChineseTmsProviders 插件中有四种地图不同类型的url:

 

 5. 在页面中添加一个搜索框,点击搜索按钮调用天地图的搜索API请求,这里由于涉及到跨域,使用到了 vue-jsonp 插件:

 

searchMap() {
  this.$jsonp(url, {
        keyword:  this.searchName,
        key: 你的密钥 ,
        output: 'jsonp'
     }, 20000).then((result) => {
        // 在这里拿到搜索的结果,用leaflet渲染出来
  }.catch(() => {
   this.$message.warning('暂未搜索到相关地址,请重新输入!')
  })
}

 

result 的格式可以在天地图的官网文档里查到:

       http://lbs.tianditu.gov.cn/server/search.html

 

 

 

 

 

 

 

posted @ 2022-05-16 10:07  我就尝一口  阅读(2943)  评论(0编辑  收藏  举报