高德 通过 起 经 止 经纬度 获取路线经纬度,(可搜索位置,新增经过点)

高德 通过 起 经 止 经纬度 获取路线经纬度


前言

之前工作的公司与道路相关,后端同事经常需要采集路线坐标,网上又没有找到合适的工具,因此请我帮忙写了一个可以根据起始点,经过点,终点,经纬度获取整条路线经纬度数组的一个功能,下面就演示获取经纬度的代码以及DEMO。


一、经纬度获取代码

代码使用Vue + elementUI 布局,Amap.js 绘制地图、路线,以及获取路线经纬度。

html

<script src="https://webapi.amap.com/maps?v=2.0Beta&key=523c9fc07c690089f319101a72c2c13e&plugin=AMap.DragRoute,AMap.PlaceSearch"></script>

<div id="app">
  <div class="coordinate-acquisition-wraper" v-loading="isLoading">
    <div class="filter-wrap" :class="{expand: isExpand}">
      <i class="el-icon" :class="isExpand ? 'el-icon-arrow-left':'el-icon-arrow-right'" @click="isExpand = !isExpand"></i>
      <el-form class="custom-scrollbar" :model="formData" ref="form" size="small" label-width="100">
        <el-form-item label="选择定位位置">
          <el-input type="text" v-model="formData.keyword" @keyup.native.enter="posSearchHandle" placeholder="请输入位置" clearable="clearable" @clear="clearHandle"></el-input>
          <el-button icon="el-icon-search" type="primary" @click="posSearchHandle"></el-button>
        </el-form-item>
        <el-form-item :label="`经纬度${i+1}`" v-for="(item, i) in formData.coordinates" :key="i" :rules="rules.coordinate" :prop="`coordinates.${i}`">
          <el-input type="text" v-model="formData.coordinates[i]" icon="md-navigate" placeholder="请输入经纬度" :class="{active: active === i}"><i class="el-input__icon el-icon-s-promotion" slot="suffix" @click="activeHandle(i)"></i></el-input>
          <el-button icon="el-icon-close" type="danger" v-if="formData.coordinates.length &gt; 2" @click="removePointHandle(i)"></el-button>
          <el-button icon="el-icon-plus" type="primary" v-if="formData.coordinates.length &lt; 15" @click="formData.coordinates.splice(i + 1, 0, ''); active = i+1"></el-button>
        </el-form-item>
        <el-button type="primary" @click="renderLine">查询路线</el-button>
        <el-form-item label="经纬度段坐标">
          <el-input type="textarea" v-model="sectionStr" readonly="readonly" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="返回路线坐标">
          <el-input type="textarea" v-model="formData.result" readonly="readonly" :rows="3"></el-input>
        </el-form-item>
        <p>可在控制台查看完整路线对象</p>
      </el-form>
    </div>
    <div class="style-change">
      <span>地图主题:</span>
      <el-select v-model="formData.style" @change="setMapStyle">
        <el-option v-for="(item, i) in styleOptions" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </div>
    <div class="search-result custom-scrollbar" id="search-result" ref="searchResult"></div>
    <div class="coordinate-acquisition" id="coordinate-acquisition" :class="{active: active !== -1}"></div>
  </div>
</div>

JavaScript

