1.登录高德开放平台
高德开放平台 | 高德地图API
2.获取密钥key
1.点击控制台
2.创建新应用
3.添加key
4.创建key
5.获取key
3.java整合
1.高德配置类
package com.thk.controller.map;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;/*** 高德地图配置类*/
@Configuration
public class AmapConfig {@Value("${amap.key}")private String apiKey;@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}@Beanpublic AmapService amapService(RestTemplate restTemplate) {return new AmapService(restTemplate, apiKey);}
}
2.高德控制器
package com.thk.controller.map;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Map;/*** 高德地图控制器*/
@RestController
@RequestMapping("/map")
public class MapController {@Autowiredprivate AmapService amapService;@GetMapping("/geocode")public ResponseEntity<?> getGeoCode(String address) {System.out.println( address );try {Map<String, Object> result = amapService.getGeoCode( address );return ResponseEntity.ok( result );} catch (Exception e) {return ResponseEntity.status( 500 ).body( "获取位置信息失败" );}}
}
3.高德服务类
package com.thk.controller.map;import org.springframework.web.client.RestTemplate;import java.util.Map;public class AmapService {private final RestTemplate restTemplate;private final String apiKey;private static final String GEOCODE_URL = "https://restapi.amap.com/v3/geocode/geo";public AmapService(RestTemplate restTemplate, String apiKey) {this.restTemplate = restTemplate;this.apiKey = apiKey;}// 获取地理编码public Map<String, Object> getGeoCode(String address) {String url = String.format("%s?address=%s&key=%s", GEOCODE_URL, address, apiKey);return restTemplate.getForObject(url, Map.class);}
}
4.yml配置高德key
4.前端测试
在java项目resources目录下新建map.html,注意一点,前端代码中的需要修改获取的key
<script src="https://webapi.amap.com/maps?v=2.0&key=输入你获取的key"></script>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>高德地图</title><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script><script src="https://webapi.amap.com/maps?v=2.0&key=你获取的key"></script><style>html, body {margin: 0;padding: 0;width: 100%;height: 100%;overflow: hidden;}#app {width: 100%;height: 100%;position: relative;}#container {width:100%;height:100%;}.search-box {position: absolute;top: 20px;left: 20px;z-index: 999;background: rgba(255,255,255,0.8);padding: 15px;border-radius: 8px;box-shadow: 0 2px 6px rgba(0,0,0,0.3);}.search-box input {width: 300px;height: 40px;padding: 0 10px;font-size: 16px;border: 1px solid #ddd;border-radius: 4px;}.search-box button {height: 40px;padding: 0 20px;margin-left: 10px;font-size: 16px;background: #1E90FF;color: white;border: none;border-radius: 4px;cursor: pointer;}.search-box button:hover {background: #187bcd;}.traffic-control {position: absolute;top: 20px;right: 20px;z-index: 999;background: rgba(255,255,255,0.8);padding: 10px;border-radius: 8px;box-shadow: 0 2px 6px rgba(0,0,0,0.3);}.traffic-control button {height: 30px;padding: 0 15px;margin-left: 5px;font-size: 14px;background: #1E90FF;color: white;border: none;border-radius: 4px;cursor: pointer;}/* 初始标记样式 */.initial-marker {background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23FF0000"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>') no-repeat;width: 40px;height: 40px;background-size: contain;animation: pulse 1.5s infinite;}@keyframes pulse {0% { transform: scale(1); }50% { transform: scale(1.2); }100% { transform: scale(1); }}</style>
</head>
<body>
<div id="app"><div class="search-box"><input v-model="address" placeholder="请输入地点名称"><button @click="searchLocation">搜索</button></div><div class="traffic-control"><button @click="toggleTraffic">{{ trafficVisible ? '隐藏交通' : '显示交通' }}</button></div><div id="container"></div>
</div><script>new Vue({el: '#app',data: {address: '',map: null,marker: null,trafficLayer: null,trafficVisible: false},mounted() {this.initMap();},methods: {initMap() {this.map = new AMap.Map('container', {zoom: 13,center: [106.550483,29.563707],viewMode: '3D'});// 添加点击地图事件this.map.on('click', this.handleMapClick);// 添加初始标记this.marker = new AMap.Marker({position: [106.550483,29.563707],content: '<div class="initial-marker" @click="handleMarkerClick"></div>', // 在标记的div上添加点击事件,但注意这通常不会生效,因为AMap的Marker不支持直接添加DOM事件。这里仅作为示例,实际应通过Marker的click事件处理。offset: new AMap.Pixel(-20, -40),map: this.map});// 为标记添加点击事件(正确方式)this.marker.on('click', this.handleMarkerClick);this.trafficLayer = new AMap.TileLayer.Traffic({zIndex: 10});},searchLocation() {if (!this.address) return;fetch(`/map/geocode?address=${this.address}`).then(res => res.json()).then(data => {if (data.status === '1' && data.geocodes.length > 0) {const location = data.geocodes[0].location.split(',');const lng = parseFloat(location[0]);const lat = parseFloat(location[1]);if (this.marker) {this.map.remove(this.marker);}this.marker = new AMap.Marker({position: [lng, lat],map: this.map});this.map.setCenter([lng, lat]);this.map.setZoom(15);}}).catch(err => console.error('搜索失败:', err));},toggleTraffic() {this.trafficVisible = !this.trafficVisible;if (this.trafficVisible) {this.trafficLayer.setMap(this.map);} else {this.trafficLayer.setMap(null);}},handleMapClick(e) {const { lnglat } = e;console.log('点击地图位置:', lnglat.lng, lnglat.lat);},handleMarkerClick(e) {// 对于Marker的点击事件,e参数本身不包含位置信息,但因为我们知道是点击的marker,所以可以直接使用marker的位置const { position } = this.marker;console.log('点击标记位置:', position.lng, position.lat);}}});
</script>
</body>
</html>
5.测试
1.输入地点
2.显示交通信息