Springboot集成百度地圖實(shí)現(xiàn)定位打卡的示例代碼
一、打卡數(shù)據(jù)庫(kù)SQL
CREATE TABLE `sign` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用戶(hù)名稱(chēng)', `location` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '打卡位置', `time` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '打卡時(shí)間', `comment` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '備注', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
二、申請(qǐng)自己的API
百度開(kāi)放平臺(tái)官網(wǎng):
https://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5

獲取API
<script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=bmvg8yeOopwOB4aHl5uvx52rgIa3VrPO"></script>
放入到我們的前端


三、寫(xiě)Java后臺(tái)
1.新建一個(gè)Java類(lèi)

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@Data
@TableName("sign")
public class Sign {
@TableId(type = IdType.AUTO)
private Integer id;
private String user;
private String location;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private String time;
private String comment;
}2.設(shè)置我們Controller

// 新增或者更新
@PostMapping
public Result save(@RequestBody Sign sign) {
if (sign.getId() == null) { // 新增打卡
String today = DateUtil.today();
QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user", sign.getUser());
queryWrapper.eq("time", today);
Sign one = signService.getOne(queryWrapper);
if (one != null) { // 打過(guò)卡了
return Result.error("-1", "您已打過(guò)卡");
}
sign.setTime(today);
}
signService.saveOrUpdate(sign);
return Result.success();
}完整代碼:
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Sign;
import com.example.demo.service.ISignService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/sign")
public class SignController {
@Resource
private ISignService signService;
// 新增或者更新
@PostMapping
public Result save(@RequestBody Sign sign) {
if (sign.getId() == null) { // 新增打卡
String today = DateUtil.today();
QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user", sign.getUser());
queryWrapper.eq("time", today);
Sign one = signService.getOne(queryWrapper);
if (one != null) { // 打過(guò)卡了
return Result.error("-1", "您已打過(guò)卡");
}
sign.setTime(today);
}
signService.saveOrUpdate(sign);
return Result.success();
}
//刪除
// @DeleteMapping("/{id}")
// public Result delete(@PathVariable Integer id) {
// return Result.success(userService.removeById(id));
// }
@PostMapping("/del/batch")
public Result deleteBatch(@RequestBody List<Integer> ids) {//批量刪除
return Result.success(signService.removeByIds(ids));
}
//查詢(xún)所有數(shù)據(jù)
@GetMapping
public Result findAll() {
return Result.success(signService.list());
}
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id) {
return Result.success(signService.getById(id));
}
@GetMapping("/page")
public Result findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String user) {
QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("id");
if (!"".equals(user)) {
queryWrapper.like("user", user);
}
return Result.success(signService.page(new Page<>(pageNum, pageSize), queryWrapper));
}
}四、前端使用接口
在需要使用的vue里面使用獲取當(dāng)前位置的函數(shù)
mounted() {
// 獲取地理位置
var geolocation = new BMapGL.Geolocation();
geolocation.getCurrentPosition(function(r){
if(this.getStatus() == BMAP_STATUS_SUCCESS){
const province = r.address.province
const city = r.address.city
localStorage.setItem("location", province + city)
}
});
},
<template>
<div>
<el-card style="width: 600px; margin-left: 5px">
<el-form label-width="80px" size="small">
<el-upload
class="avatar-uploader"
:action="'http://localhost:9090/file/upload'"
:show-file-list="false"
:on-success="handleAvatarSuccess">
<img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
<el-form-item label="用戶(hù)名">
<el-input v-model="form.username" disabled autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="昵稱(chēng)">
<el-input v-model="form.nickname" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="性別">
<el-select v-model="form.sex" placeholder="請(qǐng)選擇您的性別" style="width: 100%">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="郵箱">
<el-input v-model="form.email" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="電話">
<el-input v-model="form.phone" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="地址">
<el-input type="textarea" v-model="form.address" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="save">保 存</el-button>
<el-button type="primary" @click="sign"><i class="el-icon-location" />定位</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
<script>
export default {
name: "Person",
data() {
return {
form: {},
user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
options: [{
value: '男',
label: '男'
}, {
value: '女',
label: '女'
}],
value: ''
}
},
mounted() {
// 獲取地理位置
var geolocation = new BMapGL.Geolocation();
geolocation.getCurrentPosition(function(r){
if(this.getStatus() == BMAP_STATUS_SUCCESS){
const province = r.address.province
const city = r.address.city
localStorage.setItem("location", province + city)
}
});
},
created() {
this.load()
},
methods: {
load() {
const username = this.user.username
if (!username) {
this.$message.error("當(dāng)前無(wú)法獲取用戶(hù)信息!")
return
}
this.request.get("/user/username/" + username).then(res => {
// console.log(res)
this.form = res.data
})
},
sign() {
const location = localStorage.getItem("location")
const username = this.user.username
this.request.post("/sign", { user: username, location: location }).then(res => {
if (res.code === '200') {
this.$message.success("打卡成功")
} else {
this.$message.error(res.msg)
}
})
},
save() {
this.request.post("/user", this.form).then(res => {
if (res.data) {
this.$message.success("保存成功")
this.load()
this.$emit('refreshUser')
} else {
this.$message.error("保存失敗")
}
})
},
// 頭像上傳
handleAvatarSuccess(res) {
// res就是頭像文件路徑
this.form.avatarUrl = res
},
}
}
</script>
<style>
.avatar-uploader {
text-align: center;
padding-bottom: 10px;
}
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 138px;
height: 138px;
line-height: 138px;
text-align: center;
}
.avatar {
width: 138px;
height: 138px;
display: block;
}
</style>五、結(jié)果展示


