Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

VUE Component for AMap Address Selection

Tech May 13 2

Notes: This article builds upon the previous article "Configuring AMap in Vue-Cli 3.0", using the direct inclusion of the AMap SDK to access AMap API.

Functionality Ovreview

If a coordinate point is provided, it should be centered on the map. If no coordinate point is provided, the map should center on the current location. Once the location is set, the right side should display the longitude, latitude, and address. The marker should be draggable to adjust the location point. After dragging the marker, the updated longitude, latitude, and address should appear on the right side. Clicking the confirm button should return the final coordinates and address to the parent component.

Component Implementation Code

<template>
  <div class="map-container" :style="{ width: width, height: height }">
    <div id="map" class="map"></div>
    <div class="info-panel">
      <p>Longitude: {{coordinates ? coordinates[0] : '-'}}</p>
      <p>Latitude: {{coordinates ? coordinates[1] : '-'}}</p>
      <p>Address: {{address}}</p>
      <button size="mini" class="confirm-btn" @click="submitLocation">Confirm</button>
    </div>
  </div>
</template>

<script>
import AMap from 'AMap'
export default {
  props: {
    width: { type: String, default: '100%' },
    height: { type: String, default: '400px' },
    initialPosition: {
      type: Array,
      validator: (value) => {
        return value.length === 2
      }
    }
  },
  data () {
    return { address: '', coordinates: this.initialPosition }
  },
  mounted () {
    this.setupMap(this.coordinates)
  },
  methods: {

    setupMap (position) {
      const map = new AMap.Map('map', {
        resizeEnable: true,
        zoom: 15
      })

      map.plugin(['AMap.Geolocation', 'AMap.Geocoder'])

      this.findLocation(map, position)
    },

    findLocation (map, position) {
      if (position) {
        map.setCenter(position)
        this.addMarker(map, position)

        this.reverseGeocode(position)
      } else {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          zoomToAccuracy: true,
          buttonPosition: 'RB'
        })
        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            const coords = [result.position.lng, result.position.lat]
            map.setCenter(coords)
            this.addMarker(map, coords)

            this.coordinates = coords
            this.reverseGeocode(coords)
          } else {
            console.log('Failed to get location', result)
          }
        })
      }
    },

    addMarker (map, coords) {
      const marker = new AMap.Marker({
        map: map,
        position: coords,
        draggable: true,
        cursor: 'move',
        raiseOnDrag: true
      })
      marker.on('dragend', (e) => {
        const newCoords = [marker.getPosition().lng, marker.getPosition().lat]

        this.coordinates = newCoords
        this.reverseGeocode(newCoords)
      })
    },

    reverseGeocode (coords) {
      const geocoder = new AMap.Geocoder({ radius: 1000 })
      geocoder.getAddress(coords, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.address = result.regeocode.formattedAddress
        }
      })
    },

    submitLocation () {
      this.$emit('location', this.coordinates, this.address)
    }
  }
}
</script>

<style lang="scss" scoped>
.map-container {
  box-sizing: border-box;
  background-color: #ddd;
  padding: 15px;
  &:after {
    content: '';
    display: block;
    clear: both;
  }
  .map, .info-panel {
    float: left;
    height: 100%;
  }
  .map {
    width: 75%;
  }
  .info-panel {
    width: 25%;
    background-color: #fff;
    padding: 0 15px;
    border-left: 1px solid #eee;
    box-sizing: border-box;
    word-wrap: break-word;
  }
  .confirm-btn {
    width: 100%;
    margin: 30px 0 0 0;
    padding: 5px 0;
    color: #fff;
    cursor: pointer;
    background-color: #409eff;
    border: none;
    border-radius: 3px;
    &:hover {
      background-color: #66b1ff;
    }
  }
}
</style>

Using the Component

<template>
  <div class="container">
    <map-component width="700px" height="500px" :initial-position="[114.433703, 30.446243]" @location="handleLocation"></map-component>
  </div>
</template>

<script>
import MapComponent from '@/components/map'
export default {
  components: { MapComponent },
  methods: {
    handleLocation (coordinates, address) {
      alert(`Coordinates: ${coordinates[0]},${coordinates[1]} - Address: ${address}`)
    }
  }
}
</script>

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.