Vue

vue项目中使用高德地图api(自定义标记点为例)

2021-07-13  本文已影响0人  ciuhoi

现在实现的业务是在地图上用经纬度显示相应的标记点及数据(自定义标记点),之前使用过高德地图行政区域放大的api,由于代码量有点多就用了这个最近使用的自定义标记点的示例来做展示,实现的方式都是一样的。
高德地图JS API:https://lbs.amap.com/api/javascript-api/guide/overlays/marker

这是示例中源代码的效果图,红框标记就是自定义标记点
而现在我想实现下图的效果:

下面看一下他的源代码,源代码中province明显是一个数组,标记点是通过遍历这个数组的数据插入的,provinces[i].type === 2里面("<div class = 'taiwan'>宝岛台湾</div>")的就是我要做的自定义标记点,其实就是一个div,标记点的自定义就是通过修改这个div实现的。

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <style type="text/css">
      body,html,#container{
        height: 100%;
        margin: 0px;
        font:12px Arial;
      }
      .taiwan{
        border: solid 1px red;
        color: red;
        float: left;
        width: 50px;
        background-color: rgba(255,0,0,0.1)
      }
    </style>
    <title>Marker example</title>
  </head>
  <body>
   <div id="container" tabindex="0"></div>
   <script src="https://webapi.amap.com/js/marker.js"></script>
   <script src="https://webapi.amap.com/maps?v=1.4.2&key=608d75903d29ad471362f8c58c550daf"></script>
   <script type="text/javascript">

        var map = new AMap.Map('container',{resizeEnable: true,zoom:4});
        var markers = []; //province见Demo引用的JS文件
        for (var i = 0; i < provinces.length; i += 1) {
                var marker;
                if (provinces[i].type === 0) {
                    var icon = new AMap.Icon({
                        image: 'https://vdata.amap.com/icons/b18/1/2.png',
                        size: new AMap.Size(24, 24)
                    });
                    marker = new AMap.Marker({
                        icon: icon,
                        position: provinces[i].center.split(','),
                        offset: new AMap.Pixel(-12,-12),
                        zIndex: 101,
                        title: provinces[i].name,
                        map: map
                    });
                } else {
                    marker = new AMap.Marker({
                        position: provinces[i].center.split(','),
                        title: provinces[i].name,
                        map: map
                    });
            if (provinces[i].type === 2) {
                    var content= "<div class = 'taiwan'>宝岛台湾</div>";
                    baodao = new AMap.Marker({
                        content: content,
                        position: provinces[i].center.split(','),
                        title: provinces[i].name,
                        offset: new AMap.Pixel(0,0),
                        map: map
                    });
            }
                }
                markers.push(marker);
            }
              map.setFitView();
    </script>
    <script type="text/javascript" src="https://webapi.amap.com/demos/js/liteToolbar.js"></script>
  </body>
</html>

了解了源代码实现过程,现在是如何引入api,很多一开始接触相关业务时肯定会考虑vue的地图插件vue-amap,我也试着去实现过,但是他的文档实在是过于抽象也很难找到相应示例(可能只有我找不到),对于很多初学者或者没怎么接触这方面业务的开发者来说这似乎有点不太好实现。了解了高德地图的api后发现也不是不能实现,源代码是原生的那就用原生的方式实现。

首先看看他引入的东西是啥:

//分别是:
<script src="https://webapi.amap.com/js/marker.js"></script>
<script src="https://webapi.amap.com/maps?v=1.4.2&key=608d75903d29ad471362f8c58c550daf"></script>

//还有
<script type="text/javascript" src="https://webapi.amap.com/demos/js/liteToolbar.js"></script>

注册账号和申请key的过程如下:
1. 首先,注册开发者账号,成为高德开放平台开发者
2. 登陆之后,在进入「应用管理」 页面「创建新应用」
3. 为应用添加 Key,「服务平台」一项请选择「 Web 端 ( JSAPI )」

通过异步的的方式引入:引入的方法后面可以封装一下;只需要将provinces[i].type === 2里的内容放入遍历里面修改一下。这样基本的效果就是实现了,content的内容可以根据业务自定义,后面可以根据业务需求进行修改。最后记得在destroyed中把引入的内容清除。

