react项目中使用高德地图
基本项目使用create-react-app创建项目,并引入typescript
1. 申请高德key
2. 在index.html中引入高德地图
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=申请的key&plugin=AMap.Geocoder"></script>
3. 在页面中使用
因为使用了ts所以需要先声明一下高德地图的AMap
不声明的话会出现下图错误
import React, { Component } from 'react';
// 声明AMap,也可以选择在d.ts中声明
declare let AMap: any;
接下来就能愉快的使用高德地图了
const carImg = require('@/assets/img/car.png');
componentDidMount() {
// console.log('window.AMap', window.AMap);
const map = new AMap.Map('container', {
// zoom:11,//级别
// center: [116.4,39.92],
resizeEnable: true
// viewMode:'3D'//使用3D视图
});
map.clearMap(); // 清除地图覆盖物
// 创建一个 Icon
var carIcon = new AMap.Icon({
// 图标尺寸
size: new AMap.Size(35, 35),
// 图标的取图地址
image: carImg,
// 图标所用图片大小
imageSize: new AMap.Size(35, 35),
// 图标取图偏移量
imageOffset: new AMap.Pixel(0, 0)
});
var markers = [{
icon: carIcon,
position: [116.397428, 39.90923]
}, {
icon: carIcon,
position: [116.368904, 39.913423]
}, {
icon: carIcon,
position: [116.305467, 39.807761]
}];
// 添加一些分布不均的点到地图上,地图上添加三个点标记,作为参照
markers.forEach(function(marker) {
new AMap.Marker({
map: map,
icon: marker.icon,
position: [marker.position[0], marker.position[1]],
// 以 icon 的 [center bottom] 为原点
offset: new AMap.Pixel(-13, -30)
});
});
map.setFitView();
}
详细使用看高德官网了