Calling Baidu Map to obtain longitude and latitude in Vue

Calling Baidu Map to obtain longitude and latitude in Vue

In the project, it is necessary to obtain the latitude and longitude of the current location, or search for a location and obtain the latitude and longitude information. I use vue and the map uses Baidu Maps.

Vue calls Baidu Map to get the current longitude and latitude, and js gets the current longitude and latitude

By default, the current location latitude and longitude are automatically obtained.

js to get longitude and latitude

Drag the little red mark to get the longitude and latitude

js gets the longitude and latitude js gets the current longitude and latitude

Keyword query to obtain longitude and latitude

Preliminary preparation

First, we need to apply for a map API key from Baidu official website. Go to https://lbsyun.baidu.com/apiconsole/key and apply in Application Management, My Application.

After applying, we open the index.html file under the public file in the vue project, splice the Baidu AK value and introduce it

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=WFKACU6v7aiUdnkgtMCqdWBZC68KpUXv"></script>  

As shown above, the red area is the AK value. You can assemble your own and set the permissions to public or for the URL whitelist.

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=WFKACU6v7aiUdnkgtMCqdWBZC68KpUXv"></script>

I used elementui's pop-up windows, input boxes, and prompts. If you don't use elementui, remember to change it!

HTML Code

<template>
  <div>
    <el-dialog
      @close="clearDialog"
      :close-on-click-modal="false"
      :title="text"
      style="text-align: left"
      :visible.sync="popup"
      width="30%"
    >
      <div class="form-layer">
        <el-form label-width="100px" size="mini">
          <el-form-item label="Get location">
            <el-button type="primary" @click="fixedPos">Reposition</el-button>
          </el-form-item>
          <el-form-item label="Current latitude">
            <p>{{latitude}}</p>
          </el-form-item>
          <el-form-item label="Current longitude">
            <p>{{longitude}}</p>
          </el-form-item>
          <el-form-item>
            <div class="fac">
              <el-input v-model="keyWords" placeholder="Please enter the region" style="width: 230px;margin-right: 6px;"></el-input>
              <el-button type="primary" @click="setPlace" :disabled="!keyWords">Query</el-button>
            </div>
          </el-form-item>
        </el-form>
        <div id="map"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          v-if="type != '2'"
          @click="btnSubmit()"
          >Confirm</el-button
        >
        <el-button size="small" @click="popup = false">Cancel</el-button>
      </div>
    </el-dialog>
  </div>
</template>

JS code

<script>
  export default {
    name: "mapView",
    data() {
      return {
        map: null,
        local: null,
        mk: null,
        latitude: '',
        longitude: '',
        keyWords: ''
      };
    },
    methods: {
      // Open the pop-up window, name is the name of the pop-up window async openDialog(name) {
        this.text = name;
        this.popup = true;
        this.initMap();
      },
      // Confirm btnSubmit() {
        let key = {
          latitude: this.latitude,
          longitude: this.longitude
        }
        // Print longitude and latitude console.log(key);
        this.popup = false;
      },
      initMap() {
        this.$nextTick(() => {
          this.map = new BMap.Map("map");
          let point = new BMap.Point(116.404, 39.915);
          this.map.centerAndZoom(point, 12);
          this.map.enableScrollWheelZoom(true); // Enable mouse wheel zoom this.map.addControl(new BMap.NavigationControl());
          this.fixedPos();
        });
      },
      // Click to locate - locate to the current position fixedPos() {
        const _this = this;
        const geolocation = new BMap.Geolocation();
        this.confirmLoading = true;
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            _this.handleMarker(_this, r.point);
            let myGeo = new BMap.Geocoder();
            myGeo.getLocation(
              new BMap.Point(r.point.lng, r.point.lat),
              function (result) {
                _this.confirmLoading = false;
                if (result) {
                  _this.latitude = result.point.lat;
                  _this.longitude = result.point.lng;
                }
              }
            );
          } else {
            _this.$message.error("failed" + this.getStatus());
          }
        });
      },
      // Search address setPlace() {
        this.local = new BMap.LocalSearch(this.map, {
          onSearchComplete: this.searchPlace,
        });
        this.local.search(this.keyWords);
      },
      searchPlace() {
        if (this.local.getResults() != undefined) {
          this.map.clearOverlays(); //Clear all overlays on the mapif (this.local.getResults().getPoi(0)) {
            let point = this.local.getResults().getPoi(0).point; //Get the first smart search result this.map.centerAndZoom(point, 18);
            this.handleMarker(this, point);
            console.log("Longitude: " + point.lng + "--" + "Latitude" + point.lat);
            this.latitude = point.lat;
            this.longitude = point.lng;
          } else {
            this.$message.error("No location matched!");
          }
        } else {
          this.$message.error("No search results found!");
        }
      },
      // Set the mark handleMarker(obj, point) {
        let that = this;
        obj.mk = new BMap.Marker(point);
        obj.map.addOverlay(obj.mk);
        obj.mk.enableDragging(); // draggable obj.mk.addEventListener("dragend", function (e) {
          // Listen for the dragging of the annotation and get the longitude and latitude after the drag that.latitude = e.point.lat;
          that.longitude = e.point.lng;
        });
        obj.map.panTo(point);
      },
    }
  };