new Vue({
  el: '#app',
  name: 'CoordinateAcquisition',
  data() {
    return {
      isExpand: true,
      isLoading: false,
      formData: {
        keyword: '',
        coordinates: ['116.303843,39.983412', '116.407012,39.992093'],
        start: '116.303843,39.983412',
        end: '116.407012,39.992093',
        result: '',
        style: 'light',
      },
      styleOptions: [
        {
          label: '幻影黑',
          value: 'dark',
        },
        {
          label: '月光银',
          value: 'light',
        },
        {
          label: '远山黛',
          value: 'whitesmoke',
        },
        {
          label: '草色青',
          value: 'fresh',
        },
        {
          label: '雅士灰',
          value: 'grey',
        },
        {
          label: '涂鸦',
          value: 'graffiti',
        },
        {
          label: '马卡龙',
          value: 'macaron',
        },
        {
          label: '靛青蓝',
          value: 'blue',
        },
        {
          label: '极夜蓝',
          value: 'darkblue',
        },
        {
          label: '酱籽',
          value: 'wine',
        },
      ],
      aMap: null,
      route: null,
      placeSearch: null,
      active: -1,
      rules: {
        coordinate: [
          {
            required: true,
            message: '请输入经纬度',
          },
        ],
      },
      timer: null,
    }
  },
  computed: {
    sectionStr() {
      return JSON.stringify(this.formData.coordinates.map((item) => item.split(',').map((v) => +v)))
    },
  },
  mounted() {
    setTimeout(() => {
        this.initMap()
    }, 1000)
  },
  methods: {
    clearHandle() {
      this.$refs.searchResult.innerHTML = ''
    },
    posSearchHandle() {
      // 关键字查询
      this.formData.keyword && this.placeSearch.search(this.formData.keyword)
    },
    setMapStyle() {
      let styleName = 'amap://styles/' + this.formData.style
      this.aMap.setMapStyle(styleName)

      // this.aMap.setZoom(13)
    },
    activeHandle(i) {
      if (this.active === i) {
        this.active = -1
      } else {
        this.active = i
      }
    },
    removePointHandle(i) {
      // clearTimeout(this.timer)
      this.formData.coordinates.splice(i, 1)

      // this.timer = setTimeout(() => {
      //   this.renderLine()
      // }, 300)
    },
    initMap() {
    //   AMapLoader.load({
    //     key: '523c9fc07c690089f319101a72c2c13e',
    //     version: '2.0Beta',
    //     // 'key': '	523c9fc07c690089f319101a72c2c13e', // 申请好的Web端开发者Key,首次调用 load 时必填
    //     // 'version': '2.0Beta' // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    //     plugins: ['AMap.DragRoute', 'AMap.PlaceSearch'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
    //     // 'AMapUI': { // 是否加载 AMapUI,缺省不加载
    //     //   'version': '1.1', // AMapUI 缺省 1.1
    //     //   'plugins': [] // 需要加载的 AMapUI ui插件
    //     // },
    //     // 'Loca': { // 是否加载 Loca, 缺省不加载
    //     //   'version': '1.3.2' // Loca 版本,缺省 1.3.2
    //     // }
    //   })
    //     .then((AMap) => {
          this.aMap = new window.AMap.Map('coordinate-acquisition', {
            zoom: 5,
            mapStyle: `amap://styles/${this.formData.style}`,
          })

          // 构造地点查询类
          this.placeSearch = new window.AMap.PlaceSearch({
            pageSize: 5, // 单页显示结果条数
            pageIndex: 1, // 页码
            // city: '010', // 兴趣点城市
            // citylimit: true, // 是否强制限制在设置的城市内搜索
            map: this.aMap, // 展现结果的地图实例
            panel: 'search-result', // 结果列表将在此容器中进行展示。
            autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          })

          this.placeSearch.on('markerClick', () => {
            this.aMap.setZoom(15)
          })

          this.aMap.on('click', (e) => {
            if (this.active !== -1) {
              this.$set(this.formData.coordinates, this.active, `${e.lnglat.lng},${e.lnglat.lat}`)
              // this.$nextTick(() => {
              //   this.renderLine()
              // })
            }
          })
        // })
        // .catch((e) => {
        //   console.log(e)
        // })
    },
    renderLine() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.isLoading = true
          if (this.route) {
            this.route.destroy()
          }
          // path 是驾车导航的起、途径和终点,最多支持16个途经点
          let path = this.formData.coordinates.map((v) => v.split(','))
          // let path = []

          // path.push(this.formData.start.split(','))
          // path.push([116.321354, 39.896436])
          // path.push(this.formData.end.split(','))

          this.route = new window.AMap.DragRoute(this.aMap, path, window.AMap.DrivingPolicy.LEAST_DISTANCE)
          // 查询导航路径并开启拖拽导航
          this.route.search()

          this.route.on('complete', ({ data, target }) => {
            this.isLoading = false
            this.active = -1
            this.formData.coordinates = target._path.map((v) => `${v.lng},${v.lat}`)

            let arr = this.route.getRoute()
            let posArr = arr.map((item) => [item.lat, item.lng])
            this.formData.result = JSON.stringify(posArr)

            // this.$Message.success('可在控制台查看完整路线对象')
            let css = 'font-size: 20px; font-weight: bold;font-family: 微软雅黑; color: #fff; text-shadow: 0 0 3px rgba(0, 0, 0, 1);'
            console.clear()
            console.log('%c行车路线对象  ↓', css)
            console.log(data)
            console.log('%c行车路线数组  ↓', css)
            console.log(arr)
            console.log('%c行车路线经纬度  ↓', css)
            console.log(posArr)
            console.log('%c行车路线经纬度JSON串  ↓', css)
            console.log(this.formData.result)
          })

          this.route.on('addway', ({ target }) => {
            this.active = -1
            this.formData.coordinates = target._path.map((v) => `${v.lng},${v.lat}`)
          })
        }
      })
    },
  },
})

