当前位置:网站首页>Examples of map search
Examples of map search
2022-07-24 12:08:00 【Fantasia of the cat】
1. Functional specifications :
- In the housing information website , In order to facilitate users to find housing , Launched the function of finding houses on the map , Housing data display is more intuitive .
- for example : Chain home : Shanghai map looking for a room _ Shanghai community map _ Shanghai real estate map ( Shanghai Chain Home )


BMapGLLib:
- BMapGLLib It's based on Baidu map JSAPI GL Version of JavaScript Open source tool library .
- Code address :GitHub - huiyan-fe/BMapGLLib: Baidu Maps JSAPI GL edition JavaScript Open source tool library

Static page :

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title> Map for a room - Map search </title>
<style type="text/css">
html {
height: 100%
}
body {
height: 100%;
margin: 0px;
padding: 0px
}
#container {
height: 100%
}
.district {
width: 84px;
height: 84px;
line-height: 16px;
font-size: 12px;
display: flex;
flex-direction: column;
justify-content: center;
border: 1px solid transparent;
border-radius: 50%;
overflow: hidden;
text-align: center;
font-family: PingFangSC-Semibold;
color: #fff;
background: #00ae66 !important;
box-sizing: border-box;
}
.district i {
font-size: 12px;
color: hsla(0, 0%, 100%, .7);
line-height: 12px;
margin-top: 4px;
font-style: normal;
}
#platform > div > div > div {
background: none !important;
}
</style>
<script type="text/javascript" src="jquery-3.6.0.min.js"></script>
<script type="text/javascript"
src="http://api.map.baidu.com/api?v=1.0&type=webgl&ak=XdBGuSs0p90SNRM3dtpGGbvEygzfQyte"></script>
<script src="http://mapopen.bj.bcebos.com/github/BMapGLLib/RichMarker/src/RichMarker.min.js"></script>
</head>
<body>
<div id="container"></div>
<script type="application/javascript">
function showInfo(map) {
let bound = map.getBounds(); // Visual range rectangular coordinates , among sw Represents the southwest corner of the rectangular area , Parameters ne Represents the northeast corner of the rectangular area
let zoom = map.getZoom(); // Zoom level
console.log(bound);
// $.ajax({
// url: "/house/search",
// data: {
// maxLongitude: bound.ne.lng,
// minLongitude: bound.sw.lng,
// maxLatitude: bound.ne.lat,
// minLatitude: bound.sw.lat,
// zoom: zoom
// },
// success: function (data) {
// showMapMarker(data, map);
// }
// });
// The test results :
let data = [{"name":" Xuhui ","price":"1028.43","total":"6584","longitude":121.43676,"latitude":31.18831},{"name":" Huangpu ","price":"1016.19","total":"7374","longitude":121.49295,"latitude":31.22337},{"name":" Changning ","price":"1008.34","total":"4380","longitude":121.42462,"latitude":31.22036},{"name":" Jing'an ","price":"1005.34","total":"8077","longitude":121.4444,"latitude":31.22884},{"name":" Putuo ","price":"1026.14","total":"5176","longitude":121.39703,"latitude":31.24951},{"name":" jinshan ","price":"1099.67","total":"6","longitude":121.34164,"latitude":30.74163},{"name":" Songjiang ","price":"1017.71","total":"14","longitude":121.22879,"latitude":31.03222},{"name":" Qingpu ","price":"1038.11","total":"751","longitude":121.12417,"latitude":31.14974},{"name":" Fengxian ","price":"1108.63","total":"35","longitude":121.47412,"latitude":30.9179},{"name":" In the pudong new area ","price":"1030.22","total":"8294","longitude":121.5447,"latitude":31.22249},{"name":" Jiading ","price":"1041.45","total":"1620","longitude":121.2655,"latitude":31.37473},{"name":" baoshan ","price":"1050.65","total":"102","longitude":121.4891,"latitude":31.4045},{"name":" Minhang ","price":"1027.15","total":"941","longitude":121.38162,"latitude":31.11246},{"name":" Yangpu ","price":"1007.78","total":"2747","longitude":121.526,"latitude":31.2595},{"name":" Hongkou ","price":"1025.81","total":"4187","longitude":121.48162,"latitude":31.27788}];
showMapMarker(data, map);
}
// Show coverings
function showMapMarker(data, map) {
for (let vo of data) {
let html = "<div class=\"district\">" + vo.name + "<span>" + vo.price + " ten thousand </span><i>" + vo.total + " set </i></div>";
let marker = new BMapGLLib.RichMarker(html, new BMapGL.Point(vo.longitude, vo.latitude));
map.addOverlay(marker);
}
}
// Remove the cover
function clearMapMarker(map) {
let markers = map.getOverlays(); // Get all the covers on the map
for (let marker of markers) { // Cycle to delete
map.removeOverlay(marker);
}
}
$(function () {
// Map default location , Shanghai
let defaultX = 121.48130241985999;
let defaultY = 31.235156971414239;
let defaultZoom = 12; // Default zoom scale
let map = new BMapGL.Map("container"); // Create a map instance
let point = new BMapGL.Point(defaultX, defaultY); // Create point coordinates
map.centerAndZoom(point, defaultZoom); // Initialize map , Set center point coordinates and map level
map.enableScrollWheelZoom(true); // Turn on mouse wheel zoom
// Show scale
map.addControl(new BMapGL.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT}));
map.addEventListener("dragstart", () => { // Drag start event
clearMapMarker(map)
});
map.addEventListener("dragend", () => { // Drag the end event
showInfo(map)
});
map.addEventListener("zoomstart", () => { // Zoom start event
clearMapMarker(map)
});
map.addEventListener("zoomend", () => { // Zoom end event
showInfo(map)
});
// Initial display data
showInfo(map);
});
</script>
</body>
</html>build MongoDB Environmental Science :

