Home Web Front-end JS Tutorial Sharing examples of using Baidu Maps to implement map grids

Sharing examples of using Baidu Maps to implement map grids

Feb 06, 2018 pm 03:24 PM
map accomplish Baidu

Recently, Baidu Map is used to realize the function of real estate visualization, so the most basic function is to grid the map to realize the division of real estate in different regions; this article mainly shares an example of using Baidu Map to realize the map grid. It has a very good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.

1. Go to the open platform of Baidu Maps to apply for a secret key. Here I will post your secret key; ak=A3CklGvnFOjkAzKzay2dySgfdig0GKz4

2. Create a new simple page , below I will post my own 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"/>
 <style type="text/css">
  html {
   height: 100%
  }
  body {
   height: 100%;
   margin: 0px;
   padding: 0px
  }
  #container {
   height: 100%
  }
 </style>
 <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=A3CklGvnFOjkAzKzay2dySgfdig0GKz4"></script> 
<script type="text/javascript" src="ziroom-map.js"></script>
 </head>
 <body> 
<p id="container"></p>
 <script> 
var myMap = new ZMap("container"); </script>
 </body>
 </html>
Copy after login

3, which introduces ziroom-map.js, which is the name of our company, I will post the code, This js encapsulates Baidu's js api. If anyone wants to ask why it is encapsulated, can't it be used directly? Then my answer is: Encapsulation can combine specific businesses and maps to make the code clearer, and can persist the current map state, which is beneficial to the operation of the map.


