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.顯示交通信息