</script>

CSS Code

<style scoped>
  .form-layer {
    width: 100%;
  }
  #map {
    margin-top: 30px;
    width: 100%;
    height: 300px;
    border: 1px solid gray;
    box-sizing: border-box;
    overflow: hidden;
  }
  /deep/ .el-dialog {
    min-width: 550px;
  }
  /deep/ .el-dialog__body {
    padding: 10px;
  }
</style>

Complete code

<template>
  <div>
    <el-dialog
      @close="clearDialog"
      :close-on-click-modal="false"
      :title="text"
      style="text-align: left"
      :visible.sync="popup"
      width="30%"
    >
      <div class="form-layer">
        <el-form label-width="100px" size="mini">
          <el-form-item label="Get location">
            <el-button type="primary" @click="fixedPos">Reposition</el-button>
          </el-form-item>
          <el-form-item label="Current latitude">
            <p>{{latitude}}</p>
          </el-form-item>
          <el-form-item label="Current longitude">
            <p>{{longitude}}</p>
          </el-form-item>
          <el-form-item>
            <div class="fac">
              <el-input v-model="keyWords" placeholder="Please enter the region" style="width: 230px;margin-right: 6px;"></el-input>
              <el-button type="primary" @click="setPlace" :disabled="!keyWords">Query</el-button>
            </div>
          </el-form-item>
        </el-form>
        <div id="map"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          v-if="type != '2'"
          @click="btnSubmit()"
          >Confirm</el-button
        >
        <el-button size="small" @click="popup = false">Cancel</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: "mapView",
    data() {
      return {
        map: null,
        local: null,
        mk: null,
        latitude: '',
        longitude: '',
        keyWords: ''
      };
    },
    methods: {
      // Open the pop-up window, name is the name of the pop-up window async openDialog(name) {
        this.text = name;
        this.popup = true;
        this.initMap();
      },
      // Confirm btnSubmit() {
        let key = {
          latitude: this.latitude,
          longitude: this.longitude
        }
        // Print longitude and latitude console.log(key);
        this.popup = false;
      },
      initMap() {
        this.$nextTick(() => {
          this.map = new BMap.Map("map");
          let point = new BMap.Point(116.404, 39.915);
          this.map.centerAndZoom(point, 12);
          this.map.enableScrollWheelZoom(true); // Enable mouse wheel zoom this.map.addControl(new BMap.NavigationControl());
          this.fixedPos();
        });
      },
      // Click to locate - locate to the current position fixedPos() {
        const _this = this;
        const geolocation = new BMap.Geolocation();
        this.confirmLoading = true;
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            _this.handleMarker(_this, r.point);
            let myGeo = new BMap.Geocoder();
            myGeo.getLocation(
              new BMap.Point(r.point.lng, r.point.lat),
              function (result) {
                _this.confirmLoading = false;
                if (result) {
                  _this.latitude = result.point.lat;
                  _this.longitude = result.point.lng;
                }
              }
            );
          } else {
            _this.$message.error("failed" + this.getStatus());
          }
        });
      },
      // Search address setPlace() {
        this.local = new BMap.LocalSearch(this.map, {
          onSearchComplete: this.searchPlace,
        });
        this.local.search(this.keyWords);
      },
      searchPlace() {
        if (this.local.getResults() != undefined) {
          this.map.clearOverlays(); //Clear all overlays on the mapif (this.local.getResults().getPoi(0)) {
            let point = this.local.getResults().getPoi(0).point; //Get the first smart search result this.map.centerAndZoom(point, 18);
            this.handleMarker(this, point);
            console.log("Longitude: " + point.lng + "--" + "Latitude" + point.lat);
            this.latitude = point.lat;
            this.longitude = point.lng;
          } else {
            this.$message.error("No location matched!");
          }
        } else {
          this.$message.error("No search results found!");
        }
      },
      // Set the mark handleMarker(obj, point) {
        let that = this;
        obj.mk = new BMap.Marker(point);
        obj.map.addOverlay(obj.mk);
        obj.mk.enableDragging(); // draggable obj.mk.addEventListener("dragend", function (e) {
          // Listen for the dragging of the annotation and get the longitude and latitude after the drag that.latitude = e.point.lat;
          that.longitude = e.point.lng;
        });
        obj.map.panTo(point);
      },
    }
  };
