• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

GoogleMap——谷歌地图Api的使用

武飞扬头像
weixin_51506327
帮助5

最近公司想要在国外也使用地图功能,而我们国内使用的是高德地图,国外客户需要用谷歌地图,所以去了解了一下谷歌地图的使用,这里记录一下。

准备工作

首先你得有一个谷歌账号,然后得用一点小魔法,去谷歌地图官网申请一个API密钥,现在好像还需要绑定信用卡,有点麻烦,我就直接白嫖公司的了。

开始使用

加载Maps JavaScript API

  • 内嵌方式加载
<script async
    src="https://maps.谷歌apis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
  • 动态加载

使用npm安装

npm install @谷歌maps/js-api-loader

导入到具体的页面

import { Loader } from "@谷歌maps/js-api-loader"

创建地图

        <div style="height: 400px" id="GMap"></div>  
   initMap() {
      const loader = new Loader({
        apiKey: "YOURKEY",
        version: "YOURVERSION",
      });
      loader.load().then(() => {
        this.myMap = new 谷歌.maps.Map(document.getElementById("GMap"), {
        // 纬度在前,经度在后
          center: { lat: -34.397, lng: 150.644 },
          zoom: 8,
        });
      });
    },

这就完成了一个简单的地图创建。

然而,这种简单的地图是肯定不符合我们的需求,所以我们需要再加亿点细节。

首先,在初始化地图时,加上一些限制。

    const loader = new Loader({
         apiKey: "YOURKEY",
         version: "YOURVERSION",
       });
       loader.load().then(() => {
         this.myMap = new 谷歌.maps.Map(document.getElementById("BMap-125"), {
           center:  { lat: -34.397, lng: 150.644 },
           //缩放范围
           zoom: 6,
           minZoom: 2,
           maxZoom: 16,
           //限制拖拽范围,防止出现除地图外的灰色区域
           restriction: {
             latLngBounds: {
               north: 85,
               south: -85,
               east: 180,
               west: -180,
             },
           },
           //禁用键盘控制
           keyboardShortcuts:false,
           //关闭地图类型选择控件
           mapTypeControl:false
         });
       });
学新通

地图限制

  • 限制缩放等级:maxZoom和minZoom分别对应最大的缩放级别和最小的缩放级别,加上对应的限制,防止地图过大或过小。(补充:缩放等级对应的地图详细。1:世界,5:大陆/洲,10:城市,15:街道,20:建筑物)。
  • 限制地图边界:加上restriction,可以限制地图可以拖拽的范围,防止拖拽地图范围过大,出现灰色区域。
  • 地图控件:可以根据自己的需求,留下哪些地图控件,还可以自定义控件。

标记

为地图添加普通标记:

initMap() {
  // 坐标
  const uluru = { lat: -25.344, lng: 131.031 };
  // 创建地图
  const map = new 谷歌.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: uluru,
  });
  // 创建标记
  const marker = new 谷歌.maps.Marker({
    position: uluru,
    map: map,
  });
  //或者是
  const marker = new 谷歌.maps.Marker({
    position: uluru,
  });
  marker.setMap(map);
}
学新通

创建自定义标点

    谷歌PositionHandle(){
    	//地点
        let latLng = new 谷歌.maps.LatLng(-25.344,131.031 )
		// 创建地图
		  const map = new 谷歌.maps.Map(document.getElementById("map"), {
		    zoom: 4,
		    center: latLng,
		  });
        //设置Marker自定义图标的属性,size是图标尺寸,该尺寸为显示图标的实际尺寸,origin是切图坐标,该坐标是相对于图片左上角默认为(0,0)的相对像素坐标,anchor是锚点坐标,描述经纬度点对应图标中的位置
        var anchor = new 谷歌.maps.Point(0, 40)
        var size = new 谷歌.maps.Size(32, 32)
        var origin = new 谷歌.maps.Point(0, 0)
        var url=require('@/assets/img/p1.png')
        //创建图标
        var icon = new 谷歌.maps.MarkerImage(
          url,
          size,
          origin,
          anchor,
        );
        //设置自定义标记图标
        let marker=new 谷歌.maps.Marker({
          position: latLng,
          map: map,
          visible: true
        });
        marker.setIcon(icon)
        //标记添加点击事件,点击标记将地图中心设为标记点,放大地图
        marker.addListener('click', function() {
          map.setCenter(latLng)
          map.setZoom(16)
        });
    },
学新通

这是用png图片作为自定义图标,还可以使用svg图片作为图标,但是svg作为图标我暂时没搞懂,尤其是复杂的svg图片,所以就不写svg图片作为例子了。

创建信息窗口

  // 坐标
  const uluru = { lat: -25.344, lng: 131.031 };
  // 创建地图
  const map = new 谷歌.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: uluru,
  });
  //标记上方的信息框
  var div='<div style="text-align: center">' 
              '<div>' alias '</div>' 
           '</div>'
  let infoWindow = new 谷歌.maps.InfoWindow({
          content: div,
      });
       // 创建标记
  const marker = new 谷歌.maps.Marker({
    position: uluru,
    map: map,
  });
        //打开信息框
  infoWindow.open({
    anchor: marker,
    map:map,
    });
}
学新通