var ZMap = function (id, center, level) {
 this.initCenter = new ZPoint(116.404, 39.915);//初始化的中心点,同时为了定义网格的中心点
 this.id = id;//p的id
 this.level = level ? level : 13;//地图级别
 this.center = center ? center : this.initCenter;//中心点
 this.map = null;//百度地图实例
 this.xgrids = [];//经线
 this.ygrids = [];//纬线
 this.beSelectBounds = {};
 this.bounds = null;//当前地图的四个顶点
 this.span = null;//当前网格的跨度
 this.init();
}
ZMap.prototype = {
 init: function () {//全局初始化
  var zMap = this;
  this.map = new BMap.Map(this.id);
  this.map.centerAndZoom(this.center.point, this.level);
  this.map.enableScrollWheelZoom();
  this.map.disableInertialDragging();
  this.map.addControl(new BMap.NavigationControl({
   anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
   type: BMAP_NAVIGATION_CONTROL_ZOOM
  })); //缩放按钮
  this.map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT, offset: new BMap.Size(80, 25)})); //比例尺
  this.map.disableDoubleClickZoom();
  this.map.setMapStyle({style: &#39;googlelite&#39;});
  this.initProperty();
  this.initGrid();
  //添加移动后的点击事件
  this.map.addEventListener("dragend", function () {
   zMap.initProperty();
   zMap.initGrid();
  });
  //添加放大或缩小时的事件
  this.map.addEventListener("zoomend", function () {
   zMap.initProperty();
   zMap.initGrid();
  });
  //设置点击事件
  this.map.addEventListener("click", function (e) {
   var point = e.point;
   //获取当前点是在哪个区块内,获取正方形的四个顶点
   var points = zMap.getGrid(point);
   //判断当前区域是否已经被选中过,如果被选中过则取消选中
   var key = &#39;&#39; + points[0].lng + points[0].lat + points[2].lng + points[2].lat;//使用两个点的坐标作为key
   if (zMap.beSelectBounds[key]) {
    zMap.map.removeOverlay(zMap.beSelectBounds[key]);
    delete zMap.beSelectBounds[key];
    return;
   }
   var polygon = new BMap.Polygon(points, {strokeColor: "red", strokeWeight: 2, strokeOpacity: 0.5});
   zMap.map.addOverlay(polygon);
   zMap.beSelectBounds[key] = polygon;
  });
 },
 initProperty: function () {//初始化当前地图的状态
  this.level = this.map.getZoom();
  this.bounds = {
   x1: this.map.getBounds().getSouthWest().lng,
   y1: this.map.getBounds().getSouthWest().lat,
   x2: this.map.getBounds().getNorthEast().lng,
   y2: this.map.getBounds().getNorthEast().lat
  };
  this.span = this.getSpan();//需要使用level属性
 },
 initGrid: function () {//初始化网格
  var zMap = this;
  //将原来的网格线先去掉
  for (var i in zMap.xgrids) {
   this.map.removeOverlay(zMap.xgrids[i]);
  }
  zMap.xgrids = [];
  for (var i in zMap.ygrids) {
   this.map.removeOverlay(zMap.ygrids[i]);
  }
  zMap.ygrids = [];
  //获取当前网格跨度
  var span = zMap.span;
  //初始化地图上的网格
  for (var i = zMap.bounds.x1 + (zMap.initCenter.point.lng - zMap.bounds.x1) % span.x - span.x; i < zMap.bounds.x2 + span.x; i += span.x) {
   var polyline = new BMap.Polyline([
    new BMap.Point(i.toFixed(6), zMap.bounds.y1),
    new BMap.Point(i.toFixed(6), zMap.bounds.y2)
   ], {strokeColor: "black", strokeWeight: 1, strokeOpacity: 0.5});
   zMap.xgrids.push(polyline);
   zMap.map.addOverlay(polyline);
  }
  for (var i = zMap.bounds.y1 + (zMap.initCenter.point.lat - zMap.bounds.y1) % span.y - span.y; i < zMap.bounds.y2 + span.y; i += span.y) {
   var polyline = new BMap.Polyline([
    new BMap.Point(zMap.bounds.x1, i.toFixed(6)),
    new BMap.Point(zMap.bounds.x2, i.toFixed(6))
   ], {strokeColor: "black", strokeWeight: 1, strokeOpacity: 0.5});
   zMap.ygrids.push(polyline);
   zMap.map.addOverlay(polyline);
  }
 },
 getSpan: function () {//获取网格的跨度
  var scale = 0.75;
  var x = 0.00064;
  for (var i = this.level; i < 19; i++) {
   x *= 2;
  }
  var y = parseFloat((scale * x).toFixed(5));
  return {x: x, y: y};
 },
 getGrid: function (point) {//返回当前点在所在区块的四个顶点
  var zMap = this;
  //先找出两条纵线坐标
  var xpoints = this.xgrids.map(function (polyline) {
   return polyline.getPath()[0].lng;
  }).filter(function (lng) {
   return Math.abs(lng - point.lng) <= zMap.span.x;
  }).sort(function (a, b) {
   return a - b;
  }).slice(0, 2);
  //再找出两条横线的坐标
  var ypoints = this.ygrids.map(function (polyline) {
   return polyline.getPath()[0].lat;
  }).filter(function (lat) {
   return Math.abs(lat - point.lat) <= zMap.span.y;
  }).sort(function (a, b) {
   return a - b;
  }).slice(0, 2);
  return [
   new BMap.Point(xpoints[0], ypoints[0]),
   new BMap.Point(xpoints[0], ypoints[1]),
   new BMap.Point(xpoints[1], ypoints[1]),
   new BMap.Point(xpoints[1], ypoints[0])
  ];
 },
 reset: function () {//重置
  this.map.reset();
 }
}
var ZPoint = function (x, y, code) {
 this.code = code;
 this.point = new BMap.Point(x, y);
}
Copy after login

Related recommendations:

Example sharing of distance calculation in PHP Baidu map development

What should I do if the react framework meets Baidu Map?

JS development uses Baidu map code organization

The above is the detailed content of Sharing examples of using Baidu Maps to implement map grids. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1661
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How to make Google Maps the default map in iPhone How to make Google Maps the default map in iPhone Apr 17, 2024 pm 07:34 PM

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

After 2 months, the humanoid robot Walker S can fold clothes After 2 months, the humanoid robot Walker S can fold clothes Apr 03, 2024 am 08:01 AM

Editor of Machine Power Report: Wu Xin The domestic version of the humanoid robot + large model team completed the operation task of complex flexible materials such as folding clothes for the first time. With the unveiling of Figure01, which integrates OpenAI's multi-modal large model, the related progress of domestic peers has been attracting attention. Just yesterday, UBTECH, China's "number one humanoid robot stock", released the first demo of the humanoid robot WalkerS that is deeply integrated with Baidu Wenxin's large model, showing some interesting new features. Now, WalkerS, blessed by Baidu Wenxin’s large model capabilities, looks like this. Like Figure01, WalkerS does not move around, but stands behind a desk to complete a series of tasks. It can follow human commands and fold clothes

