高德地图的开发和常用 API 的使用

1.引入高德地图的 API 文件

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>

2.创建地图容器

在你想要展示地图的页面中,创建一个 div 容器,并制定 id 标识:

<div id="container" />

同时制定容器大小。

#container {width:300px; height: 180px; }  

3.创建地图,设置中心点和级别等配置

mapMethods = new AMap.Map('container', {
  center: [113.84513250000002, 32.885113878375115], // 默认中心点
  resizeEnable: true,
  zoom: 5,
  zooms: [3, 12], // 缩放范围, 最大19
  mapStyle: 'amap://styles/fresh', // 地图的主题,官方有提供
})

4.创建点标记

同地图一样,点标记可以在创建的时候设定位置等属性,如果设定了map属性的话,marker点将被立即添加到地图上:

var startMarker = new AMap.Marker({
  position: [116.480983, 39.989628],
  icon: getOriginIcon(),
  map: mapMethods, 
})
mapMethods.add([startMarker])

5.创建折线

var routeLine = new AMap.Polyline({
  path: path, // 折线的节点坐标数组
  borderWeight: 2,
  strokeWeight: 5,  // 线宽
  strokeColor: 'green',  // 线条颜色
})
routeLine.setMap(mapMethods) // 设置折线所在的地图。

更多详情:请看 高德地图 API 之 Polyline 类绘制折线

6.创建信息窗体

var infoWindow = new AMap.InfoWindow({ 
  content: `消息内容`,
  offset: new AMap.Pixel(16, -45),
})
var onMarkerClick = function (e) {
  infoWindow.open(mapMethods, e.target.getPosition()) // 打开信息窗体
  // e.target就是被点击的Marker
}
shipMarker.on('click', onMarkerClick)

6.地址转经纬度

使用 AMap.Geocoder 方法用于地址描述与坐标间的互相转换

高的开放平台:地理编码(地址转坐标)案例。

handleGeocoder 方法传入 address 参数,返回一个 Promise 对象。将解析成功的地址使用 resolve 方法返回经纬度,否则返回 解析失败。

handleGeocoder (address) {
  return new Promise((resolve, reject) => {
    AMap.plugin('AMap.Geocoder', function () {
      const geocoder = new AMap.Geocoder() // 地址解析对象
      geocoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          const position = result.geocodes[0].location
          resolve({
            lat: position.lat,
            lng: position.lng,
          })
        } else {
          reject('地址解析失败, 请刷新重试')
        }
      })
    })
  })
},

7.创建驾车路线

参考:高德地图驾车服务案例

AMap.plugin(['AMap.Driving'], function () {
  // 构造路线导航类
  var driving = new AMap.Driving()
  // 据起终点经纬度规划驾车导航路线
  driving.search(new AMap.LngLat(116.379028, 39.865042), new AMap.LngLat(116.427281, 39.903719), function (status, result) {
    // result即是对应的驾车导航信息,相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
    if (status === 'complete') {
      console.log('绘制驾车路线完成')
    } else {
      console.log('获取驾车数据失败:' + result)
    }
  })
})

new AMap.LngLat() :经纬度坐标,确定地图上的一个点

new AMap.Pixel():像素坐标,确定地图上的一个像素点。

mapMethods.setFitView([ startMarker, endMarker, routeLine ]):自动适配到合适视野范围。

无参数,默认包括所有覆盖物的情况;传入覆盖物数组,仅包括数组里的情况;

mapMethods.clearMap() :清除地图上所有添加的覆盖物

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值