六、后臺(tái)管理

<template>
<div>
<div style="margin: 10px 0">
<el-input style="width: 200px" placeholder="請(qǐng)輸入名稱(chēng)" suffix-icon="el-icon-search" v-model="name"></el-input>
<el-button class="ml-5" type="primary" @click="load">搜索</el-button>
<el-button type="warning" @click="reset">刷新</el-button>
</div>
<div style="margin: 10px 0">
<el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
<el-popconfirm
class="ml-5"
confirm-button-text='確定'
cancel-button-text='我再想想'
icon="el-icon-info"
icon-color="red"
title="您確定批量刪除這些數(shù)據(jù)嗎?"
@confirm="delBatch">
<el-button type="danger" slot="reference">批量刪除 <i class="el-icon-remove-outline"></i></el-button>
</el-popconfirm>
</div>
<el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
<el-table-column prop="user" label="用戶(hù)名稱(chēng)"></el-table-column>
<el-table-column prop="location" label="打卡位置"></el-table-column>
<el-table-column prop="time" label="打卡時(shí)間"></el-table-column>
<el-table-column prop="comment" label="備注"></el-table-column>
<el-table-column label="操作" width="180" align="center">
<template slot-scope="scope">
<el-button type="success" @click="handleEdit(scope.row)">編輯 <i class="el-icon-edit"></i></el-button>
<el-popconfirm
class="ml-5"
confirm-button-text='確定'
cancel-button-text='我再想想'
icon="el-icon-info"
icon-color="red"
title="您確定刪除嗎?"
@confirm="del(scope.row.id)"
>
<el-button type="danger" slot="reference">刪除 <i class="el-icon-remove-outline"></i></el-button>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<div style="padding: 10px 0">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pageNum"
:page-sizes="[2, 5, 10, 20]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
<el-dialog title="信息" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
<el-form label-width="140px" size="small" style="width: 85%;">
<el-form-item label="用戶(hù)名稱(chēng)">
<el-input v-model="form.user" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="打卡位置">
<el-input v-model="form.location" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="打卡時(shí)間">
<el-date-picker v-model="form.time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="選擇日期時(shí)間"></el-date-picker>
</el-form-item>
<el-form-item label="備注">
<el-input v-model="form.comment" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="save">確 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
name: "Sign",
data() {
return {
tableData: [],
total: 0,
pageNum: 1,
pageSize: 10,
name: "",
form: {},
dialogFormVisible: false,
multipleSelection: [],
user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
}
},
created() {
this.load()
},
methods: {
load() {
this.request.get("/sign/page", {
params: {
pageNum: this.pageNum,
pageSize: this.pageSize,
name: this.name,
}
}).then(res => {
this.tableData = res.data.records
this.total = res.data.total
})
},
save() {
this.request.post("/sign", this.form).then(res => {
if (res.code === '200') {
this.$message.success("保存成功")
this.dialogFormVisible = false
this.load()
} else {
this.$message.error("保存失敗")
}
})
},
handleAdd() {
this.dialogFormVisible = true
this.form = {}
this.$nextTick(() => {
if(this.$refs.img) {
this.$refs.img.clearFiles();
}
if(this.$refs.file) {
this.$refs.file.clearFiles();
}
})
},
handleEdit(row) {
this.form = JSON.parse(JSON.stringify(row))
this.dialogFormVisible = true
this.$nextTick(() => {
if(this.$refs.img) {
this.$refs.img.clearFiles();
}
if(this.$refs.file) {
this.$refs.file.clearFiles();
}
})
},
del(id) {
this.request.delete("/sign/" + id).then(res => {
if (res.code === '200') {
this.$message.success("刪除成功")
this.load()
} else {
this.$message.error("刪除失敗")
}
})
},
handleSelectionChange(val) {
console.log(val)
this.multipleSelection = val
},
delBatch() {
if (!this.multipleSelection.length) {
this.$message.error("請(qǐng)選擇需要?jiǎng)h除的數(shù)據(jù)")
return
}
let ids = this.multipleSelection.map(v => v.id) // [{}, {}, {}] => [1,2,3]
this.request.post("/sign/del/batch", ids).then(res => {
if (res.code === '200') {
this.$message.success("批量刪除成功")
this.load()
} else {
this.$message.error("批量刪除失敗")
}
})
},
reset() {
this.name = ""
this.load()
},
handleSizeChange(pageSize) {
console.log(pageSize)
this.pageSize = pageSize
this.load()
},
handleCurrentChange(pageNum) {
console.log(pageNum)
this.pageNum = pageNum
this.load()
},
handleFileUploadSuccess(res) {
this.form.file = res
},
handleImgUploadSuccess(res) {
this.form.img = res
},
download(url) {
window.open(url)
},
exp() {
window.open("http://localhost:9090/sign/export")
},
handleExcelImportSuccess() {
this.$message.success("導(dǎo)入成功")
this.load()
}
}
}
</script>
<style>
.headerBg {
background: #eee!important;
}
</style>


