preface

With a small example of digging treasure on the map, to summarize their use of Gaode map experience.

Amap document

Start – load Amap

/ / to enter
cd utils

// Create the amap.js file
vim AMap.js
Copy the code

AMap.js

export default function MapLoader() {
  return new Promise((resolve, reject) = > {
    if (window.AMap) {
      resolve(window.AMap);
    } else {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.async = true;
      script.src =
        "Https://webapi.amap.com/maps?v=1.4.15&key= your own application key&plugin = AMap. Geocoder&callback = initAMap";
      script.onerror = reject;
      document.head.appendChild(script);
    }
    window.initAMap = (a)= > {
      resolve(window.AMap);
    };
  });
}

Copy the code

Use, on that page you need to use the Gaud map, called on that page

<script>
import AMap from "@/utils/AMap";

export default {
  name: "home",
  data() {
    return {
      map: null
    };
  },
  created() {
    window.title = "Map";
  },
  mounted() {
    this.initAMap();
  },
  methods: {
    async initAMap() {
      try {
        const res = await AMap();
        this.map = new res.Map("container", {
          resizeEnable: true.// Whether to monitor map container size changes
          zoom: 11.// Initialize the map hierarchy
          center: [116.397428.39.90923] // Initializes the map center point
        });
      } catch (err) {
        console.error(err); }}}};</script>
Copy the code

Gets the location of the treasure chest passed in


// Don't forget to add LNG and LAT to data
created() {
    this.lng = this.$route.query.lng;
    this.lat = this.$route.query.lat;
},

Copy the code

Consider the convenience of calling autonavi API, modify the code

<script>
import AMap from "@/utils/AMap";

export default {
  name: "home",
  data() {
    return {
      map: null.// The location of the treasure box
      lng: null.lat: null./ / new
      resMap: null
    };
  },
  created() {
    this.lng = this.$route.query.lng;
    this.lat = this.$route.query.lat;
  },
  mounted() {
    this.initAMap();
  },
  methods: {
    async initAMap() {
      try {
        / / modify
        this.resMap = await AMap();
        
        this.map = new this.resMap.Map("container", {
          resizeEnable: true.// Whether to monitor map container size changes
          zooms: [3.19].// Set the map level range
          zoom: 14.// Initialize the map hierarchy
          zoomEnable: true.// Whether to scale
          scrollWheel: true.// Whether scroll wheel scaling is supported
          dragEnable: true.// Whether mouse drag and move is supported
          jogEnable: true.// Whether the easing effect is supported
          buildingAnimation: true.// Is there any animation effect when the module disappears
          center:  [this.lng, this.lat] // Initializes the map center point
        });
      } catch (err) {
        console.error(err); }}}};</script>
Copy the code

Add dot mark

Create a new function

// Create dot tags
addMarker() {
  this.marker = new this.resMap.Marker({
    icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png".position:  [this.lng, this.lat],
    offset: new this.resMap.Pixel(- 13.- 30)});this.map.add(this.marker);
  this.map.setFitView();
},
Copy the code

Called in the initAMap function

async initAMap() {
      try{... this.addMarker() }catch (err) {
        console.error(err); }}Copy the code

Add vector circles

Create a new function

// Construct vector circles
addCircle() {
  return new this.resMap.Circle({
    center: new this.resMap.LngLat(`The ${this.lng}`.`The ${this.lat}`), // The center of the circle
    radius: 500.// The radius is meters
    strokeColor: "#F33"./ / thread color
    strokeOpacity: 1.// Line transparency
    strokeWeight: 3.// Line thickness
    fillColor: "#ee2200".// Fill the color
    fillOpacity: 0.35 // Fill transparency
  });
},
Copy the code

Modify the addMarker function

// Create dot tags
addMarker() {
  ...
   
  // Add circle to data
  this.circle = this.addCircle();

  this.map.add([this.marker, this.circle]);
  this.map.setFitView();
},
Copy the code

Add an icon

Create a new function

// Create an icon
addIcon() {
  return new this.resMap.Icon({
    // Icon size
    size: new this.resMap.Size(40.40),
    // The address of the icon
    image: require("@/assets/images/Treasure Box.png"),
    // The size of the image used by the icon
    imageSize: new this.resMap.Size(40.40)
    // The icon takes the graph offset
    // imageOffset: new this.resMap.Pixel(0, 13)
  });
},
Copy the code

Modify the addMarker function

 // Create dot tags
addMarker() {
  this.marker = new this.resMap.Marker({
    icon: this.addIcon(),
    position: [this.lng, this.lat],
    offset: new this.resMap.Pixel(- 20.- 20)});this.circle = this.addCircle();

  this.map.add([this.marker, this.circle]);
  this.map.setFitView();
},
Copy the code

Get current location

Create a new function

// Get the current location information
getCityInfo() {
  this.map.plugin("AMap.Geolocation", () = > {var geolocation = new this.resMap.Geolocation({
      // Whether to use high precision positioning. Default: true
      enableHighAccuracy: true.// Set location timeout. Default: infinite
      timeout: 10000.// The offset of the location button's docking position, default: Pixel(10, 20)
      buttonOffset: new this.resMap.Pixel(10.20),
      // After successful positioning, adjust the map view range to make the positioning position and accuracy range visible in the view. Default: false
      zoomToAccuracy: true.// Locate the position of the button, RB represents the lower right
      buttonPosition: "RB"
    });

    geolocation.getCurrentPosition();
    this.resMap.event.addListener(geolocation, "complete".this.onComplete);
    this.resMap.event.addListener(geolocation, "error".this.onError);
  });
},

// Get the location result
onComplete(res) {
  console.log(res)
},

// Location error
onError(err) {
  console.error(err, "-- positioning error --");
}

Copy the code

Calculate the distance between the chest and the current

Create a new function

// Calculate the distance between two points
calculatingDistance(position) {
  const p1 = [this.lng, this.lat];
  // Add myPosition to data
  this.myPosition = [position.lng, position.lat];
  return this.resMap.GeometryUtil.distance(p1, this.myPosition);
},
Copy the code

Modify the onComplete function

onComplete(res) {
  // Add distance to data
  this.distance = this.calculatingDistance(res.position);
},

Copy the code

Added whether you can dig a treasure logic

Current position within 500 meters of treasure chest can be dug, at the same time display ‘ME’ mark

computed: {
    // Is it within 500 meters
    is500() {
      return this.distance === undefined ||
        this.distance === null ||
        this.distance > 500
        ? false
        : true; }},watch: {
    is500(newValue) {
      if (newValue) {
        const marker = new this.resMap.Marker({
          icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png".position: this.myPosition,
          offset: new this.resMap.Pixel(- 13.- 30),
          title: "我"
        });
        this.map.add(marker);
        this.map.setFitView();
    
        // Set the text prompt for the mouse pointer
        marker.setTitle("我");
    
        // Set the label
        // label is displayed in the upper left corner of the white background by default. The style className is amap-marker-label
        marker.setLabel({
          offset: new this.resMap.Pixel(0.0), // Set the offset of the text annotation
          content: "< div class =" info "> I < / div >".// Set the text annotation content
          direction: "bottom" // Set the orientation of the text annotation}); }}},Copy the code

The last

Level is limited, there are mistakes in the big guy light spray!

reference

Use AMap asynchronously in VUE projects