1. Primero, debe solicitar su propia cuenta y clave en el sitio web oficial de Gaode Map
Proceder de la siguiente:
2. Realizar el mapa de visualización
2.1 Introducir recursos para crear mapas
<!-- 引入资源 -->
<script type="text/javascript">
// 引入密钥和key值
window._AMapSecurityConfig = {
// 这里写自己申请的安全密钥
securityJsCode: 'b015002be73d099ca1138212dc65d497',
}
</script>
<!-- 这里写自己申请的key值 -->
<script type="text/javascript"
src="https://webapi.amap.com/maps?v=2.0&key=5d654dec4fa284f641fde765ea5bc604&plugin=AMap.GeoJSON">
</script>
<!-- 引入jquery资源 -->
<script src="../jquery.min.js"></script>
<!-- 引入高德所给的css样式 -->
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
Luego use la demostración dada por el mapa de Gaode para realizar la visualización del mapa
<!-- 创建地图容器 -->
<div id="container">
</div>
var map = new AMap.Map('container', {
center: [118.910321, 32.105220],
zoom: 16,
viewMode: '3D',
pitch: 45,
});
El mapa muestra: (El punto central aquí es el Campus Xianlin de la Universidad Normal de Nanjing)
2.2 Darse cuenta de agregar controles
// 使用控件
AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.ControlBar', 'AMap.MoveAnimation'], function () {
map.addControl(new AMap.ToolBar({
position: {
top: '80px',
right: '40px'
}
}))
map.addControl(new AMap.Scale);
map.addControl(new AMap.ControlBar);
})
Los resultados agregados se muestran de la siguiente manera:
2.3 Realizar la función de marcado
Aquí, el estilo css de Gaode se usa para crear un control div:
<div class="info">点击地图热门地点</div>
A continuación, agregue el evento de escucha de clics en el mapa:
// 监听地图点击事件
map.on('click',function(e){
// 创建标记
var marker = new AMap.Marker({
position:e.lnglat,
})
// 添加标记图层
map.add(marker)
})
El efecto es el siguiente:
2.4 Realizar almacenamiento de datos permanente
Registre datos en el almacenamiento local usando GeoJSON. el código se muestra a continuación:
// 定义一个全局变量
var geojson = new AMap.GeoJSON({
geoJSON: null,
})
if (JSON.stringify(getData()) != '[]') {
// 导入数据
geojson.importData(getData())
// 恢复旧数据的点击事件
geojson.eachOverlay(function (item) {
item.on('click', function (e) {
var ext = item.getExtData()
var click = ++ext._geoJsonProperties.click
var infowindow = new AMap.InfoWindow({
anchor: 'top-center',
content: `<div>打卡了${click}次</div>`
})
infowindow.open(map, item.getPosition())
saveData(geojson.toGeoJSON())
})
})
}
// 将geojson加载到地图上
map.add(geojson)
// 监听地图的点击事件
map.on('click', function (e) {
var marker = new AMap.Marker({
position: e.lnglat,
extData: {
_geoJsonProperties: {
gid: geojson.getOverlays().length + 1,
click: 0,
},
}
})
// 使用覆盖物的点击事件
marker.on('click', function (e) {
var ext = marker.getExtData()
var click = ++ext._geoJsonProperties.click
// console.log('点击了' + click + '次')
// 使用消息提示框显示
var infowindow = new AMap.InfoWindow({
anchor: 'top-center',
content: `<div>打卡了${click}次</div>`
})
// 打开信息窗口
infowindow.open(map, marker.getPosition())
saveData(geojson.toGeoJSON())
})
// 数据持久化
// map.add(marker)
geojson.addOverlay(marker)
// console.log(geojson)
saveData(geojson.toGeoJSON())
})
// 从local storage中读取数据
function getData() {
//判断本地local storage中不存在数据
if (!localStorage.getItem('geojson')) {
localStorage.setItem('geojson', '[]')
}
return JSON.parse(localStorage.getItem('geojson'))
}
// 从local storage中写数据
function saveData(data) {
localStorage.setItem('geojson', JSON.stringify(data))
};
2.5 Realizar la función de navegación
Primero, agregue un cuadro div en el mapa para implementar los botones de navegación.
<div class="input-card">
<h4>推荐路线</h4>
<div class="input-item">
<button class="btn" onclick="startAnimation()">开始动画</button>
</div>
Esto se implementa aquí, un botón en el que se puede hacer clic para navegar:
Al presionar este botón, el usuario espera obtener indicaciones. Aquí debe escribir una función de devolución de llamada.
El punto de partida y el punto final aquí son la Puerta No. 1 de la Universidad Normal del Sur y la Puerta No. 6 de la Universidad Normal del Sur.
function startAnimation() {
// console.log('开始动画')
AMap.plugin('AMap.Driving', function () {
var driving = new AMap.Driving({
map: map,
policy: AMap.DrivingPolicy.LEAST_TIME,
})
// 设置起点和终点
var start = new AMap.LngLat(118.912561, 32.100193)
var end = new AMap.LngLat(118.916887, 32.113263)
var opts = {
waypoints: [],
}
geojson.eachOverlay(function (item) {
opts.waypoints.push(item.getPosition())
})
driving.search(start, end, opts, function (status, result) {
if (status == 'complete') {
console.log(result)
var lineArr = []
result.routes[0].steps.forEach(function (item) {
lineArr.push(...item.path)
});
var marker = new AMap.Marker({
map: map,
position: start,
icon: 'https://webapi.amap.com/images/car.png',
offset: new AMap.Pixel(-13, -26),
autoRotation: true,
angle: 180,
})
var passedPolyline = new AMap.Polyline({
map: map,
strokeColor: '#AF5',//描边的绿色
strokeWeight: 6,//线宽
})
marker.on('moving', function (e) {
passedPolyline.setPath(e.passedPath)
})
map.setFitView()
marker.moveAlong(lineArr, {
duration: 500,
autoRotation: true,
})
} else {
console.log('error')
}
}
)
})
}
Luego establezca el waypoint, se ha mostrado el código anterior. El plan de ruta final es:
2.7 Realizar el efecto de animación
el código se muestra a continuación:
function startAnimation() {
// console.log('开始动画')
AMap.plugin('AMap.Driving', function () {
var driving = new AMap.Driving({
map: map,
policy: AMap.DrivingPolicy.LEAST_TIME,
})
// 设置起点和终点
var start = new AMap.LngLat(118.912561, 32.100193)
var end = new AMap.LngLat(118.916887, 32.113263)
var opts = {
waypoints: [],
}
geojson.eachOverlay(function (item) {
opts.waypoints.push(item.getPosition())
})
driving.search(start, end, opts, function (status, result) {
if (status == 'complete') {
console.log(result)
var lineArr = []
result.routes[0].steps.forEach(function (item) {
lineArr.push(...item.path)
});
var marker = new AMap.Marker({
map: map,
position: start,
icon: 'https://webapi.amap.com/images/car.png',
offset: new AMap.Pixel(-13, -26),
autoRotation: true,
angle: 180,
})
var passedPolyline = new AMap.Polyline({
map: map,
strokeColor: '#AF5',//描边的绿色
strokeWeight: 6,//线宽
})
marker.on('moving', function (e) {
passedPolyline.setPath(e.passedPath)
})
map.setFitView()
marker.moveAlong(lineArr, {
duration: 500,
autoRotation: true,
})
} else {
console.log('error')
}
}
)
})
}
Luego haga clic en el botón de inicio de animación para realizar la ejecución automática de la ruta.
3. Problemas que surgen
Hay muchos problemas con el código anterior:
(1) Si hay un problema con algunas declaraciones de funciones, se informará un error
(2) El error se muestra de la siguiente manera:
La razón principal es que olvidé escribir nuevo para abrir un nuevo objeto
En resumen, el proceso de modificación del BUG es realmente lento, pero estoy muy feliz de poder solucionarlo, y también he ejercitado mi paciencia.