SpringBoot整合Mybatis實(shí)現(xiàn)高德地圖定位并將數(shù)據(jù)存入數(shù)據(jù)庫的步驟詳解
第一步配置yml文件
server: port: 8080 spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html encoding: UTF-8 content-type: text/html mode: HTML5 mybatis: mapper-locations: classpath:mapping/GaoDe.xml type-aliases-package: car2021.winter.com.demo.entity logging: file: name: car2021.winter.log
第二步對(duì)Mybatis進(jìn)行配置,并將實(shí)體映射。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="car2021.winter.com.demo.mapper.GaoDeMapper"> <resultMap id="GaoDeMap" type="car2021.winter.com.demo.entity.GaoDe"> <result column="id" jdbcType="INTEGER" property="id"></result> <result column="time" jdbcType="VARCHAR" property="time"></result> <result column="Longitude" jdbcType="DOUBLE" property="Longitude"></result> <result column="Latitude" jdbcType="DOUBLE" property="Latitude"></result> <result column="Position" jdbcType="VARCHAR" property="Position"></result> </resultMap> <insert id="insertGaoDe"> insert into GaoDe (time ,Longitude,Latitude,Position) values(#{time},#{Longitude},#{Latitude},#{Position}) </insert> </mapper>
第三步寫HTML,并引入自己的高德API(需要申請(qǐng)key)
<!DOCTYPE HTML> <html> <head> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdn.bootcss.com/popper.js/1.14.7/umd/popper.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>高德地圖</title> <style type="text/css"> body { margin: 0; height: 100%; width: 100%; position: absolute; font-size: 12px; } #mapContainer { position: absolute; top: 0; left: 0; right: 0; bottom: 0; } #tip { background-color: #fff; border: 1px solid #ccc; padding-left: 10px; padding-right: 2px; position: absolute; min-height: 65px; top: 10px; font-size: 12px; right: 10px; border-radius: 3px; overflow: hidden; line-height: 20px; min-width: 400px; } #tip input[type="button"] { background-color: #0D9BF2; height: 25px; text-align: center; line-height: 25px; color: #fff; font-size: 12px; border-radius: 3px; outline: none; border: 0; cursor: pointer; } #tip input[type="text"] { height: 25px; border: 1px solid #ccc; padding-left: 5px; border-radius: 3px; outline: none; } #pos { height: 70px; background-color: #fff; padding-left: 10px; padding-right: 10px; position: absolute; font-size: 12px; right: 10px; bottom: 30px; border-radius: 3px; line-height: 30px; border: 1px solid #ccc; } #pos input { border: 1px solid #ddd; height: 23px; border-radius: 3px; outline: none; } #result1 { max-height: 300px; } </style> </head> <body> <div id="mapContainer"></div> <div id="tip"> <b>當(dāng)前位置</b> <input type="text" id="keyword1" name="keyword1" value="" onkeydown="keydown(event)" style="width: 95%"/> <br> <b>請(qǐng)輸入關(guān)鍵字:</b> <input type="text" id="keyword" name="keyword" value="" onkeydown='keydown(event)' style="width: 95%;" autocomplete="off"/> <button id="GaoDe" type="button" style="color: #4cae4c; width: 95%" onclick="commitGaoDe()">點(diǎn)擊提交坐標(biāo)信息</button> <div id="result1" name="result1"></div> </div> <div id="pos"> <b>鼠標(biāo)左鍵在地圖上單擊獲取坐標(biāo)</b> <br> <div>X:<input type="text" id="lngX" name="lngX" value=""/> Y:<input type="text" id="latY" name="latY" value=""/></div> </div> <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=你申請(qǐng)的Key值"></script> <script type="text/javascript"> var windowsArr = []; var marker = []; var mapObj = new AMap.Map("mapContainer", { resizeEnable: true, view: new AMap.View2D({ resizeEnable: true, zoom: 13//地圖顯示的縮放級(jí)別 }), keyboardEnable: false }); var clickEventListener = AMap.event.addListener(mapObj, 'click', function (e) { document.getElementById("lngX").value = e.lnglat.getLng(); document.getElementById("latY").value = e.lnglat.getLat(); AMap.plugin('AMap.Geocoder', function () { var geocoder = new AMap.Geocoder({ city: "010"http://城市,默認(rèn):“全國” }); geocoder.getAddress(e.lnglat, function (status, result) { if (status === 'complete') { document.getElementById("keyword1").value = result.regeocode.formattedAddress; } else { alert("無法獲取地址") } }) }); }); function commitGaoDe() { var Longitude = document.getElementById("lngX").value; var Latitude = document.getElementById("latY").value; var positionArea = document.getElementById("keyword1").value; Date.prototype.Format = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "H+": this.getHours(), //小時(shí) "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; }; var time = new Date().Format("yyyy-MM-dd HH:mm:ss"); var params = {"time": time, "Longitude": Longitude, "Latitude": Latitude, "position": positionArea}; params = JSON.stringify(params); $.ajax({ type: 'post', url: 'http://localhost:8080/submitMap', data: params, dataType: "json", contentType: 'application/json;charset=utf-8', async: false, success: function (data) { if (data.code === "200") { alert(data.message) } else { alert(data.message) } }, error: function () { alert("服務(wù)器出現(xiàn)了問題") } }); } document.getElementById("keyword").onkeyup = keydown; //輸入提示 function autoSearch() { var keywords = document.getElementById("keyword").value; var auto; //加載輸入提示插件 AMap.service(["AMap.Autocomplete"], function () { var autoOptions = { city: "" //城市,默認(rèn)全國 }; auto = new AMap.Autocomplete(autoOptions); //查詢成功時(shí)返回查詢結(jié)果 if (keywords.length > 0) { auto.search(keywords, function (status, result) { autocomplete_CallBack(result); }); } else { document.getElementById("result1").style.display = "none"; } }); } //輸出輸入提示結(jié)果的回調(diào)函數(shù) function autocomplete_CallBack(data) { var resultStr = ""; var tipArr = data.tips; if (tipArr && tipArr.length > 0) { for (var i = 0; i < tipArr.length; i++) { resultStr += "<div id='divid" + (i + 1) + "' οnmοuseοver='openMarkerTipById(" + (i + 1) + ",this)' οnclick='selectResult(" + i + ")' οnmοuseοut='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\"" + "data=" + tipArr[i].adcode + ">" + tipArr[i].name + "<span style='color:#C1C1C1;'>" + tipArr[i].district + "</span></div>"; } } else { resultStr = " π__π 親,人家找不到結(jié)果!<br />要不試試:<br />1.請(qǐng)確保所有字詞拼寫正確<br />2.嘗試不同的關(guān)鍵字<br />3.嘗試更寬泛的關(guān)鍵字"; } document.getElementById("result1").curSelect = -1; document.getElementById("result1").tipArr = tipArr; document.getElementById("result1").innerHTML = resultStr; document.getElementById("result1").style.display = "block"; } //輸入提示框鼠標(biāo)滑過時(shí)的樣式 function openMarkerTipById(pointid, thiss) { //根據(jù)id打開搜索結(jié)果點(diǎn)tip thiss.style.background = '#CAE1FF'; } //輸入提示框鼠標(biāo)移出時(shí)的樣式 function onmouseout_MarkerStyle(pointid, thiss) { //鼠標(biāo)移開后點(diǎn)樣式恢復(fù) thiss.style.background = ""; } //從輸入提示框中選擇關(guān)鍵字并查詢 function selectResult(index) { if (index < 0) { return; } if (navigator.userAgent.indexOf("MSIE") > 0) { document.getElementById("keyword").onpropertychange = null; document.getElementById("keyword").onfocus = focus_callback; } //截取輸入提示的關(guān)鍵字部分 var text = document.getElementById("divid" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g, ""); var cityCode = document.getElementById("divid" + (index + 1)).getAttribute('data'); document.getElementById("keyword").value = text; document.getElementById("result1").style.display = "none"; //根據(jù)選擇的輸入提示關(guān)鍵字查詢 mapObj.plugin(["AMap.PlaceSearch"], function () { var msearch = new AMap.PlaceSearch(); //構(gòu)造地點(diǎn)查詢類 AMap.event.addListener(msearch, "complete", placeSearch_CallBack); //查詢成功時(shí)的回調(diào)函數(shù) msearch.setCity(cityCode); msearch.search(text); //關(guān)鍵字查詢查詢 }); } //定位選擇輸入提示關(guān)鍵字 function focus_callback() { if (navigator.userAgent.indexOf("MSIE") > 0) { document.getElementById("keyword").onpropertychange = autoSearch; } } //輸出關(guān)鍵字查詢結(jié)果的回調(diào)函數(shù) function placeSearch_CallBack(data) { //清空地圖上的InfoWindow和Marker windowsArr = []; marker = []; mapObj.clearMap(); var resultStr1 = ""; var poiArr = data.poiList.pois; var resultCount = poiArr.length; for (var i = 0; i < resultCount; i++) { resultStr1 += "<div id='divid" + (i + 1) + "' οnmοuseοver='openMarkerTipById1(" + i + ",this)' οnmοuseοut='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"http://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><h3><font color=\"#00a6ac\">名稱: " + poiArr[i].name + "</font></h3>"; resultStr1 += TipContents(poiArr[i].type, poiArr[i].address, poiArr[i].tel) + "</td></tr></table></div>"; addmarker(i, poiArr[i]); } mapObj.setFitView(); } //鼠標(biāo)滑過查詢結(jié)果改變背景樣式,根據(jù)id打開信息窗體 function openMarkerTipById1(pointid, thiss) { thiss.style.background = '#CAE1FF'; windowsArr[pointid].open(mapObj, marker[pointid]); } //添加查詢結(jié)果的marker&infowindow function addmarker(i, d) { var lngX = d.location.getLng(); var latY = d.location.getLat(); var markerOption = { map: mapObj, icon: "http://webapi.amap.com/images/" + (i + 1) + ".png", position: new AMap.LngLat(lngX, latY) }; var mar = new AMap.Marker(markerOption); marker.push(new AMap.LngLat(lngX, latY)); var infoWindow = new AMap.InfoWindow({ content: "<h3><font color=\"#00a6ac\"> " + (i + 1) + ". " + d.name + "</font></h3>" + TipContents(d.type, d.address, d.tel), size: new AMap.Size(300, 0), autoMove: true, offset: new AMap.Pixel(0, -30) }); windowsArr.push(infoWindow); var aa = function (e) { var nowPosition = mar.getPosition(), lng_str = nowPosition.lng, lat_str = nowPosition.lat; infoWindow.open(mapObj, nowPosition); document.getElementById("lngX").value = lng_str; document.getElementById("latY").value = lat_str; }; AMap.event.addListener(mar, "mouseover", aa); } //infowindow顯示內(nèi)容 function TipContents(type, address, tel) { //窗體內(nèi)容 if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") { type = "暫無"; } if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") { address = "暫無"; } if (tel == "" || tel == "undefined" || tel == null || tel == " undefined" || typeof address == "tel") { tel = "暫無"; } var str = " 地址:" + address + "<br /> 電話:" + tel + " <br /> 類型:" + type; return str; } function keydown(event) { var key = (event || window.event).keyCode; var result = document.getElementById("result1") var cur = result.curSelect; if (key === 40) { //down if (cur + 1 < result.childNodes.length) { if (result.childNodes[cur]) { result.childNodes[cur].style.background = ''; } result.curSelect = cur + 1; result.childNodes[cur + 1].style.background = '#CAE1FF'; document.getElementById("keyword").value = result.tipArr[cur + 1].name; } } else if (key === 38) { //up if (cur - 1 >= 0) { if (result.childNodes[cur]) { result.childNodes[cur].style.background = ''; } result.curSelect = cur - 1; result.childNodes[cur - 1].style.background = '#CAE1FF'; document.getElementById("keyword").value = result.tipArr[cur - 1].name; } } else if (key === 13) { var res = document.getElementById("result1"); if (res && res['curSelect'] !== -1) { selectResult(document.getElementById("result1").curSelect); } } else { autoSearch(); } } </script> </body> </html>
創(chuàng)建實(shí)體類GaoDe
package car2021.winter.com.demo.entity; import org.springframework.format.annotation.DateTimeFormat; /** * Author: PXY * Email: 1817865166@qq.com * Date: 2021/1/4 */ public class GaoDe { @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private String time; private double Longitude;//經(jīng)度 private double Latitude;//維度 private String Position;//當(dāng)前位置 public GaoDe() { } public GaoDe(String time, double Longitude, double Latitude, String Position) { this.time = time; this.Longitude = Longitude; this.Latitude = Latitude; this.Position = Position; } @Override public String toString() { return "GaoDe{" + "time='" + time + '\'' + ", Longitude=" + Longitude + ", Latitude=" + Latitude + ", Position='" + Position + '\'' + '}'; } public String getId() { return time; } public void setId(String time) { this.time = time; } public double getLongitude() { return Longitude; } public void setLongitude(double longitude) { Longitude = longitude; } public double getLatitude() { return Latitude; } public void setLatitude(double latitude) { Latitude = latitude; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getPosition() { return Position; } public void setPosition(String position) { Position = position; } }
創(chuàng)建實(shí)體類newsCode
package car2021.winter.com.demo.entity; /** * Author: PXY * Email: 1817865166@qq.com * Date: 2021/1/5 */ public class NewsCode { private String code; private String message; public NewsCode(String code, String message) { this.code = code; this.message = message; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
創(chuàng)建接口Code
package car2021.winter.com.demo.entity; /** * Author: PXY * Email: 1817865166@qq.com * Date: 2021/1/5 */ public interface Code { String Code_OK = "200"; String message_OK = "數(shù)據(jù)提交成功"; String Code_NotOK="404"; String message_Not_Ok="數(shù)據(jù)提交失敗"; String Code_Service="500"; String message_Service="服務(wù)器有點(diǎn)問題"; }
Mapper接口
package car2021.winter.com.demo.mapper; import car2021.winter.com.demo.entity.GaoDe; import org.springframework.stereotype.Repository; /** * Author: PXY * Email: 1817865166@qq.com * Date: 2021/1/5 */ @Repository public interface GaoDeMapper { /** * 將經(jīng)緯度信息插入數(shù)據(jù)庫 */ void insertGaoDe(GaoDe gaoDe); }
Service
package car2021.winter.com.demo.service; import car2021.winter.com.demo.entity.GaoDe; import car2021.winter.com.demo.mapper.GaoDeMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Author: PXY * Email: 1817865166@qq.com * Date: 2021/1/5 */ @Service public class GaoDeService { @Autowired GaoDeMapper gaoDeMapper; public void insertGaoDe(GaoDe gaoDe) { gaoDeMapper.insertGaoDe(gaoDe); } }
controller
package car2021.winter.com.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Author: PXY * Email: 1817865166@qq.com * Date: 2021/1/5 */ @Controller public class GaoDeMap { @RequestMapping("/GaoDe") public String GaoDeMap() { return "GaoDe"; } }
package car2021.winter.com.demo.controller; import car2021.winter.com.demo.entity.Code; import car2021.winter.com.demo.entity.GaoDe; import car2021.winter.com.demo.entity.NewsCode; import car2021.winter.com.demo.service.GaoDeService; import ch.qos.logback.core.encoder.EchoEncoder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; /** * Author: PXY * Email: 1817865166@qq.com * Date: 2021/1/5 */ @RestController public class AlterGaoDe { @Autowired private GaoDeService gaoDeService; @RequestMapping(value = "/submitMap", method = RequestMethod.POST) public NewsCode insertMap(@RequestBody GaoDe gaoDe) { try { gaoDeService.insertGaoDe(gaoDe); System.out.println(gaoDe); return new NewsCode(Code.Code_OK, Code.message_OK); } catch (Exception e) { e.printStackTrace(); return new NewsCode(Code.Code_NotOK, Code.message_Not_Ok); } } }
//最后啟動(dòng)主類 @SpringBootApplication @MapperScan("car2021.winter.com.demo.mapper") public class CarInfoApplication { public static void main(String[] args) { SpringApplication.run(CarInfoApplication.class, args); } }
訪問localhost://post/Gaode就是要求的界面
代碼結(jié)構(gòu)
到此這篇關(guān)于SpringBoot整合Mybatis實(shí)現(xiàn)高德地圖定位并將數(shù)據(jù)存入數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)SpringBoot整合Mybatis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實(shí)現(xiàn)KFC點(diǎn)餐小程序
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)KFC點(diǎn)餐系統(tǒng)小程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01spring boot動(dòng)態(tài)加載Echart餅狀圖
這篇文章主要為大家詳細(xì)介紹了spring boot動(dòng)態(tài)加載Echart餅狀圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12mybatis多層嵌套resultMap及返回自定義參數(shù)詳解
這篇文章主要介紹了mybatis多層嵌套resultMap及返回自定義參數(shù)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12Java8新特性之Collectors.joining()實(shí)例詳解
在項(xiàng)目中我們常常要對(duì)list集合的數(shù)據(jù)做一些字符串拼接/處理等相關(guān)操作,下面這篇文章主要給大家介紹了關(guān)于Java8新特性之Collectors.joining()的相關(guān)資料,需要的朋友可以參考下2023-01-01Spring Boot熱加載jar實(shí)現(xiàn)動(dòng)態(tài)插件的思路
本文主要介紹在 Spring Boot 工程中熱加載 jar 包并注冊(cè)成為 Bean 對(duì)象的一種實(shí)現(xiàn)思路,在動(dòng)態(tài)擴(kuò)展功能的同時(shí)支持在插件中注入主程序的 Bean 實(shí)現(xiàn)功能更強(qiáng)大的插件2021-10-10