一. 项目需求(举例)
寻主功能需要推送离用户最近的线下门店,系统需要将用户的输入的地址解析为经纬度。再通过经纬度计算哪一家店铺离用户地址最近。
实现地址输入提示,手动输入的地址不完整。
二. 百度地图开发平台
百度地图提供了很多开发的api,方便开发者接入到自己应用中。我们根据用户注册的地址,在百度地图进行标注,方便系统管理员管理
主站地址:http://lbsyun.baidu.com/
注册成功申请成为开发者后,创建应用-申请AK
1 2 3 4
| 应用名称:项目名 应用类型:浏览器端 启用服务:全选,特别是逆地址 白名单:* - 表示所有网址都可以访问
|
测试地图功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";font-size:14px;} #l-map{height:300px;width:100%;} #r-result{width:100%;} </style> <script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=LSNHTIDvIKtkv7UgAUKfStSz4QU74osS"></script> <title>关键字输入提示词条</title> </head> <body> <div id="l-map"></div> <div id="r-result">请输入:<input type="text" id="suggestId" size="20" value="百度" style="width:150px;" /></div> <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div> </body> </html> <script type="text/javascript"> function G(id) { return document.getElementById(id); }
var map = new BMap.Map("l-map");
var ac = new BMap.Autocomplete( {"input" : "suggestId" ,"location" : map });
ac.addEventListener("onhighlight", function(e) { var str = ""; var _value = e.fromitem.value; var value = ""; if (e.fromitem.index > -1) { value = _value.province + _value.city + _value.district + _value.street + _value.business; } str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
value = ""; if (e.toitem.index > -1) { _value = e.toitem.value; value = _value.province + _value.city + _value.district + _value.street + _value.business; } str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value; G("searchResultPanel").innerHTML = str; });
var myValue; ac.addEventListener("onconfirm", function(e) { var _value = e.item.value; myValue = _value.province + _value.city + _value.district + _value.street + _value.business; G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
setPlace(); });
function setPlace(){ map.clearOverlays(); function myFun(){ var pp = local.getResults().getPoi(0).point; map.centerAndZoom(pp, 18); map.addOverlay(new BMap.Marker(pp)); } var local = new BMap.LocalSearch(map, { onSearchComplete: myFun }); local.search(myValue); } </script>
|
三. vue集成百度地图api
1. 安装百度地图(在当前项目路径下安装)
1
| npm install --save vue-baidu-map
|
2. 全局引入百度地图
1 2 3 4 5 6 7 8
| 在main.js中引入:
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, { ak: '4RWmQlKQkGgdOUuDqaVbkjBg2IY3sjh0' })
|
3. 地图展示框
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <el-form-item prop="address" label="店铺地址"> <el-input type="text" v-model="shop.address" auto-complete="off" placeholder="请输入地址!"></el-input> <el-button size="small" type="primary" @click="selectAddress">选择</el-button> </el-form-item>
<!--百度地图--> <el-dialog title="选择地址" :visible.sync="dialogVisable" width="30%"> <baidu-map :center="{lng: 104.06, lat: 30.67}" :zoom="11"> <bm-view class="map"></bm-view> <bm-control :offset="{width: '10px', height: '10px'}"> <bm-auto-complete v-model="keyword" :sugStyle="{zIndex: 2100}"> <div style="margin-bottom:10px"> <input id="searchInput" type="text" placeholder="请输入关键字" class="searchinput"/> <el-button type="success" @click="selectAddressConfirm">确定</el-button> </div> </bm-auto-complete> </bm-control> <bm-local-search :keyword="keyword" :auto-viewport="true" ></bm-local-search> </baidu-map> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisable=false">取 消</el-button> <el-button type="primary" @click="selectAddressConfirm">确 定</el-button> </span> </el-dialog>
|
4. 业务代码
1 2 3 4 5 6 7 8 9 10 11
| selectAddressConfirm() { var searchInputV = document.getElementById("searchInput").value; this.shop.address = searchInputV; this.dialogVisable = false; }, selectAddress() { this.dialogVisable = true; },
|
四. HTML页面输入地址自动提示
1 2 3 4 5 6 7 8
| <!-- 引入百度地图 --> <script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=LSNHTIDvIKtkv7UgAUKfStSz4QU74osS"></script>
<!-- 引入vue和axios --> <script src="js/plugins/vue/dist/vue.js"></script> <script src="js/plugins/axios/dist/axios.js"></script> <!-- axios全局配置 --> <script src="js/common.js"></script>
|
引入js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| <script type="text/javascript"> function G(id) { return document.getElementById(id); }
var map = new BMap.Map("");
var ac = new BMap.Autocomplete( { "input": "suggestId" , "location": map });
ac.addEventListener("onhighlight", function (e) { var str = ""; var _value = e.fromitem.value; var value = ""; if (e.fromitem.index > -1) { value = _value.province + _value.city + _value.district + _value.street + _value.business; } str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
value = ""; if (e.toitem.index > -1) { _value = e.toitem.value; value = _value.province + _value.city + _value.district + _value.street + _value.business; } str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value; });
var myValue; ac.addEventListener("onconfirm", function (e) { var _value = e.item.value; myValue = _value.province + _value.city + _value.district + _value.street + _value.business; vue.searchMasterMsg.address = myValue; setPlace(); });
function setPlace() { map.clearOverlays(); function myFun() { var pp = local.getResults().getPoi(0).point; map.centerAndZoom(pp, 18); map.addOverlay(new BMap.Marker(pp)); }
var local = new BMap.LocalSearch(map, { onSearchComplete: myFun }); local.search(myValue); } </script>
|
输入框定义suggestId
1 2 3 4 5 6 7 8 9
| <div class="am-form-group"> <label for="suggestId" class="am-form-label">地址</label> <div class="am-form-content"> <input type="text" id="suggestId" v-model="searchMasterMsg.address" placeholder="请输入地址"> </div> </div> <div class="info-btn"> <div class="am-btn am-btn-danger" @click="publish">发布</div> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| publish() { if (this.searchMasterMsg.gender) { this.searchMasterMsg.gender = parseInt(this.searchMasterMsg.gender); } this.$http.post("/searchMasterMsg/publish", this.searchMasterMsg).then(result => { result = result.data; if (result.success) { alert("发布成功!"); location.href = "/index.html"; } else { alert(result.msg); } }).catch(res => { alert("系统错误"); }) }
|
addEventListener方法中添加一句代码,这样地址才能传递到后端
vue.searchMasterMsg.address = myValue;
要注释点G(“searchResultPanel”),这个是用来显示地图的,没有这个id属性
vue挂在实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| const vue = new Vue({ el: "#myDiv", data() { return { loginInfo: null, searchMasterMsg: { name: '小七', price: 10, age: 3, gender: 1, coatColor: '黑色', resources: null, petType: 1, address: null, title: '二哈寻主' } } }, methods: { publish() { if (this.searchMasterMsg.gender) { this.searchMasterMsg.gender = parseInt(this.searchMasterMsg.gender); } this.$http.post("/searchMasterMsg/publish", this.searchMasterMsg).then(result => { result = result.data; if (result.success) { alert("发布成功!"); location.href = "/index.html"; } else { alert(result.msg); } }).catch(res => { alert("系统错误"); }) } }, mounted() { let loginInfo = localStorage.getItem("loginInfo"); if (loginInfo) { this.loginInfo = JSON.parse(loginInfo); } }
});
|
五. 工具类
1. 解析地址经纬度
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package io.coderyeah.basic.util;
import lombok.Data;
@Data public class Point { private Double lng; private Double lat; }
|
2. 位置工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| package io.coderyeah.basic.util;
import io.coderyeah.org.domain.Shop;
import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List;
public class DistanceUtils {
public static Point getPoint(String address) { String Application_ID = "PQ9FAt6qg7taDWj6LLABYO7u6bSETXhD"; try { String sCurrentLine; String sTotalString; sCurrentLine = ""; sTotalString = ""; InputStream l_urlStream; URL l_url = new URL("http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + Application_ID + "&callback=showLocation"); HttpURLConnection l_connection = (HttpURLConnection) l_url.openConnection(); l_connection.connect(); l_urlStream = l_connection.getInputStream(); java.io.BufferedReader l_reader = new java.io.BufferedReader(new InputStreamReader(l_urlStream)); String str = l_reader.readLine(); System.out.println(str);
String s = "," + "\"" + "lat" + "\"" + ":"; String strs[] = str.split(s, 2); String s1 = "\"" + "lng" + "\"" + ":"; String a[] = strs[0].split(s1, 2); s1 = "}" + "," + "\""; String a1[] = strs[1].split(s1, 2);
Point point = new Point(); point.setLng(Double.valueOf(a[1])); point.setLat(Double.valueOf(a1[0])); return point; } catch (Exception e) { e.printStackTrace(); return null; } }
private static final double EARTH_RADIUS = 6378137;
private static double rad(double d) { return d * Math.PI / 180.0; }
public static double getDistance(Point point1, Point point2) { double radLat1 = rad(point1.getLat()); double radLat2 = rad(point2.getLat()); double a = radLat1 - radLat2; double b = rad(point1.getLng()) - rad(point2.getLng()); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000) / 10000; return s; }
public static Shop getNearestShop(Point point, List<Shop> shops) {
Shop shop = shops.get(0); double distance = getDistance(point, getPoint(shops.get(0).getAddress())); double minDistance = distance; if (shops.size() > 1) { for (int i = 1; i < shops.size(); i++) { double distanceTmp = getDistance(point, getPoint(shops.get(i).getAddress())); if (distanceTmp < minDistance) { shop = shops.get(i); minDistance = distanceTmp; } } } if (minDistance > 50000) { return null; } return shop; }
public static void main(String[] args) { System.out.println(getPoint("成都市天府广场")); } }
|
3. 业务代码(示例)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| package io.coderyeah.search.service.impl;
@Service @Slf4j public class SearchMasterMsgServiceImpl extends ServiceImpl<SearchMasterMsgMapper, SearchMasterMsg> implements SearchMasterMsgService { @Autowired private EmployeeMapper employeeMapper; @Autowired private UserMapper userMapper; @Resource private SearchMasterMsgMapper searchMasterMsgMapper; @Autowired private BaiduAiAuditService baiduAiAuditService; @Resource private SearchMasterMsgAuditLogMapper logMapper; @Resource private ShopMapper shopMapper;
@Transactional @Override public Result publish(SearchMasterMsg searchMasterMsg, HttpServletRequest req) { if (StrUtil.isBlank(searchMasterMsg.getAddress()) || StrUtil.isBlank(searchMasterMsg.getName())) { return Result.fail("参数错误"); } LoginInfo loginInfo = LoginContext.getLoginInfo(req); assert loginInfo != null; User user = userMapper.selectOne(new LambdaQueryWrapper<User>() .eq(User::getLogininfoId, loginInfo.getId())); searchMasterMsg.setUserId(user.getId()); searchMasterMsgMapper.insert(searchMasterMsg); final Boolean bool1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle() + searchMasterMsg.getCoatColor()); final Boolean bool2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources()); final SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog(); log.setMsgId(searchMasterMsg.getId()); if (bool1 && bool2) { searchMasterMsg.setState(1); final List<Shop> shops = shopMapper.selectList(new LambdaUpdateWrapper<>()); final Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress()); final Shop nearestShop = DistanceUtils.getNearestShop(point, shops); if (nearestShop != null) { searchMasterMsg.setState(2); searchMasterMsg.setShopId(nearestShop.getId()); searchMasterMsgMapper.updateById(searchMasterMsg); final Employee employee = employeeMapper.selectOne(new LambdaUpdateWrapper<Employee>().eq(Employee::getShopId, nearestShop.getId()));
System.out.println("您有新的订单啦!请前往" + searchMasterMsg.getAddress() + "完成收购!"); } else { searchMasterMsg.setState(3); searchMasterMsgMapper.updateById(searchMasterMsg); } log.setState(1); log.setNote("AI审核通过"); logMapper.insert(log); } else { log.setState(0); log.setNote("AI审核未通过"); logMapper.insert(log); searchMasterMsgMapper.deleteById(searchMasterMsg.getId());
return Result.fail("发布失败,请修改信息后再次提交"); } return Result.success("发布成功"); } }
|