application.properties Configuration in file :
spring.application.name = itcast-baidumap
server.port = 8899
#springboot MongoDB To configure
spring.data.mongodb.username=house
spring.data.mongodb.password=********
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=house
spring.data.mongodb.port=27017
spring.data.mongodb.host=192.168.31.81
spring.data.mongodb.auto-index-creation=trueStructural data :
For data authenticity , We grab some community data from the Internet , The location data of the community can be accessed through Baidu map API data

Take Shanghai as an example , Its have 16 Administrative districts
The constructed data is as follows :

Business district data is a sub classification of administrative regions :

After the construction is completed 198 Data

Community data capture online data .
After grabbing , share 20510 Data ( It is recommended to use the data provided , No need to crawl again )

Because the housing data only shows the number , So no more data fetching , Construct according to the cell data
Each cell is randomly constructed 1~20 A list of houses
The final construction is 106094 Data .

MongoDB The aggregation operation of :
- MongoDB The aggregation operation of is completed in the form of pipeline , After one pipeline is processed, the result is transferred to the next pipeline for processing
- Common aggregation operations are :

MongoDB The aggregation operator for :

Implement search :
The key points to realize search :
The rectangular search range can be determined by the coordinates of the diagonal of the rectangle .
You need to group and aggregate queries according to different map scales , By following the Administrative Region 、 Group business district or community name , Aggregate quantity 、 Price and other data .
The response data :