信息窗口是展示在标记的上方。

获取点击处的位置

       const myMap = new 谷歌.maps.Map(document.getElementById("GMap"), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8,
        });
       谷歌.maps.event.addListener(myMap, 'click', function (event) {
          const pos = {
            lat: event.latLng.lat(),
            lng: event.latLng.lng()
          };
          console.log(pos)
        });

打印的位置信息,就是鼠标点击的位置的经纬度。

创建自定义控件
谷歌默认是没有获取当前按钮的控件,如果我们有这种需求,我们可以自己自定义一个控件。

	//添加定位按钮,map为地图实例
    addYourLocationButton(map) {
    var controlDiv = document.createElement('div');
    var firstChild = document.createElement('button');
    firstChild.style.backgroundColor = '#fff';
    firstChild.style.border = 'none';
    firstChild.style.outline = 'none';
    firstChild.style.width = '40px';
    firstChild.style.height = '40px';
    firstChild.style.borderRadius = '2px';
    firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
    firstChild.style.cursor = 'pointer';
    firstChild.style.marginRight = '10px';
    firstChild.style.padding = '0px';
    firstChild.title = 'Your Location';
    controlDiv.appendChild(firstChild);

    var secondChild = document.createElement('div');
    secondChild.style.margin = '5px';
    secondChild.style.width = '18px';
    secondChild.style.height = '18px';
    secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
    secondChild.style.backgroundSize = '180px 18px';
    secondChild.style.backgroundPosition = '0px 0px';
    secondChild.style.backgroundRepeat = 'no-repeat';
    secondChild.style.margin='auto'
    secondChild.id = 'location_img';
    firstChild.appendChild(secondChild);
    firstChild.addEventListener('click', function() {
      if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          const latlng = new 谷歌.maps.LatLng(position.coords.latitude, position.coords.longitude);
          map.setCenter(latlng);
          map.setZoom(15)
          var myMarker = new 谷歌.maps.Marker({
            animation: 谷歌.maps.Animation.DROP,
            position: latlng
          });
          myMarker.setMap(map)
        });
      }
    });
    controlDiv.index = 1;
    map.controls[谷歌.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
  }
学新通

这样调用这个方法后,地图上就有了获取当前位置的图标了。

在Echarts中使用谷歌地图
Echarts中默认使用的是百度地图,如果想要使用谷歌地图,需要额外安装插件——echarts-extension-gmap,在github上可以找到。
安装

npm install echarts-extension-gmap --save

使用

import * as echarts from 'echarts';
import 'echarts-extension-gmap';
     this.mapEChart=this.$echarts.init(document.getElementById('gmap'))
     var 谷歌Option = {
       // load gmap component
       gmap: {
                center: [108.39, 39.9],
                // center: { lng: 108.39, lat: 39.9 },
                zoom: 4,
                disableDefaultUI:true,
                renderOnMoving: true,
                // the zIndex of echarts layer for Google Map. `2000` by default.
                echartsLayerZIndex: 2019,
                // whether to enable gesture handling. `true` by default.
                // since v1.4.0
                roam: true,
                minZoom: 2,
                maxZoom: 16,
                //限制拖拽范围,防止出现除地图外的灰色区域
                restriction: {
                  latLngBounds: {
                    north: 85,
                    south: -85,
                    east: 180,
                    west: -180,
                  },
                }
         },
         series: [
                {
                  type: 'scatter',
                  coordinateSystem: 'gmap',
                  data: this.mapPoints,//地图上的点
                  encode: {
                    value: 2
                  },
                  label: {
                    formatter: "{b}",
                    position: "right",
                    show: false
                  },
                  emphasis: {
                    label: {
                      show: true
                    }
                  }
                },
                {
                  type: 'effectScatter',
                  color:'#3ba308',
                  coordinateSystem: 'gmap',
                  data: data,
                  label: {
                    formatter: "{b}",
                    position: "right",
                    show: true
                  },
                  emphasis: {
                    label: {
                      show: true
                    }
                  }
                }
              ]
      		};
     this.mapEChart.setOption(谷歌Option)
     //获取地图
     var gmap = this.mapEChart.getModel().getComponent('gmap').getGoogleMap();
     //创建标记
	 var marker = new 谷歌.maps.Marker({ position: gmap.getCenter() });
	 //设置
     marker.setMap(gmap);     
学新通

这就完成了在谷歌地图上构建散点图。

总结

总的来说,谷歌地图的api使用起来还是比较友好的,官网写的也挺详细,如果有不清楚的地方可以多看看官网的例子。本人只是一个菜鸟,如果有什么不对的地方,欢迎评论区指出,谢谢。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfffhei
系列文章
更多 icon
同类精品
更多 icon
继续加载