Recently, I used Baidu map to display the address of the company. Although it is a repetitive function, I found that the code written by others before is too redundant. Based on the native code, there is no framework

Baidu map

1. If you obtain Baidu map AK

Create ak

I’m going to use * directly here, but you can use the following:

One thing to note in the browser is this Referer whitelist, which is important. A lot of people get lazy and just use *, which means all domain names are available. One problem with this is that it’s fine if you test it locally, but if you put it in a production environment, the AK will leak and be used by someone else, which can lead to quota overruns and unnecessary costs.

Our previous team did this by creating two applications, one that didn’t limit the referer whitelist, and one that limited the domain name to test and production environments (of course, you can also make a separate distinction between test and production environments).

From: Baidu Map developer registration process (obtain AK method)

Before I encountered such an error: APP service is disabled, can access etc ~~~~ generally ak does not have the correct application

2. Use

To reuse map-related stuff, we use iframe to nest map-related pages

index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <style>
    .map {
      width: 500px;
      height: 400px;
    }
    #mapFrame{
      width: 100%;
      height: 100%;
    }
  </style>
   <div style="color: chocolate; font-size: 24px;">Company Address:</div>
  <div class="map">
    <iframe src="./commonMap.html" frameborder="0" id="mapFrame"></iframe>
  </div>
</head>
<body>
  <script>
    window.onload = function () {
       // Map markers
      var msg = {
        name: Shenzhen Lehang World Technology Co., LTD..address: Address: 18th Floor, Building B1, Nanshan Zhiyuan, 1001 Xueyuan Avenue, Nanshan District, Shenzhen city, Guangdong Province.position: {
          lng: "114.009587".lat: "22.600399"}};var mapFrame = document.querySelector('#mapFrame');
      mapFrame.contentWindow.postMessage(JSON.stringify(msg));
    }
  </script>
</body>
</html>
Copy the code

commonMap.html

<! DOCTYPEhtml>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>The map shows</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="Initial - scale = 1.0, the user - the scalable = no">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <style>
    body.html.#container {
        overflow: hidden;
        width: 100%;
        height: 100%;
        margin: 0;
        font-family: Microsoft Yahei;
    }
    </style>
    <script src="Https://api.map.baidu.com/api?type=webgl&v=1.0&ak= I ak"></script>
</head>
<body>
    <div id="container"></div>
</body>
</html>
<script>
  const map = new BMapGL.Map('container');
  window.addEventListener('message'.function (e) {
    // Map instance initialization
    createMap(e.data)
    // Set the map event
    handleMap()
    // Add controls
    handleControl()
    // Remove the bottom © 2021 BidU-GS (2021)6026 - A test zi 1100930 etc
    setTimeout(function () {
      document.querySelector('.BMap_cpyCtrl.anchorBL').style.cssText = 'display:none; ';
    }, 1000)},false);

  // Map instance initialization
  function createMap(msg) {
    const { position: { lng, lat }, name, address } = JSON.parse(msg)
    // Create the corresponding latitude and longitude
    const point = new BMapGL.Point(lng, lat);
    map.centerAndZoom(point, 16);
    // Add the corresponding text description (name + address)
    const addressMsg = `<span style="color:grey">${address}</span>`
    const nameMsg = {
      width: 400.height: 50.title: `<span style="weight:bold">${name}</span>`
    }
    const infoWindow = new BMapGL.InfoWindow(addressMsg, nameMsg);
    map.openInfoWindow(infoWindow, point);
    // Add a corresponding destination icon
    const marker = new BMapGL.Marker(point, {
      icon: new BMapGL.Icon("./location.png".new BMapGL.Size(32.32), {
        imageOffset: new BMapGL.Size(0.0)})}); map.addOverlay(marker); }// Set the map event
  function handleMap() {
    map.enableScrollWheelZoom(); // Mouse scroll moves
    map.enableKeyboard() // Use the up and down keys to move
  }

  // Add controls
  function handleControl() {
    var scaleCtrl = new BMapGL.ScaleControl();  // Add scale control - the default is meters
    // scaleCtrl.setUnit(BMAP_UNIT_IMPERIAL); It can be switched to feet
    map.addControl(scaleCtrl);
    var zoomCtrl = new BMapGL.ZoomControl();  // Add a scale control
    map.addControl(zoomCtrl);
  }
</script>
Copy the code

The commonMap component ignores the ability to write labels and styles directly on title and content, as well as the default functions such as double click to enlarge and drag

3. Run the page

Because window.postMessage is used for parameter passing, you need to simulate the server environment

Please install live Server in vscode

I’m gonna go ahead and right click

Since we don’t have a domain name and run it directly, there will be cross-domain, where the Live Server plug-in can be used to simulate the Server environment

4. Demonstrate

I wrote it from a random company

5. My official account

I feel that I have no talent for code, I can only be diligent ~ recently I have been writing some interesting stories about climbing and falling in the front end industry and life to make myself happier and pursue progress in life and work

Fans too little, please pay attention to me ~ public number: program yuan love talk