vue中使用google地图(自定义label、信息窗口)

本文介绍了在Vue项目中使用vue2-google-maps插件结合Google JavaScript API来实现自定义Label的功能。由于vue2-google-maps不支持Label位置控制,作者选择了原生API并引入markerwithlabel.js库。文章详细阐述了如何申请Google Maps秘钥、在Vue项目中引入地图库以及避免在created钩子中初始化地图导致的错误,强调初始化地图应在mounted钩子中进行。
摘要由CSDN通过智能技术生成

     最近公司爱尔兰项目需要使用google地图,项目还是用vue写的,那我就寻思找个vue能用的google地图的插件吧,找了vue2-google-maps,这个插件确实还行,而且github上还有api文档,虽然都是英文很难受,但是还行,没有骚需求的话,用它还行。

    google地图里面有个功能,label,vue2-google-maps里面是没有办法控制label的位置的,默认就是显示在中间,但是如果写自定义覆盖层又觉得麻烦,于是还是用了原生得Google JavaScriptApi,并且引用了一个js库,markerwithlabel.js,引入了这个库就可以对label进行操作,库的代码不是很多,附在最后。

Map JavaScriptApi:

https://developers.google.cn/maps/documentation/javascript/tutorial

    那么,使用google需要几步,

    1、申请秘钥,这个秘钥说起来就很恶心了,我自己申请过了,但是只是好用了一下,刷新了就报错了,好像是说秘钥过期,很醉,于是找安卓小哥要了秘钥,据说客户付过费了还是咋的,具体我也不清楚google的秘钥规则,要给api权限好像,很麻烦。

    2、引入google的地图库,即便你用的是vue也可以直接在index.html中使用,下面是引入的操作label的文件

  <!--GGMap-->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=***你的秘钥***"></script>
    <script type="text/javascript" src="./static/markerwithlabel.js"></script>

    3、创建map的实例,还是原生的用着舒服。有一个很重要,初始化地图,不要在created钩子中调用方法,否则会google is

not defend,很难受,我也找了很久的原因,原因是不能再初始化实例的时候去创建地图,需要等待dom渲染完,在mounted钩子中调用就好了。

<template>
    <div >
      <div id="map_canvas" style="height: 700px; width: 100%"></div>
    </div>
</template>
<script>
    export default {
        name: 'GGMap',
      data(){
          return{
            show:false,
            center: {lng: 120.5, lat: 30.2},
            markers: [{
              position: {lng: 120.4, lat: 30.2},
              orderId:'123456',
              name:'吴韩伟',
              show:false,
            }, {
              position: {lng: 120.5, lat: 30.2},
              orderId:'654321',
              name:'姚永琪',
              show:false,
            }],
            icon: '../../../static/img/qishou.png',
            position:{},
            websock:null,

          }
      },
      created(){
        //页面刚进入时开启长连接
        // this.initWebSocket()
      },
      destroyed: function() {
        //页面销毁时关闭长连接
        this.websocketclose();
      },
      mounted(){
      this.mapBuild() //初始化实例之后调用
      },
      methods:{
        //  地图实例
        mapBuild(){
            //创建地图实例,zoom是缩放比例
          let map = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 12,
            center: this.center,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          });
            //这里因为需要很多标记,所以遍历了this.markers(后端给的数据)来循环创建标记
          this.markers.map(item=>{
            let marker = new MarkerWithLabel({
              position: item.position,
              icon: '../../../static/img/qishou.png', //标记自定义图标
              draggable: false, //不可拖动
              map: map,   //地图实例 
              labelContent: item.name,    //label的内容
              labelAnchor: new google.maps.Point(22, 0),    //label的位置,可以调
              labelClass: "labels", // the CSS class for the label
              labelStyle: { background:'#fff',padding:'5px' }
            });
            //自定义信息窗口
            let iw = new google.maps.InfoWindow({
              content: `<div>
                          <p>订单编号: ${item.orderId}</p>
                          <p>快递员:${item.name}</p>
                        </div>`});
            //点击信息窗口显示
            google.maps.event.addListener(marker, "click", function (e) { iw.open(map, marker); });
          })
        },
      },
    }
