1、注册成为开发者
登录 高德开放平台控制台,如果没有开发者账号,请 注册开发者。
2. 创建key,项目里面要用
进入应用管理,创建新应用,新应用中添加 key,服务平台选择 Web端(JS API)。
3.获取 key 和密钥
创建成功后,可获取 key 和安全密钥。
4.使用前准备
编写 HTML 页面的基本的结构代码,需要一个<div>节点作为地图容器,同时为此<div>指定id属性
<div id='container' />
5.JS API 的加载和地图初始化
使用 JS API Loader 来加载,引入在控制台申请的 key 和安全密钥。
useEffect(() => {
AMapLoader.load({
key: import.meta.env.VITE_AMAP_KEY,
version: '2.0',
})
.then((AMap) => {
const amap = new AMap.Map('container', {
center: [116.45, 39.92],
zoom: 11,
viewMode: '2D',
features: ['bg', 'point', 'road'],
})
setAMap(amap)
})
.catch((err) => {
console.log(err)
})
}, [])
6.例子
绘制标记
<script>
//创建地图
var map = new AMap.Map('container', {
zoom: 10,
center: [116.405285, 39.904989]
});
// 创建两个点标记
var m1 = new AMap.Marker({
position: [116.49, 39.9]
});
var m2 = new AMap.Marker({
position: [116.29, 39.9]
});
var m3 = new AMap.Marker({
position: [116.69, 39.9],
icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png"
});
map.add(m1);
map.add(m2);
map.add(m3);
//自动适配到指定视野范围
document.querySelector("#fitblue").onclick = function(){
map.setFitView([m1, m2]);
}
//无参数时,自动自适应所有覆盖物
document.querySelector("#fitall").onclick = function(){
map.setFitView();
}
</script>
绘制折线
<script type="text/javascript">
var map = new AMap.Map("container", {
center: [116.395577, 39.892257],
zoom: 14
});
var path = [
[116.362209, 39.887487],
[116.422897, 39.878002],
[116.372105, 39.90651],
[116.428945, 39.89663]
];
var path2 = [
[
[
116.32873535156249,
40.01499435375046
],
[
116.52099609375,
40.019201307686785
],
[
116.49902343749999,
40.12849105685408
]
],
[
[
116.66931152343749,
40.0360265298117
],
[
116.72973632812499,
40.14948820651523
],
[
116.81213378906249,
40.01499435375046
]
]
]
var polyline = new AMap.Polyline({
path: path,
isOutline: true,
outlineColor: '#ffeeff',
borderWeight: 3,
strokeColor: "#3366FF",
strokeOpacity: 1,
strokeWeight: 6,
// 折线样式还支持 'dashed'
strokeStyle: "solid",
// strokeStyle是dashed时有效
strokeDasharray: [10, 5],
lineJoin: 'round',
lineCap: 'round',
zIndex: 50,
})
var polyline2 = new AMap.Polyline({
path: path2,
isOutline: true,
outlineColor: '#ffeeff',
borderWeight: 3,
strokeColor: "#3366FF",
strokeOpacity: 1,
strokeWeight: 6,
// 折线样式还支持 'dashed'
strokeStyle: "dashed",
// strokeStyle是dashed时有效
strokeDasharray: [15, 5],
lineJoin: 'round',
lineCap: 'round',
zIndex: 50,
})
map.add([polyline,polyline2]);
map.setFitView();
</script>