当前位置: 首页 > news >正文

Springboot整合高德地图

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

http://www.dtcms.com/a/264135.html

相关文章:

  • NeurIPS-2023《A Definition of Continual Reinforcement Learning》
  • 基于GD32 MCU的IAP差分升级方案
  • 迎战 AI Overviews:SEO 不被淘汰的实战策略
  • SpringBoot全局异常详解
  • Electron 应用打包与分发:从开发到交付的完整指南
  • 多容器应用与编排——AI教你学Docker
  • Java-String类静态成员方法深度解析
  • AR 地产互动沙盘:为地产沙盘带来变革​
  • OpenCV-Python Tutorial : A Candy from Official Main Page(二)
  • 设备管理的重要性:企业数字化浪潮下的核心命题
  • 企业上网行为管理:零信任安全产品的对比分析
  • Linux基本命令篇 —— grep命令
  • 防 XSS和CSRF 过滤器(Filter)
  • go语言安装达梦数据完整教程
  • JVM 中的垃圾回收算法及垃圾回收器详解
  • 【仿muduo库实现并发服务器】Connection模块
  • CentOS 8中 更新或下载时报错:为仓库 ‘appstream‘ 下载元数据失败 : Cannot prepare internal
  • 02.SpringBoot常用Utils工具类详解
  • 从马赛克到色彩错乱:一次前景图像处理异常的全流程踩坑记录
  • Python实例题:基于 Python 的简单爬虫与数据可视化
  • 【IP 潮玩行业深度研究与学习】
  • 【仿muduo库实现并发服务器】eventloop模块
  • 香橙派3B学习笔记14:deb 打包程序_解包前后脚本运行
  • 折线图多数据处理
  • redux基本概念介绍 与 更新方式
  • 【网工|知识升华版|理论】ARQ机制|CSMA/CD协议
  • NetSuite 中如何在已关账期间内Unapply Customer Payment?
  • 数据结构day6——内核链表
  • 手机屏色斑缺陷修复及相关液晶线路激光修复原理
  • 一文讲清楚React合成事件机制和this的绑定问题