async mounted() {
        let that = this;
        try{
            await that.createMarker();
            await that.createCoreScript()
            await that.createDemo();

            console.log('所有资源成功获取...')
            that.map = new AMap.Map('container', {
                resizeEnable: true,
                zoom:4
            });
            let markers = [];
            
            let dataList [{        //dataList数据根据具体业务修改
              lng: '',
              lat: '',
              name: '龙华',
              count: '25'
            },{
              lng: '',
              lat: '',
              name: '龙华',
              count: '25'
            }]

            for (var i = 0; i < that.dataList.length; i += 1) {
                let marker;
                let content= `<div id = 'taiwan' 
                    style='display:flex;flex-direction: column;justify-content:center;align-items:center;color: #333;width: 80px; height:80px;border-radius:50%;text-align:center;background-color: #e2991a;font-weight:bold'
                >
                    <div style='margin-bottom:6px'>${that.dataList[i].name}</div>
                    <div>${that.dataList[i].count}个楼盘</div>
                </div>`;
                marker = new AMap.Marker({
                    content: content,
                    position: [that.dataList[i].Lng,that.dataList[i].Lat],
                    title: that.dataList[i].name,
                    offset: new AMap.Pixel(0,0),
                    map: that.map
                });
                markers.push(marker);
            }
        } catch(e) {
            console.log('资源获取失败')
        }
    },
    destroyed() {
        let coreScript = document.getElementById('coreScript');
        let markerScript = document.getElementById('markerScript');
        let demoScript = document.getElementById('demoScript');

        coreScript.parentNode.removeChild(coreScript);
        markerScript.parentNode.removeChild(markerScript);
        demoScript.parentNode.removeChild(demoScript);
    },
 methods: {
        createCoreScript() {
            return new Promise((resolve, reject) => {
                console.log('进入加载核心资源')
                let url = `http://webapi.amap.com/maps?v=1.4.2&key=${this.KEY}`;
                let $script =document.createElement('script');
                $script.id = 'coreScript';
                $script.src = url;
                $script.type = 'text/javascript';
                $script.addEventListener('load', (event) => {
                    console.log('核心script 获取成功')
                    resolve()
                })
                $script.onerror = function (e) {
                    console.log('js资源加载失败了')
                }
                document.body.appendChild($script)
            })
        },

        createMarker() {
            return new Promise((resolve, reject) => {
            let url = `http://webapi.amap.com/js/marker.js`;
            let $script = document.createElement('script');
            $script.id = 'markerScript';
            $script.src = url;
            $script.type = 'text/javascript';
            $script.addEventListener('load', (event) => {
                console.log('Marker script 获取成功')
                resolve()
            })
            document.body.appendChild($script)
            })
        },

        createDemo() {
            return new Promise((resolve, reject) => {
            let url = `http://webapi.amap.com/demos/js/liteToolbar.js`;
            let $script = document.createElement('script');
            $script.id = 'demoScript';
            $script.src = url;
            $script.type = 'text/javascript';
            $script.addEventListener('load', (event) => {
                console.log('demo script 获取成功')
                resolve()
            })
            document.body.appendChild($script)
            })
        },

    }

下面是完整基本实现的代码:其他api的实现方法也一样

<template>
        <div class="container">
            <div id="container"></div>
        </div>
</template>

<script>
export default {
    name: 'HelloWorld',
    data() {
        return {
            map: '',
            KEY: '',    //将开发者账号申请的key放入
        }
    },
    async mounted() {
        let that = this;
        try{
            await that.createMarker();
            await that.createCoreScript()
            await that.createDemo();

            console.log('所有资源成功获取...')
            that.map = new AMap.Map('container', {
                resizeEnable: true,
                zoom:4
            });
            let markers = [];
             let dataList [{        //dataList数据根据具体业务修改
              lng: '',
              lat: '',
              name: '龙华',
              count: '25'
            },{
              lng: '',
              lat: '',
              name: '龙华',
              count: '25'
            }]

            for (var i = 0; i < that.dataList.length; i += 1) {
                let marker;
                console.log(i)
                let content= `<div id = 'taiwan' 
                    style='display:flex;flex-direction: column;justify-content:center;align-items:center;color: #333;width: 80px; height:80px;border-radius:50%;text-align:center;background-color: #e2991a;font-weight:bold'
                >
                    <div style='margin-bottom:6px'>${that.dataList[i].name}</div>
                    <div>${that.dataList[i].count}个楼盘</div>
                </div>`;
                marker = new AMap.Marker({
                    content: content,
                    position: [that.dataList[i].Lng,that.dataList[i].Lat],
                    title: that.dataList[i].name,
                    offset: new AMap.Pixel(0,0),
                    map: that.map
                });
                markers.push(marker);
            }
        } catch(e) {
            console.log('资源获取失败')
        }
    },
    destroyed() {
        let coreScript = document.getElementById('coreScript');
        let markerScript = document.getElementById('markerScript');
        let demoScript = document.getElementById('demoScript');

        coreScript.parentNode.removeChild(coreScript);
        markerScript.parentNode.removeChild(markerScript);
        demoScript.parentNode.removeChild(demoScript);
    },
    methods: {
        async getData(){
            const res = await this.$axios.get('/index/v1.index/find');
            this.dataList = res.data;
        },
        createCoreScript() {
            return new Promise((resolve, reject) => {
                console.log('进入加载核心资源')
                let url = `http://webapi.amap.com/maps?v=1.4.2&key=${this.KEY}`;
                let $script = document.createElement('script');
                $script.id = 'coreScript';
                $script.src = url;
                $script.type = 'text/javascript';
                
                $script.addEventListener('load', (event) => {
                    console.log('核心script 获取成功')
                    resolve()
                })
                $script.onerror = function (e) {
                    console.log('js资源加载失败了')
                }
                document.body.appendChild($script)
            })
        },

        createMarker() {
            return new Promise((resolve, reject) => {
            let url = `http://webapi.amap.com/js/marker.js`;
            let $script = document.createElement('script');
            $script.id = 'markerScript';
            $script.src = url;
            $script.type = 'text/javascript';
            $script.addEventListener('load', (event) => {
                console.log('Marker script 获取成功')
                resolve()
            })
            document.body.appendChild($script)
            })
        },

        createDemo() {
            return new Promise((resolve, reject) => {
            let url = `http://webapi.amap.com/demos/js/liteToolbar.js`;
            let $script = document.createElement('script');
            $script.id = 'demoScript';
            $script.src = url;
            $script.type = 'text/javascript';
            $script.addEventListener('load', (event) => {
                console.log('demo script 获取成功')
                resolve()
            })
            document.body.appendChild($script)
            })
        },

    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.container{
    width: 100%;
    height: 1000px;
    margin: 0 auto;
    #container{
        height: 100%;
        margin: 0px;
        font:12px Arial;
    }
    .taiwan{
        border: solid 1px rgb(223, 52, 52);
        color: red;
        float: left;
        width: 50px;
        background-color: rgba(228, 162, 40, 0.1);
        background-color: #fff;
    }
}


</style>

上一篇下一篇

猜你喜欢

热点阅读