pom file :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Integrate through inheritance SpringBoot-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<groupId>cn.itcast</groupId>
<artifactId>itcast-baidumap</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- A dependency version number is defined centrally -->
<properties>
<mongo.version>4.0.3</mongo.version>
<lombok.version>1.18.4</lombok.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.2</version>
</dependency>
<!--springdata about mongodb Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-core</artifactId>
<version>0.7.3</version>
</dependency>
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-extension</artifactId>
<version>0.7.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java Compile the plug-in -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>Realization 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 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;
/**
* @Description:
* @Author : Jerry
* @create : 2022-07-19 18:50
*/
@Service
public class HouseSearchService {
@Autowired
private MongoTemplate mongoTemplate;
/**
* Map search service
* @param maxLongitude Maximum longitude
* @param minLongitude Minimum longitude
* @param maxLatitude Maximum latitude
* @param minLatitude Minimum latitude
* @param zoom Map zoom value
* @return
*/
public List<HouseResultVo> search(Double maxLongitude,
Double minLongitude,
Double maxLatitude,
Double minLatitude,
Double zoom) {
// Collect aggregate query criteria
List<AggregationOperation> operationList = new ArrayList<>();
// Search within visual range
Box box = new Box(new double[]{maxLongitude,maxLongitude},new double[]{minLongitude,minLatitude});
MatchOperation matchOperation = Aggregation.match(Criteria.where("location").within(box));
operationList.add(matchOperation);
int type;
GroupOperation groupOperation;
// Group according to the zoom ratio of the map
if(zoom < 13.5){ //2 Km above
// Grouped by administrative districts
groupOperation = Aggregation.group("districtCode");
type = 1;
}else if(zoom < 15.5){ //200 Meters above
// Group by business district
groupOperation = Aggregation.group("businessCircleCode");
type = 2;
}else{ //200 Below meters
// Group by cell
groupOperation = Aggregation.group("communityId");
type = 3;
}
groupOperation = groupOperation.count().as("total")
.avg("price").as("price");
operationList.add(groupOperation);
// Generate the final aggregation condition
Aggregation aggregation = Aggregation.newAggregation(operationList);
// Execute the query
AggregationResults<HouseResultVo> aggregationResults = this.mongoTemplate.aggregate(aggregation, House.class, HouseResultVo.class);
List<HouseResultVo> houseResultVoList = aggregationResults.getMappedResults();
if(CollUtil.isEmpty(houseResultVoList)){
return Collections.emptyList();
}
// Fill in the data
switch (type){
case 1:{
// Query administrative region data
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());
// Keep the price to two decimal places
houseResultVo.setPrice(NumberUtil.roundStr(houseResultVo.getPrice(),2));
}
break;
}
case 2:{
// Query business district data
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());
// Keep the price to two decimal places
houseResultVo.setPrice(NumberUtil.roundStr(houseResultVo.getPrice(),2));
}
break;
}
case 3:{
// Query business district data
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());
// Keep the price to two decimal places
houseResultVo.setPrice(NumberUtil.roundStr(houseResultVo.getPrice(),2));
}
break;
}
default: return Collections.emptyList();
}
return houseResultVoList;
}
/**
* according to code Query administrative region data
* @param code
* @return
*/
private District queryDistrictByCode(Integer code){
Query query = Query.query(Criteria.where("code").is(code));
return this.mongoTemplate.findOne(query,District.class);
}
/**
* according to code Query business district data
* @param code
* @return
*/
private BusinessCircle queryBusinessCircleByCode(Integer code){
Query query = Query.query(Criteria.where("code").is(code));
return this.mongoTemplate.findOne(query,BusinessCircle.class);
}
/**
* according to code Query cell data
* @param id
* @return
*/
private Community queryCommunityById(ObjectId id){
return this.mongoTemplate.findById(id,Community.class);
}
}
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.*;
import java.util.List;
/**
* @Description:
* @Author : Jerry
* @create : 2022-07-19 18:40
*/
@RequestMapping("house/search")
@RestController
public class HouseSearchController {
@Autowired
private HouseSearchService houseSearchService;
@GetMapping
public List<HouseResultVo> 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);
}
}
Realization effect : According to the degree of zoom , Display different information about house searching .


边栏推荐
- How to eliminate the character set and sorting rules specially set for fields in MySQL tables?
- Jackson parsing JSON detailed tutorial
- [C and pointer Chapter 14] preprocessor
- [Commons beanautils topic] 005- convertutils topic
- Svn server and client installation (Chinese package) and simple use
- Top and bottom of stack
- Day4: circular structure
- 离散分布常用公式及应用场景
- Microsoft SQL Server database language and function usage (XII)
- scrapy-redis写项目备忘
猜你喜欢

Convergence rules for 4 * 4 image weights

Basic usage of GCC

C language programming code

Source code analysis sentry user behavior record implementation process

Day3: branch structure

JMeter while controller

基于ARM和FPGA的数字示波器设计——QMJ

在kuborad图形化界面中,操作Kubernetes 集群,实现mysql中的主从复制

String matching KMP

QT notes - EventFilter event filter
随机推荐
What is prescaler in STM32
Most after analyze table in PostgreSQL_ common_ Why is the elems field not filled in?
6k+ star, a deep learning code base for Xiaobai! One line of code implements all attention mechanisms!
第0章 前言和环境配置
Why is the datetime type field 8 hours earlier when I use flinkcdc to read MySQL's binlog?
QT notes - realize form adaptation
MySQL creates partition tables and automatically partitions them by day
QT notes - custom data types
AcWing 92. 递归实现指数型枚举
Detailed OSPF configuration of layer 3 switch / router [Huawei ENSP experiment]
Basic syntax of MySQL DDL and DML and DQL
SQL multi condition query cannot be implemented
Leetcode:51. queen n
JMeter while controller
Hash - 15. Sum of three numbers
Hash - 202. Happy number
[data mining engineer - written examination] sheen company in 2022
三层交换机配置MSTP协议详解【华为eNSP实验】
Use prometheus+grafana to monitor server performance in real time
Detailed explanation of MSTP protocol for layer 3 switch configuration [Huawei ENSP experiment]