CSS

#app,
body,
html {
  height: 100%;
  padding: 0;
  margin: 0;
}
.coordinate-acquisition-wraper {
  height: 100%;
  position: relative;
  font-family: "微软雅黑";
}
.coordinate-acquisition-wraper .style-change span {
  font-size: 14px;
  font-weight: bold;
  font-family: "微软雅黑";
}
.coordinate-acquisition-wraper .filter-wrap {
  border-right: 1px solid #ddd;
  position: absolute;
  z-index: 7;
  height: 100%;
  background-color: #fff;
  transition: left 0.3s;
  padding: 10px 0 10px 10px;
  width: 397px;
  box-sizing: border-box;
  left: -397px;
}
.coordinate-acquisition-wraper .filter-wrap.expand {
  left: 0;
}
.coordinate-acquisition-wraper .filter-wrap > .el-icon {
  cursor: pointer;
  font-size: 18px;
  position: absolute;
  right: -17px;
  height: 60px;
  line-height: 60px;
  width: 16px;
  box-shadow: 1px 1px 2px rgba(0,0,0,0.1);
  top: calc(50% - 30px);
  background-color: #fff;
  border-radius: 0 5px 5px 0;
}
.coordinate-acquisition-wraper .el-form {
  height: 100%;
  overflow: auto;
}
.coordinate-acquisition-wraper .el-form p {
  color: #888;
  text-shadow: 0 0 1px #fff;
  padding-left: 100px;
}
.coordinate-acquisition-wraper .el-form > .el-button {
  display: block;
  margin-left: 212px;
  margin-bottom: 10px;
}
.coordinate-acquisition-wraper .el-form .el-form-item {
  margin-bottom: 20px;
  padding-right: 10px;
}
.coordinate-acquisition-wraper .el-form .el-form-item .el-input.active .el-icon-s-promotion {
  color: #409eff;
}
.coordinate-acquisition-wraper .el-form .el-form-item .el-icon-s-promotion {
  cursor: pointer;
}
.coordinate-acquisition-wraper .el-form .el-form-item .el-form-item-error-tip {
  position: static;
}
.coordinate-acquisition-wraper .el-form .el-form-item .el-form-item__content {
  display: flex;
}
.coordinate-acquisition-wraper .el-form .el-form-item .el-button {
  margin-left: 3px;
}
.coordinate-acquisition-wraper .coordinate-acquisition {
  height: 100%;
}
.coordinate-acquisition-wraper .coordinate-acquisition.active .amap-layer {
  cursor: crosshair !important;
}
.coordinate-acquisition-wraper .coordinate-acquisition .amap-copyright,
.coordinate-acquisition-wraper .coordinate-acquisition .amap-logo {
  display: none !important;
}
.coordinate-acquisition-wraper .style-change {
  position: absolute;
  z-index: 7;
  right: 10px;
  top: 10px;
}
.coordinate-acquisition-wraper .style-change .el-select {
  width: 120px;
}
.coordinate-acquisition-wraper .search-result {
  position: absolute;
  z-index: 7;
  top: 50px;
  right: 10px;
  max-height: calc(100% - 70px);
  overflow: auto;
}

二、效果图演示

演示功能效果图
功能描述
1.可以通过输入选择定位位置搜索需要查询的地方
2.选择 飞机图标变蓝后可以点击地图 自动插入点击处经纬度
3.可以新增 经过点 经纬度(通过+加号,或地图上路线点击拖拽)
4.官方自带主题可以切换
5.点击查询路线,会根据以上所填经纬度查询经过经过所有经纬度的路线斌返回经过经纬度路线数组

三、DEMO 演示地址

根据起 、经、止 经纬度查询路线经纬度 演示demo
在demo 内可在线编辑代码

总结

