Vue 개발 고 덕 지도 응용 최고의 실천
이전에 지도 상호작용 에 관 한 제품 시스템 을 많이 만 들 지 못 했 는데 현재 국내 주류 의 지도 응용 SDK 는 몇 개 밖 에 없다.고 덕,바 이 두 와 텐 센트 이다.그래서 개인 적 으로 PC 응용 에 있어 고 덕 지도 개발 이 상대 적 으로 좋 고 적어도 체험 해 보면 뚜렷 한 구덩이 가 없다 고 생각 합 니 다.이 글 은 개발 지도 응용 정 리 를 총괄 한 셈 이다.
비동기 로드
js sdk 응용 프로그램 을 사용 하기 때문에 스 크 립 트 파일 자체 의 부피 가 매우 크기 때문에 불 러 오 는 화이트 스크린 시간 을 주의 하여 사용자 체험 문 제 를 해결 해 야 합 니 다.현재 대부분의 제품 응용 은 SPA 단일 페이지 응용 시스템 이기 때문에 저 는 비동기 로 불 러 오 는 방법 을 패키지 합 니 다.
const loadScripts = async scripts => {
  const get = src => {
    return new Promise(function(resolve, reject) {
      const el = document.createElement('script')
      el.addEventListener('load', function() {
        resolve(src)
      }, false)
      el.addEventListener('error', function() {
        reject(src)
      }, false)
      el.id = src.id
      el.src = src.url
      document.getElementsByTagName('body')[0].appendChild(el) || document.getElementsByTagName('head')[0].appendChild(el)
    })
  }
  const myPromises = scripts.map(async script => {
    if (document.getElementById(script.id) === null) {
      return await get(script)
    }
  })
  return await Promise.all(myPromises)
}
export default loadScripts
패키지 구성 요소
만약 에 시스템 에 여러 페이지 가 지도 응용 업 무 를 필요 로 한다 면 유 니 버 설 맵 구성 요 소 를 밀봉 하고 프로젝트 의 유지 가능성 을 향상 시 켜 야 합 니 다.제 쪽 은 간단하게 지도 응용 을 포장 해 야 합 니 다.
<template>
  <div
    :style="{
      width: width,
      height: height
    }"
    class="amap-container"
  >
    <div ref="amap" class="amap">
      <slot />
    </div>
  </div>
</template>
<style lang="scss" scoped>
    .amap-container {
    .amap {
        width: 100%;
        height: 100%;
    }
    }
</style>
import loadScripts from '@/loadScripts'
export default {
  name: 'AMapContainer',
  props: {
    width: {
      require: false,
      type: String,
      default: '100%'
    },
    height: {
      require: false,
      type: String,
      default: '600px'
    },
    options: {
      require: false,
      type: Object,
      default: () => {}
    }
  },
  data: () => ({
    amap: null,
    amapInfo: {
      key: 'xxxxxxxxxxxxxx'
    }
  }),
  created() {
    this.initAMap()
  },
  beforeDestroy() {
    //     
    if (!this.amap) {
      return
    }
    this.amap.destroy()
    this.amap = null
  },
  methods: {
    initAMap() {
      loadScripts([{
        id: 'ampa',
        url: `https://webapi.amap.com/maps?v=2.0&key=${this.amapInfo.key}&plugin=AMap.PolygonEditor`
      }]).then(() => {
        this.amap = new window.AMap.Map(this.$refs['amap'], this.options)
        this.$emit('map', this.amap, window.AMap)
      })
    }
  }
}
구성 요소 사용
구성 요 소 를 밀봉 한 후 해당 페이지 에서 구성 요 소 를 도입 하여 사용 하면 됩 니 다.
<template>
    <amap-container height="100%" :options="amapOptions" @map="getAMapData" />
</template>
<script>
    import AMap from '@/components/AMap'
    export default {
        name: 'AMapDemo',
        components: {
            'amap-container': AMap
        },
        data: () => ({
            amapOptions: {
                zoom: 14,
                resizeEnable: true,
                viewMode: '3D',
                mapStyle: 'amap://styles/normal'
            },
            AMap: null, //     
            amap: null //       
        }),
        methods: {
            /**
             *         
             * @param amap
             * @param AMap
             */
            getAMapData(amap, AMap) {
                //         amap   
                this.amap = amap
                //         AMap     
                this.AMap = AMap
            }
        }
    }
</script>
사용자 정의 인터페이스 최 적 실천
이전에 제 작 된 지도 응용 프로그램 은 표 시 된 상세 한 인터페이스(왼쪽 단 추 를 선택 하여 화면 을 엽 니 다)에 있 습 니 다.이 화면 은 원생 document 대상 에 들 어가 야 하지만 vue 대상 에서 이러한 쓰기 에 부합 되 지 않 기 때문에 예전 에 많은 시스템 들 이 dom 구 조 를 작성 하 는 데 많은 시간 을 들 였 습 니 다.골 치 아 팠 습 니 다.나중에 이 문 제 를 해결 하기 위해 서 는...vue 에서 구성 요 소 를 마 운 트 하여 실제 document 대상 을 가 져 올 수 있 는 방법 이 있 는 지,관련 문 서 를 찾 아 본 후에 이 api 가 있 습 니 다:Vue.extend.이 api 를 이용 하여 구성 요소 대상 을 마 운 트 하면 실례 화 된 구성 요소 의 대상 을 얻 을 수 있 습 니 다.
import ContextCard from './components/ContextCard'
//     
const marker = new this.AMap.Marker({
  map: this.amap,
  position: [119.058904, 33.537069]
})
//       
marker.on('click', this.markerInfoWindow)
//       
const markerInfoWindow = () => {
  //    Vue         
  const ContextCardContent = Vue.extend(ContextCard)
  //     
  const contextCardContent = new ContextCardContent().$mount()
  //        
  this.amapInfoWindow = new this.AMap.InfoWindow({
    isCustom: true,
    content: contextCardContent.$el,
    offset: new this.AMap.Pixel(0, -40)
  })
  //     
  this.amapInfoWindow.open(this.amap, marker.getPosition())
  //           
  contextCardContent.$on('closeWindow', () => this.amapInfoWindow.close())
}
<template>
  <el-card class="context-box-card box-card">
    <div slot="header" class="header">
      <span>    </span>
      <el-button type="text" class="close-btn" @click="closeWindow">  </el-button>
    </div>
    <div v-for="o in 4" :key="o" class="text item">
      {{ '     ' + o }}
    </div>
  </el-card>
</template>
<script>
export default {
  name: 'AMapContextCard',
  methods: {
    closeWindow() {
      this.$emit('closeWindow')
    }
  }
}
</script>
<style lang="scss" scoped>
.context-box-card {
  width: 320px;
  height: 200px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  ::v-deep .el-card__header {
    padding: 5px 20px;
  }
}
</style>
import Vue from "vue";
import App from "./App.vue";
import Element from "element-ui";
import "normalize.css/normalize.css";
import "element-ui/lib/theme-chalk/index.css";
Vue.config.productionTip = false;
Vue.use(Element);
new Vue({
  render: (h) => h(App)
}).$mount("#app");
Vue 의 고 덕 지도 앱 개발 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 Vue 고 덕 지도 앱 에 관 한 내용 은 저희 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 읽 어 주시 기 바 랍 니 다.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Fastapi websocket 및 vue 3(Composition API)1부: FastAPI virtualenv 만들기(선택 사항) FastAPI 및 필요한 모든 것을 다음과 같이 설치하십시오. 생성main.py 파일 및 실행 - 브라우저에서 이 링크 열기http://127.0.0.1:...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.