?小結(jié)
以上就是對(duì)Springboot集成百度地圖實(shí)現(xiàn)定位打卡功能簡(jiǎn)單的概述,更多相關(guān)Springboot 定位打卡內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Flask實(shí)現(xiàn)異步非阻塞請(qǐng)求功能實(shí)例解析
這篇文章主要介紹了Flask實(shí)現(xiàn)異步非阻塞請(qǐng)求功能實(shí)例解析,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
Spring使用@Autowired為抽象父類(lèi)注入依賴(lài)代碼實(shí)例
這篇文章主要介紹了Spring使用@Autowired為抽象父類(lèi)注入依賴(lài)代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
jpa多條件查詢(xún)重寫(xiě)Specification的toPredicate方法
這篇文章主要介紹了多條件查詢(xún)重寫(xiě)Specification的toPredicate方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
SpringCloud實(shí)現(xiàn)服務(wù)調(diào)用feign與熔斷hystrix和網(wǎng)關(guān)gateway詳細(xì)分析
這篇文章主要介紹了SpringCloud實(shí)現(xiàn)服務(wù)調(diào)用feign與熔斷hystrix和網(wǎng)關(guān)gateway,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-04-04
如何解決springboot自動(dòng)重啟問(wèn)題
這篇文章主要介紹了如何解決springboot自動(dòng)重啟問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Java項(xiàng)目中大批量數(shù)據(jù)查詢(xún)導(dǎo)致OOM的解決
本文主要介紹了Java項(xiàng)目中大批量數(shù)據(jù)查詢(xún)導(dǎo)致OOM的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
java中l(wèi)ong(Long)與int(Integer)之間的轉(zhuǎn)換方式
這篇文章主要介紹了java中l(wèi)ong(Long)與int(Integer)之間的轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
SpringBoot整合InfluxDB的詳細(xì)過(guò)程
InfluxDB是一個(gè)開(kāi)源的時(shí)間序列數(shù)據(jù)庫(kù),由Go語(yǔ)言編寫(xiě),適用于存儲(chǔ)和查詢(xún)按時(shí)間順序產(chǎn)生的數(shù)據(jù),它具有高效的數(shù)據(jù)存儲(chǔ)和查詢(xún)機(jī)制,支持高并發(fā)寫(xiě)入和查詢(xún),靈活的數(shù)據(jù)模型和強(qiáng)大的查詢(xún)語(yǔ)言,本文介紹SpringBoot整合InfluxDB的詳細(xì)過(guò)程,感興趣的朋友一起看看吧2024-12-12
MyBatis-Plus輸出完整SQL(帶參數(shù))的三種方案
當(dāng)我們使用 mybatis-plus 時(shí),可能會(huì)遇到SQL 不能直接執(zhí)行,調(diào)試也不方便的情況,那么,如何打印完整 SQL(帶參數(shù))呢?本篇文章將介紹 3 種實(shí)現(xiàn)方式,并對(duì)比它們的優(yōu)缺點(diǎn),需要的朋友可以參考下2025-02-02

