0


GoogleMap——谷歌地图Api的使用

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

准备工作

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

开始使用

加载Maps JavaScript API

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

使用npm安装

npminstall @googlemaps/js-api-loader

导入到具体的页面

import{ Loader } from "@googlemaps/js-api-loader"

创建地图

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

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

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

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

const loader =newLoader({apiKey:"YOURKEY",version:"YOURVERSION",});
       loader.load().then(()=>{this.myMap =newgoogle.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 =newgoogle.maps.Map(document.getElementById("map"),{zoom:4,center: uluru,});// 创建标记const marker =newgoogle.maps.Marker({position: uluru,map: map,});//或者是const marker =newgoogle.maps.Marker({position: uluru,});
  marker.setMap(map);}

创建自定义标点

googlePositionHandle(){//地点let latLng =newgoogle.maps.LatLng(-25.344,131.031)// 创建地图const map =newgoogle.maps.Map(document.getElementById("map"),{zoom:4,center: latLng,});//设置Marker自定义图标的属性,size是图标尺寸,该尺寸为显示图标的实际尺寸,origin是切图坐标,该坐标是相对于图片左上角默认为(0,0)的相对像素坐标,anchor是锚点坐标,描述经纬度点对应图标中的位置var anchor =newgoogle.maps.Point(0,40)var size =newgoogle.maps.Size(32,32)var origin =newgoogle.maps.Point(0,0)var url=require('@/assets/img/p1.png')//创建图标var icon =newgoogle.maps.MarkerImage(
          url,
          size,
          origin,
          anchor,);//设置自定义标记图标let marker=newgoogle.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 =newgoogle.maps.Map(document.getElementById("map"),{zoom:4,center: uluru,});//标记上方的信息框var div='<div style="text-align: center">'+'<div>'+alias+'</div>'+'</div>'let infoWindow =newgoogle.maps.InfoWindow({content: div,});// 创建标记const marker =newgoogle.maps.Marker({position: uluru,map: map,});//打开信息框
  infoWindow.open({anchor: marker,map:map,});}

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

获取点击处的位置

const myMap =newgoogle.maps.Map(document.getElementById("GMap"),{center:{lat:-34.397,lng:150.644},zoom:8,});
       google.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 =newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude);
          map.setCenter(latlng);
          map.setZoom(15)var myMarker =newgoogle.maps.Marker({animation: google.maps.Animation.DROP,position: latlng
          });
          myMarker.setMap(map)});}});
    controlDiv.index =1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);}

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

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

npminstall echarts-extension-gmap --save

使用

import * as echarts from 'echarts';import'echarts-extension-gmap';
this.mapEChart=this.$echarts.init(document.getElementById('gmap'))var googleOption ={// load gmap componentgmap:{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.0roam: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(googleOption)//获取地图var gmap =this.mapEChart.getModel().getComponent('gmap').getGoogleMap();//创建标记var marker =newgoogle.maps.Marker({position: gmap.getCenter()});//设置
     marker.setMap(gmap);

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

总结

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


本文转载自: https://blog.csdn.net/weixin_51506327/article/details/128220536
版权归原作者 weixin_51506327 所有, 如有侵权,请联系我们删除。

“GoogleMap——谷歌地图Api的使用”的评论:

还没有评论