前端vue使用高德地圖


首先,注冊Key

  1. 注冊開發者賬號,成為高德開放平台開發者
  2. 登陸之后,在進入「應用管理」 頁面「創建新應用」
  3. 為應用添加 Key,「服務平台」一項請選擇「 Web 端 ( JSAPI ) 」

然后,書寫代碼
  在vuecli public文件夾中的index.html添加導入 JS API 的入口腳本標簽

<!DOCTYPE html>
<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">
    <link rel="icon" href="./iconLink.png">
    <title>高德地圖</title>
    <!-- 建議將導入的script寫在body前面,以便提前加載 -->
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=2.0&key=d6c35bb2619f107f86ccda4b378415f6&plugin=AMap.MouseTool"></script> <!-- 只是我的key,可以暫時用為測試(不定什么時候失效) -->
   <script src="//webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script> <!-- 高德官方文檔的ui庫 --> </head> <body> <div id="app"></div> </body>
</html>

在vue.config.js中修改配置

module.exports = {
    publicPath: "./",
    configureWebpack: {
        externals: {
            AMap: 'window.AMap',
            AMapUI: 'window.AMapUI' // 高德地圖配置
        },
    }
};

接着,正式書寫vue組件

<template>
    <div class="map_wrapper">
        <div class="box">
            <div id="container" style="width: 100%; height: 500px"></div>
        </div>
    </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
@Component({
})
export default class page extends Vue {
   // 使用 import AMap from 'amap'; 會有編輯器報錯Cannot find module 'amap'; 所以變通換一種寫法
    protected AMap: any = (window as any).AMap;
    protected AMapUI: any = (window as any).AMapUI;

   // 如果寫在created會報錯 "Error: Map container div not exist"
    mounted() {
            let map = new this.AMap.Map('container', {
                center: [121.227577, 31.101471], // 中心點坐標
                resizeEnable: true, // 是否監控地圖容器尺寸變化
                zoom: 10, // 初始化地圖層級,可以理解為縮放比例
                showMarker: true, // 定位成功后在定位到的位置顯示點標記,默認:true
            });

            //加載SimpleInfoWindow,loadUI的路徑參數為模塊名中 'ui/' 之后的部分
            this.AMapUI.loadUI(['overlay/SimpleInfoWindow'], (SimpleInfoWindow: any) => {
                let marker = new this.AMap.Marker({
                    map: map,
                    zIndex: 9999999,
                    position: map.getCenter(),
                });

                let infoWindow = new SimpleInfoWindow({
                    infoTitle: '<strong>這里是標題</strong>',
                    infoBody: '<p>這里是內容。</p>',
                    offset: new this.AMap.Pixel(0, -31),  // 文本定位偏移
                });
                //顯示在map上
                function openInfoWin() {
                    infoWindow.open(map, marker.getPosition());
                }
                marker.on('click', () => {
                    openInfoWin();  // 點擊標記時顯示文本
                });
                openInfoWin();
            });
    }
}
</script>

<style scoped lang="scss"></style>

最終效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM