欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合Mybatis实现高德地图定位并将数据存入数据库的步骤详解

程序员文章站 2022-07-03 13:11:48
第一步配置yml文件server: port: 8080spring: datasource: username: root password: 123456 url: jdbc:mysql://lo...

第一步配置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

第二步对mybatis进行配置,并将实体映射。

<?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(需要申请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>当前位置</b>
 <input type="text" id="keyword1" name="keyword1" value="" onkeydown="keydown(event)" style="width: 95%"/>
 <br>
 <b>请输入关键字:</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()">点击提交坐标信息</button>
 <div id="result1" name="result1"></div>
</div>
<div id="pos">
 <b>鼠标左键在地图上单击获取坐标</b>
 <br>
 <div>x:<input type="text" id="lngx" name="lngx" value=""/>&nbsp;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=你申请的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//地图显示的缩放级别
  }),
  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"//城市,默认:“全国”
   });
   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(), //小时
    "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("服务器出现了问题")
   }
  });
 }


 document.getelementbyid("keyword").onkeyup = keydown;

 //输入提示
 function autosearch() {
  var keywords = document.getelementbyid("keyword").value;
  var auto;
  //加载输入提示插件
  amap.service(["amap.autocomplete"], function () {
   var autooptions = {
    city: "" //城市,默认全国
   };
   auto = new amap.autocomplete(autooptions);
   //查询成功时返回查询结果
   if (keywords.length > 0) {
    auto.search(keywords, function (status, result) {
     autocomplete_callback(result);
    });
   } else {
    document.getelementbyid("result1").style.display = "none";
   }
  });
 }

 //输出输入提示结果的回调函数
 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 = " π__π 亲,人家找不到结果!<br />要不试试:<br />1.请确保所有字词拼写正确<br />2.尝试不同的关键字<br />3.尝试更宽泛的关键字";
  }
  document.getelementbyid("result1").curselect = -1;
  document.getelementbyid("result1").tiparr = tiparr;
  document.getelementbyid("result1").innerhtml = resultstr;
  document.getelementbyid("result1").style.display = "block";
 }

 //输入提示框鼠标滑过时的样式
 function openmarkertipbyid(pointid, thiss) { //根据id打开搜索结果点tip
  thiss.style.background = '#cae1ff';
 }

 //输入提示框鼠标移出时的样式
 function onmouseout_markerstyle(pointid, thiss) { //鼠标移开后点样式恢复
  thiss.style.background = "";
 }

 //从输入提示框中选择关键字并查询
 function selectresult(index) {
  if (index < 0) {
   return;
  }
  if (navigator.useragent.indexof("msie") > 0) {
   document.getelementbyid("keyword").onpropertychange = null;
   document.getelementbyid("keyword").onfocus = focus_callback;
  }
  //截取输入提示的关键字部分
  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";
  //根据选择的输入提示关键字查询
  mapobj.plugin(["amap.placesearch"], function () {
   var msearch = new amap.placesearch(); //构造地点查询类
   amap.event.addlistener(msearch, "complete", placesearch_callback); //查询成功时的回调函数
   msearch.setcity(citycode);
   msearch.search(text); //关键字查询查询
  });
 }

 //定位选择输入提示关键字
 function focus_callback() {
  if (navigator.useragent.indexof("msie") > 0) {
   document.getelementbyid("keyword").onpropertychange = autosearch;
  }
 }

 //输出关键字查询结果的回调函数
 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();
 }

 //鼠标滑过查询结果改变背景样式,根据id打开信息窗体
 function openmarkertipbyid1(pointid, thiss) {
  thiss.style.background = '#cae1ff';
  windowsarr[pointid].open(mapobj, marker[pointid]);
 }

 //添加查询结果的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显示内容
 function tipcontents(type, address, tel) { //窗体内容
  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>

创建实体类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;//经度
 private double latitude;//维度
 private string position;//当前位置

 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;
 }
}

创建实体类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;
 }
}

创建接口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 = "数据提交成功";

 string code_notok="404";
 string message_not_ok="数据提交失败";

 string code_service="500";
 string message_service="服务器有点问题";

}

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 {
 /**
  * 将经纬度信息插入数据库
  */
 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);
  }
 }
}
//最后启动主类
@springbootapplication
@mapperscan("car2021.winter.com.demo.mapper")
public class carinfoapplication {

 public static void main(string[] args) {
  springapplication.run(carinfoapplication.class, args);
 }

}

访问localhost://post/gaode就是要求的界面

SpringBoot整合Mybatis实现高德地图定位并将数据存入数据库的步骤详解

代码结构

SpringBoot整合Mybatis实现高德地图定位并将数据存入数据库的步骤详解

到此这篇关于springboot整合mybatis实现高德地图定位并将数据存入数据库的文章就介绍到这了,更多相关springboot整合mybatis内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!