以上信息如有疏漏或错误欢迎指正,谢谢。

  • 13
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
### 回答1: JavaScript 高德地图 API 可以通过经纬度获取地理位置信息。该 API 使用了逆地理编码技术,可以将地理位置经纬度坐标转换成详细的地址描述信息。您可以使用 JavaScript 调用 API,传递经度和纬度参数,即可获取对应的定位信息。 在使用高德地图 API 的时候,需要先通过 JavaScript 加载地库,然后创建一个地容器,指定容器的宽度和高度,设置地的中心和缩放级别。然后,在 JavaScript 代码中调用逆地理编码方法,传递经度和纬度参数,该方法会返回一个地址描述对象,包含国家、省份、城市、区县、街道等详细描述信息。 除了通过 JavaScript 调用高德地图 API 进行地理位置获取,还可以使用其他的开发工具和平台进行位置定位,如百度地、谷歌地等。这些地 API 都提供了类似的功能,可以通过经纬度获取地址信息,并进行地理位置展示、导航等操作。 ### 回答2: JavaScript 高德地图 API 是一个基于 JavaScript 的地理信息可视化库,它可以帮助我们在 web 上创建交互式地应用程序,使用 API 获取和展示地理位置信息,也可以通过 API 提供的方法来对地进行交互。 我们可以使用经纬度获取地理位置信息,一般来说,我们需要使用地 API 提供的 geocoder 对象的 search 方法,将需要查询的经纬度作为参数传递过去。geocoder 对象是地理编码与逆地理编码服务的核心类,它把地理信息转换为经纬度坐标和反之。在 JavaScript 高德地图 API 中,我们可以通过以下代码来实现经纬度与地理位置之间的转换: ``` var geocoder, map = new AMap.Map("container"); //初始化地理编码器 geocoder = new AMap.Geocoder({ city: "010" //城市,默认:“全国” }); //调用搜索方法,获取地理位置信息 geocoder.search([116.480983, 39.989628], function(status, result) { //根据状态判断是否查询成功 if (status === 'complete' && result.info === 'OK') { //地理位置信息 var address = result.regeocode.formattedAddress; console.log(address); } else { console.log("查询失败!"); } }); ``` 在这个例子中,我们创建了一个 geocoder 对象,并传递了城市参数。然后,我们调用了 geocoder 的 search 方法,并向其中传递了一个包含需要查询的经纬度的数组。当查询成功时,我们可以通过 result 对象获取到地理位置信息,其中包含了详细地址、城市、省份等信息。从中,我们可以获取到我们需要的详细地址信息,来帮助我们完成相应的功能。 总之,JavaScript 高德地图 API 提供了非常方便的地理位置信息获取方式。我们可以通过 geocoder 对象的 search 方法来获取经纬度对应的地理位置信息,方便我们开发与地理位置相关的应用程序。 ### 回答3: JS高德地图API提供了通过经纬度获取地理位置的功能。下面是具体的步骤: 1.在使用该功能前,需要在高德地图开发者平台注册并申请相应的API Key。 2.在HTML页面中引入高德地图API的JavaScript文件,同时创建一个显示地的DOM元素。 3.利用JavaScript获取用户的经纬度信息。 4.将获取到的经纬度信息作为参数,调用API中的逆地理编码模块,获取经纬度所处的地理位置信息。 5.将获取到的位置信息通过JavaScript动态渲染到页面上。 具体代码实现如下: 先在HTML页面中引入高德地图API的JavaScript文件: ``` <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.7&key=YOUR_API_KEY"></script> ``` 其中,YOUR_API_KEY需要替换成你所申请的API Key。 创建一个用于显示地的DOM元素: ``` <div id="map" style="width: 100%; height: 500px;"></div> ``` 获取用户的经纬度信息: ``` navigator.geolocation.getCurrentPosition(function(position) { var longitude = position.coords.longitude; var latitude = position.coords.latitude; // TODO: 调用API获取地理位置信息 }); ``` 将经纬度信息作为参数,调用API的逆地理编码模块: ``` var geocoder = new AMap.Geocoder({ city: "", // 城市,默认:“全国” }); geocoder.getAddress([longitude, latitude], function(status, result) { if (status === 'complete' && result.regeocode) { var address = result.regeocode.formattedAddress; // TODO: 将位置信息渲染到页面上 } }); ``` 其中,geocoder.getAddress()方法会返回一个Result对象,里面包含了位置信息,例如formattedAddress、addressComponent等。 最后,将位置信息通过JavaScript动态渲染到页面上即可。 总之,JS高德地图API提供了通过经纬度获取地理位置信息的功能,使用起来相对简单方便。在使用该功能时,需要注意申请API Key并确保用户已经授权获取其地理位置信息。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值