Baidu Apollo releases Apollo ADFM, the world's first large model that supports L4 autonomous driving Baidu Apollo releases Apollo ADFM, the world's first large model that supports L4 autonomous driving Jun 04, 2024 pm 08:01 PM

On May 15, Baidu Apollo held Apollo Day 2024 in Wuhan Baidu Luobo Automobile Robot Zhixing Valley, comprehensively demonstrating Baidu's major progress in autonomous driving over the past ten years, bringing technological leaps based on large models and a new definition of passenger safety. With the world's largest autonomous vehicle operation network, Baidu has made autonomous driving safer than human driving. Thanks to this, safer, more comfortable, green and low-carbon travel methods are turning from ideal to reality. Wang Yunpeng, vice president of Baidu Group and president of the Intelligent Driving Business Group, said on the spot: "Our original intention to build autonomous vehicles is to satisfy people's growing yearning for better travel. People's satisfaction is our driving force. Because safety, So beautiful, we are happy to see

How to add store address to Xiaohongshu map? How to fill in the store address setting? How to add store address to Xiaohongshu map? How to fill in the store address setting? Mar 29, 2024 am 09:41 AM

As Xiaohongshu becomes more and more popular among young people, more and more people choose to open stores on Xiaohongshu. Many novice sellers encounter difficulties when setting up their store address and do not know how to add the store address to the map. 1. How to add the store address to the map in Xiaohongshu? 1. First, make sure your store has a registered account on Xiaohongshu and has successfully opened a store. 2. Log in to your Xiaohongshu account, enter the store backend, and find the "Store Settings" option. 3. On the store settings page, find the "Store Address" column and click "Add Address". 4. In the address adding page that pops up, fill in the detailed address information of the store, including province, city, district, county, street, house number, etc. 5. After filling in, click the "Confirm Add" button. Xiaohongshu will provide you with the address

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

How to use at-a-glance directions on Google Maps How to use at-a-glance directions on Google Maps Jun 13, 2024 pm 09:40 PM

A year after its launch, Google Maps has launched a new feature. Once you set a route to your destination on the map, it summarizes your travel route. Once your journey begins, you can "Browse" route guidance from your phone's lock screen. You can use Google Maps to see your estimated arrival time and route. Throughout your trip, you can view navigation information on your lock screen, and by unlocking your phone, you can view navigation information without accessing Google Maps. By unlocking your phone, you can view navigation information without accessing Google Maps. By unlocking your phone, you can view navigation information without accessing Google Maps. By unlocking your phone, you can view navigation information without accessing Google Maps. By unlocking your phone, you can view navigation information without accessing Google Maps. By unlocking your phone, you can view navigation information without accessing Google Maps.

Baidu Robin Li led a team to visit PetroChina to discuss the intelligence of the oil and gas industry Baidu Robin Li led a team to visit PetroChina to discuss the intelligence of the oil and gas industry May 07, 2024 pm 06:13 PM

According to news from this site on May 7, on May 6, Robin Li, founder, chairman and CEO of Baidu, led a team to visit China National Petroleum Corporation (hereinafter referred to as "PetroChina") in Beijing and met with directors of China National Petroleum Corporation Chairman and Party Secretary Dai Houliang held talks. The two parties had in-depth exchanges on strengthening cooperation and promoting the deep integration of the energy industry with digital intelligence. PetroChina will accelerate the construction of a digital China Petroleum Corporation, strengthen cooperation with Baidu Group, promote the in-depth integration of the energy industry with digital intelligence, and make greater contributions to ensuring national energy security. Robin Li said that the "intelligent emergence" and core capabilities of understanding, generation, logic, and memory displayed by large models have opened up a broader space for imagination for the combination of cutting-edge technology and oil and gas business. Always

deepseek web version entrance deepseek official website entrance deepseek web version entrance deepseek official website entrance Feb 19, 2025 pm 04:54 PM

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

See all articles