</script>

markerwithlabel.js

/**
 * @name MarkerWithLabel for V3
 * @version 1.1.10 [April 8, 2014]
 * @author Gary Little (inspired by code from Marc Ridey of Google).
 * @copyright Copyright 2012 Gary Little [gary at luxcentral.com]
 * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3
 *  <code>google.maps.Marker</code> class.
 *  <p>
 *  MarkerWithLabel allows you to define markers with associated labels. As you would expect,
 *  if the marker is draggable, so too will be the label. In addition, a marker with a label
 *  responds to all mouse events in the same manner as a regular marker. It also fires mouse
 *  events and "property changed" events just as a regular marker would. Version 1.1 adds
 *  support for the raiseOnDrag feature introduced in API V3.3.
 *  <p>
 *  If you drag a marker by its label, you can cancel the drag and return the marker to its
 *  original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker
 *  itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class.
 */

/*!
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*jslint browser:true */
/*global document,google */

/**
 * @param {Function} childCtor Child class.
 * @param {Function} parentCtor Parent class.
 * @pr
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
Vue百度地图定义信息窗口,可以通过以下步骤实现: 1. 安装百度地图JavaScript API库 在Vue项目,可以通过npm安装百度地图JavaScript API库: ``` npm install bmap-jsapi ``` 2. 在Vue组件引入百度地图JavaScript API库 在Vue组件,可以通过以下方式引入百度地图JavaScript API库: ``` import BMap from 'bmap-jsapi'; ``` 3. 创建百度地图实例和信息窗口Vue组件的`mounted`生命周期,可以创建百度地图实例和信息窗口: ``` mounted() { const map = new BMap.Map('map-container'); const point = new BMap.Point(116.404, 39.915); map.centerAndZoom(point, 15); const marker = new BMap.Marker(point); map.addOverlay(marker); const infoWindow = new BMap.InfoWindow('<p>这是一个自定义信息窗口</p>'); marker.addEventListener('click', function(){ this.openInfoWindow(infoWindow); }); } ``` 在上述代码,首先创建了一个BMap.Map实例,并定位到北京市心点。然后创建了一个BMap.Marker实例,并添加到地图上。最后创建了一个BMap.InfoWindow实例,设置了自定义信息窗口内容,并添加到BMap.Marker实例上。 4. 自定义信息窗口样式 为了自定义信息窗口样式,可以在创建BMap.InfoWindow实例时,传入一个样式对象,并通过CSS样式来设置信息窗口的样式: ``` const infoWindow = new BMap.InfoWindow(` <div class="info-window"> <h3 class="title">这是一个自定义信息窗口</h3> <p class="content">欢迎来到百度地图JavaScript API</p> </div> `, { width: 300, height: 150, enableMessage: false }); ``` 在上述代码,通过HTML字符串构建了一个自定义信息窗口,并为其添加了CSS样式。 完整代码如下: ``` <template> <div id="map-container" style="width: 100%; height: 500px;"></div> </template> <script> import BMap from 'bmap-jsapi'; export default { mounted() { const map = new BMap.Map('map-container'); const point = new BMap.Point(116.404, 39.915); map.centerAndZoom(point, 15); const marker = new BMap.Marker(point); map.addOverlay(marker); const infoWindow = new BMap.InfoWindow(` <div class="info-window"> <h3 class="title">这是一个自定义信息窗口</h3> <p class="content">欢迎来到百度地图JavaScript API</p> </div> `, { width: 300, height: 150, enableMessage: false }); marker.addEventListener('click', function(){ this.openInfoWindow(infoWindow); }); } } </script> <style> .info-window { background-color: #fff; border: 1px solid #ccc; padding: 10px; font-size: 16px; } .title { font-size: 24px; margin-bottom: 10px; } .content { margin: 0; } </style> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值