</script>
<style scoped>
  .form-layer {
    width: 100%;
  }
  #map {
    margin-top: 30px;
    width: 100%;
    height: 300px;
    border: 1px solid gray;
    box-sizing: border-box;
    overflow: hidden;
  }
  /deep/ .el-dialog {
    min-width: 550px;
  }
  /deep/ .el-dialog__body {
    padding: 10px;
  }
</style>

This is the end of this article about how to call Baidu Maps in Vue to obtain longitude and latitude. For more information about how to call Baidu Maps in Vue to obtain longitude and latitude, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue sample code using exif to get the latitude and longitude of the image
  • vue implements the positioning function on the Web side to obtain longitude and latitude
  • Vue component based on elementUI using v-model to implement longitude and latitude input

<<:  Mysql database advanced usage of views, transactions, indexes, self-connections, user management example analysis

>>:  Detailed explanation of the functions of -I (uppercase i), -L (uppercase l), and -l (lowercase l) when compiling programs with g++ under Linux

Recommend

How InnoDB cleverly implements transaction isolation levels

Preface In the previous article Detailed Explanat...

Solution to prevent caching in pages

Solution: Add the following code in <head>: ...

Nginx builds rtmp live server implementation code

1. Create a new rtmp directory in the nginx sourc...

Use the njs module to introduce js scripts in nginx configuration

Table of contents Preface 1. Install NJS module M...

In-depth explanation of Session and Cookie in Tomcat

Preface HTTP is a stateless communication protoco...

Usage and description of HTML tag tbody

The tbody element should be used in conjunction wi...

How to configure MGR single master and multiple slaves in MySQL 8.0.15

1. Introduction MySQL Group Replication (MGR for ...

How to set a dotted border in html

Use CSS styles and HTML tag elements In order to ...

MySQL recursion problem

MySQL itself does not support recursive syntax, b...

JavaScript array deduplication solution

Table of contents Method 1: set: It is not a data...

Detailed deployment of docker+gitlab+gitlab-runner

environment Server: centos7 Client: window Deploy...

Summary of using the reduce() method in JS

Table of contents 1. Grammar 2. Examples 3. Other...

In-depth analysis of MySQL index data structure

Table of contents Overview Index data structure B...

Implementation of formatting partitions and mounting in Centos7

Linux often encounters situations such as adding ...

The difference between MySQL database stored procedures and transactions

Transactions ensure the atomicity of multiple SQL...