本课程基于百度地图技术,由基础入门开始到应用实战,适合零基础入门学习。将企业项目中地图相关常见应用场景的落地实战,包括有地图找房、轻骑小程序、金运物流等。同时讲了基于Netty实现高性能的web服务,来处理高并发的问题。还讲解了海量坐标数据处理解决方案。
学完本课程能够收获:百度地图技术的应用、轨迹类场景、路线规划场景,电子围栏场景的开发,增长开发经验。
百度地图提供了各种平台的SDK,地址:百度地图开放平台 | 百度地图API SDK | 地图开发 如下:
创建地图的基本步骤如下:
编写HTML页面的基础代码
引入百度地图API文件
初始化地图逻辑以及设置各种参数
参考官方文档:
jspopularGL | 百度地图API SDK
页面效果:
Baidu Map
Baidu Map - 覆盖物
Baidu Map - 事件
Baidu Map - 变更地图样式
Baidu Map - 搜索兴趣点
Baidu Map - 圆形范围搜索兴趣点
MapV开发文档
地址: web服务API | 百度地图API SDK
package cn.itcast.baidumap;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import org.junit.Test;
public class TestBaiduWebApi {
private String ak = "64Ut0Peo2Dsb1l43FRl1nReM0tBdpE3L";
/**
* 测试坐标转换服务
*/
@Test
public void testGeoconv() {
String url = "https://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.575429778924&from=1&to=5&ak={}";
url = StrUtil.format(url, ak);
//发起get请求
String body = HttpRequest.get(url).execute().body();
System.out.println(body);
}
/**
* 测试IP定位服务
*/
@Test
public void testLocation(){
String url = "https://api.map.baidu.com/location/ip?ak={}&ip=140.206.149.83&coor=bd09ll";
url = StrUtil.format(url, ak);
//发起get请求
String body = HttpRequest.get(url).execute().body();
System.out.println(body);
}
/**
* 测试地点输入提示服务
*/
@Test
public void testSuggestion(){
String url = "https://api.map.baidu.com/place/v2/suggestion?query=清华大®ion=北京&city_limit=true&output=json&ak={}";
url = StrUtil.format(url, ak);
//发起get请求
String body = HttpRequest.get(url).execute().body();
System.out.println(body);
}
/**
* 测试路线规划
*/
@Test
public void testDriving(){
String url = "https://api.map.baidu.com/direction/v2/driving?alternatives=1&origin=40.009645,116.333374&destination=39.937016,116.453576&ak={}";
url = StrUtil.format(url, ak);
//发起get请求
String body = HttpRequest.get(url).execute().body();
System.out.println(body);
}
}
GitHub - huiyan-fe/BMapGLLib: 百度地图JSAPI GL版JavaScript开源工具库
地图找房 - 地图搜索
#拉取镜像
docker pull mongo:4.0.3
#创建容器
docker create --name mongodb-server -p 27017:27017 -v mongodb-data:/data/db mongo:4.0.3 --auth
#启动容器
docker start mongodb-server
#进入容器
docker exec -it mongodb-server /bin/bash
#进入admin数据库
mongo
use admin
#添加管理员,其拥有管理用户和角色的权限
db.createUser({ user: 'root', pwd: 'root', roles: [ { role: "root", db: "admin" } ] })
#退出后进行认证
#进行认证
mongo -u "root" -p "root" --authenticationDatabase "admin"
#通过admin添加普通用户
use admin
db.createUser({ user: 'house', pwd: 'oudqBFGmGY8pU6WS', roles: [ { role: "readWrite", db: "house" } ] });
#通过tanhua用户登录进行测试
mongo -u "house" -p "oudqBFGmGY8pU6WS" --authenticationDatabase "admin"
#发现可以正常进入控制台进行操作
package cn.itcast.baidumap.wm;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.baidumap.pojo.BusinessCircle;
import cn.itcast.baidumap.pojo.Community;
import cn.itcast.baidumap.pojo.District;
import cn.itcast.baidumap.util.BaiduApiUtil;
import org.bson.types.ObjectId;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
public class CommunityPageProcessor implements PageProcessor {
private District district;
private BusinessCircle businessCircle;
private MongoTemplate mongoTemplate;
public CommunityPageProcessor(District district, BusinessCircle businessCircle, MongoTemplate mongoTemplate) {
this.district = district;
this.businessCircle = businessCircle;
this.mongoTemplate = mongoTemplate;
}
@Override
public void process(Page page) {
Document html = Jsoup.parse(page.getRawText()); //解析html
Elements elements = html.select("div.info div.title a"); //获取数据链接对象
for (Element element : elements) {
Community community = new Community();
community.setId(ObjectId.get());
community.setName(element.text()); //获取小区名称
community.setLianJiaUrl(element.attr("href")); //获取链接
community.setBusinessCircleCode(this.businessCircle.getCode());
community.setDistrictCode(this.district.getCode());
String address = StrUtil.format("上海市{}{}{}",
this.district.getName(),
this.businessCircle.getName(),
community.getName());
//通过百度地图api查询地址对应的经纬度
double[] coordinate = BaiduApiUtil.queryCoordinateByAddress(address);
community.setLocation(new GeoJsonPoint(coordinate[0], coordinate[1]));
this.mongoTemplate.save(community);
}
//设置分页
String pageData = html.select("div[page-data]").attr("page-data");
JSONObject pageJson = JSONUtil.parseObj(pageData);
Integer totalPage = pageJson.getInt("totalPage", 1);
Integer curPage = pageJson.getInt("curPage", 1);
if (curPage < totalPage) {
String url = businessCircle.getLianJiaUrl() + "pg" + (curPage + 1);
page.addTargetRequest(url);
}
}
@Override
public Site getSite() {
//失败重试3次,每次抓取休息200毫秒
return Site.me().setRetryTimes(3).setSleepTime(200);
}
}
POJO类、Vo类
Controller
package cn.itcast.baidumap.controller;
import cn.itcast.baidumap.service.HouseSearchService;
import cn.itcast.baidumap.vo.HouseResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequestMapping("house/search")
@RestController
public class HouseSearchController {
@Autowired
private HouseSearchService houseSearchService;
/**
* 地图找房搜索服务
*
* @param maxLongitude 最大经度
* @param minLongitude 最小经度
* @param maxLatitude 最大纬度
* @param minLatitude 最小纬度
* @param zoom 地图缩放比例值
* @return
*/
@GetMapping
public List search(@RequestParam("maxLongitude") Double maxLongitude,
@RequestParam("minLongitude") Double minLongitude,
@RequestParam("maxLatitude") Double maxLatitude,
@RequestParam("minLatitude") Double minLatitude,
@RequestParam("zoom") Double zoom) {
return this.houseSearchService.search(maxLongitude, minLongitude, maxLatitude, minLatitude, zoom);
}
}
Service
package cn.itcast.baidumap.service;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.itcast.baidumap.pojo.BusinessCircle;
import cn.itcast.baidumap.pojo.Community;
import cn.itcast.baidumap.pojo.District;
import cn.itcast.baidumap.pojo.House;
import cn.itcast.baidumap.vo.HouseResultVo;
import com.mongodb.internal.operation.AggregateOperation;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Box;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Service
public class HouseSearchService {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 地图找房搜索服务
*
* @param maxLongitude 最大经度
* @param minLongitude 最小经度
* @param maxLatitude 最大纬度
* @param minLatitude 最小纬度
* @param zoom 地图缩放比例值
* @return
*/
public List search(Double maxLongitude,
Double minLongitude,
Double maxLatitude,
Double minLatitude,
Double zoom) {
//收集聚合查询条件
List operationList = new ArrayList<>();
//在可视范围内搜索
Box box = new Box(new double[]{maxLongitude, maxLatitude}, new double[]{minLongitude, minLatitude});
MatchOperation matchOperation = Aggregation.match
(Criteria.where("location").within(box));
operationList.add(matchOperation);
int type;
GroupOperation groupOperation;
//根据地图的缩放比例进行分组
if (zoom < 13.5) { //2公里以上
//按照行政区分组
groupOperation = Aggregation.group("districtCode");
type = 1;
} else if (zoom < 15.5) { //200米以上
//按照商圈分组
groupOperation = Aggregation.group("businessCircleCode");
type = 2;
} else { //200以下
//按照小区分组
groupOperation = Aggregation.group("communityId");
type = 3;
}
groupOperation = groupOperation.count().as("total")
.avg("price").as("price");
operationList.add(groupOperation);
//生成最终的聚合条件
Aggregation aggregation = Aggregation.newAggregation(operationList);
//执行查询
AggregationResults aggregationResults = this.mongoTemplate.aggregate(aggregation, House.class, HouseResultVo.class);
List houseResultVoList = aggregationResults.getMappedResults();
if (CollUtil.isEmpty(houseResultVoList)) {
return Collections.emptyList();
}
//填充数据
switch (type) {
case 1: {
//查询行政区数据
for (HouseResultVo houseResultVo : houseResultVoList) {
District district = this.queryDistrictByCode(Convert.toInt(houseResultVo.getCode()));
houseResultVo.setName(district.getName());
houseResultVo.setLongitude(district.getLocation().getX());
houseResultVo.setLatitude(district.getLocation().getY());
//价格保留2位小数
houseResultVo.setPrice(NumberUtil.roundStr(houseResultVo.getPrice(), 2));
}
break;
}
case 2: {
//查询商圈数据
for (HouseResultVo houseResultVo : houseResultVoList) {
BusinessCircle businessCircle = this.queryBusinessCircleByCode(Convert.toInt(houseResultVo.getCode()));
houseResultVo.setName(businessCircle.getName());
houseResultVo.setLongitude(businessCircle.getLocation().getX());
houseResultVo.setLatitude(businessCircle.getLocation().getY());
//价格保留2位小数
houseResultVo.setPrice(NumberUtil.roundStr(houseResultVo.getPrice(), 2));
}
break;
}
case 3: {
//查询小区数据
for (HouseResultVo houseResultVo : houseResultVoList) {
Community community = this.queryCommunityById(new ObjectId(houseResultVo.getCode()));
houseResultVo.setName(community.getName());
houseResultVo.setLongitude(community.getLocation().getX());
houseResultVo.setLatitude(community.getLocation().getY());
//价格保留2位小数
houseResultVo.setPrice(NumberUtil.roundStr(houseResultVo.getPrice(), 2));
}
break;
}
default: {
return Collections.emptyList();
}
}
return houseResultVoList;
}
/**
* 根据code查询行政区数据
*
* @param code
* @return
*/
private District queryDistrictByCode(Integer code) {
Query query = Query.query(Criteria.where("code").is(code));
return this.mongoTemplate.findOne(query, District.class);
}
/**
* 根据code查询商圈数据
*
* @param code
* @return
*/
private BusinessCircle queryBusinessCircleByCode(Integer code) {
Query query = Query.query(Criteria.where("code").is(code));
return this.mongoTemplate.findOne(query, BusinessCircle.class);
}
/**
* 根据code查询小区数据
*
* @return
*/
private Community queryCommunityById(ObjectId id) {
return this.mongoTemplate.findById(id, Community.class);
}
}
非常感谢您阅读到这里,如果这篇文章对您有帮助,希望能留下您的点赞 关注 收藏 评论感谢支持!!!