首页 > 其他分享 >高德地图Demo

高德地图Demo

时间:2023-04-24 14:48:29浏览次数:35  
标签:function map console log Demo 地图 AMap position 高德

第一步先创建高德账号,创建应用获取key和密匙,自行百度。

npm安装

 npm i @amap/amap-jsapi-loader --save

 

引入插件使用,此处是vue3引入,主要使用了位置和天气功能

<template>
   <div class="page">
    <div class="icon"><img src="../assets/logo.png" alt=""></div>
    <div id="container"></div>
   </div>
   <button @click="showNowPosition">确定</button>
</template>

<script>
import { onMounted,reactive } from 'vue'
import AMapLoader from "@amap/amap-jsapi-loader";
import coordtransform from 'coordtransform';
export default {
  name: 'HelloW',
  setup(){

    let nowPosiotion = []
    function getCurrentPosition(){
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition, showError);
      } else {
          alert("Geolocation is not supported by this browser.");
      }

      function showPosition(position) {
          let latitude = position.coords.latitude;
          let longitude = position.coords.longitude;
          // 在这里处理获取到的位置信息
          // 转高德经纬度,当前就是高德经纬度
          // nowPosiotion = coordtransform.wgs84togcj02(longitude,latitude);
          nowPosiotion = [longitude,latitude]
          console.log(nowPosiotion)
      }

      function showError(error) {
          switch(error.code) {
              case error.PERMISSION_DENIED:
                  alert("User denied the request for Geolocation. please open");
                  break;
              case error.POSITION_UNAVAILABLE:
                  alert("Location information is unavailable.");
                  break;
              case error.TIMEOUT:
                  alert("The request to get user location timed out.");
                  break;
              case error.UNKNOWN_ERROR:
                  alert("An unknown error occurred.");
                  break;
          }
      }
    }

    //存储map对象
    let map
    //存储地址对象
    let geocoder
    //储存天气对象
    let weather

    //存储标点信息
    const state = reactive({
        path: [],
        current_position: [],
    });
    
    //进行地图初始化
    function initMap() {
      AMapLoader.load({
        key: "你的key值", // 申请好的Web端开发者Key,首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
      })
      .then((AMap) => {
        map = new AMap.Map("container", {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          pitch:65,//地图仰视角
          zoom: 10, //初始化地图级别
          center: nowPosiotion?nowPosiotion:[121.4737021, 31.2303904], //初始化地图中心点位置,谷歌有可能获取不到当前位置,需要设置https
        });
        //添加插件
        AMap.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye",'AMap.Geocoder','AMap.Weather'], function () {
          //异步同时加载多个插件
          map.addControl(new AMap.HawkEye()); //显示缩略图
          map.addControl(new AMap.Scale()); //显示当前地图中心的比例尺
          //逆编码实例
        })
    
        geocoder = new AMap.Geocoder({
            city: '010'
          });
        // 创建一个 Marker当前位置实例:
        let marker = new AMap.Marker({
            // position: new AMap.LngLat(121.4737021, 31.2303904),   // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
            position:nowPosiotion,
            title: '当前位置'
        });

        weather = new AMap.Weather();

        //将创建的点标记添加到已有的地图实例:
        map.add(marker);

        // 单击事件
        map.on("click", (e) => {
          console.log(e);
          // state.current_position = [e.lnglat.KL, e.lnglat.kT];
          // state.path.push([e.lnglat.KL, e.lnglat.kT]);
          // console.log(state)
          // addMarker();
          // addPolyLine();
          // 地图按照适合展示图层内数据的缩放等级展示
          // map.setFitView();
        });
        //移动结束事件
        map.on('moveend',(e)=>{
          // console.log(map.getCenter().toString())
        })

        //地图缩放改变事件
        map.on('zoomchange', (e)=>{
          //设置中心点
          // map.setCenter(nowPosiotion);
        });
        // 实例化点标记
        function addMarker() {
          const marker = new AMap.Marker({
            icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            position: state.current_position,
            offset: new AMap.Pixel(-26, -54),
          });
          map.add(marker)
        }

      // 折线
      function addPolyLine() {
        const polyline = new AMap.Polyline({
          path: state.path,
          isOutline: true,
          outlineColor: "#ffeeff",
          borderWeight: 1,
          strokeColor: "#3366FF",
          strokeOpacity: 0.6,
          strokeWeight: 5,
          // 折线样式还支持 'dashed'
          strokeStyle: "solid",
          // strokeStyle是dashed时有效
          // strokeDasharray: [10, 5],
          lineJoin: "round",
          lineCap: "round",
          zIndex: 50,
        });
        map.add([polyline]);
      }
      }).catch((e) => {
            console.log(e);
        });
    }

    onMounted(()=>{
      getCurrentPosition()
      initMap();
    })

    function showNowPosition(){
      let lnglat = [map?.getCenter()?.KL,map?.getCenter()?.kT]//这里是需要转化的经纬度
      // console.log(lnglat,geocoder.getAddress)
      geocoder.getAddress(lnglat?lnglat:[], function(status, result) {
        console.log(status,result)
        if (status === 'complete' && result.regeocode) {
          console.log(result.regeocode.formattedAddress);
          //根据位置获取天气
          weather.getLive(result.regeocode.addressComponent.district, function(err, data) {
            console.log(data);
          });
        } else {
          console.log('根据经纬度查询地址失败');
        }
      })
    }
    return{
      showNowPosition
    }
  }
}
</script>

<style scoped>
#container {width:1200px; height: 610px; }  

/deep/ .amap-icon img{
  position: relative;
}
.page{
  position: relative;
  width:1200px; height: 610px;
}
.icon{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  z-index: 2000;
  width: 30px;
  height: 30px;
}
.icon > img{
    width: 30px;
    height: 30px;
    position: relative;
    top: -20px;
}
</style>

注意:模板中只引入了可以,获取位置时请求不到,因为还要密匙,可以在index.html模板中引入

   <script type="text/javascript">
      window._AMapSecurityConfig = {
      securityJsCode:'你的密匙',
      }
    </script>

另外,获取本地位置的api:navigator.geolocation.getCurrentPosition在谷歌地图中可能会走谷歌引擎,获取不到,需要设置https请求,目前edag和火狐是没有问题的。

 

标签:function,map,console,log,Demo,地图,AMap,position,高德
From: https://www.cnblogs.com/lijun12138/p/17349439.html

相关文章

  • BIP2087E: Broker BrokerDemo was unable to process the internal configuration mes
    今天部署的时候,.出现下面这个错误,BIP4041E:执行组'默认'发现一个无效的配置信息。BIP2210E:无效的配置信息:属性名称'allowQueryWSDL'不为目标对象的有效'Main.TestMessageFlows。' Beginrunningtask[Deploying[BrokerDemo.bar]toexecutiongroup[default]]BIP2087E:Broker......
  • pyqt gui demo
    一些供学习的样例:#-*-coding:utf-8-*-"""@Time:2023/4/2410:53@FileName:gui_demo.py"""importsysfromPyQt5.QtWidgetsimport*fromPyQt5.QtCoreimport*fromPyQt5.QtGuiimport*fromPyQt5importQtGui,QtWidgets,QtC......
  • 【前端可视化】ECharts中国地图+散点图demo
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metahttp-equiv="X-UA-Compatible"content="IE=edge"/><metaname="viewport"content="w......
  • 高德地图授权
    公司出行项目用到了高德地图。用了几个月,最近收到高德官方电话告知:高德地图接口商用需授权才能使用。授权费,基础版5w元/每年。5万一年对小企业来说,有点负担重重重重。但有没办法,只能给钱。三大地图都要求授权才能使用:高德商用授权:https://lbs.amap.com/upgrade#business百度......
  • ai问答:使使用 Vue3 组合式API 和 TypeScript 父子组件demo
    这是一个使用Vue3组合式API和TypeScript的简单父子组件示例父组件Parent.vue:<template><div><p>{{msg}}</p><Child/></div></template><scriptlang="ts">import{ref}from'vue'import......
  • v3+ts中使用百度地图 附带搜索地址
     话不多说直接上源码letaddressInfo=reactive({longitude:"",//经度latitude:"",//纬度province:"",//省city:"",//市district:"",//区address:"",//详细地址});letopenMap=ref(fals......
  • hyperf3搭建grpc demo
    搭建环境如果是linux因为默认版本的gcc是4.8.5编译安装grpc失败,必须升级gcc的版本可以参考《php安装grpc扩展》。gcc重新编译比较耗时所以还是比较建议用dockerDockerfileFROMphp:8.1#安装必要的工具和依赖RUNapt-getupdate\&&apt-getinstall-y--no-insta......
  • 如何采集百度地图上搜索电话,导出到excel里去
      很多销售推广人员问,怎么样能够快速的把BAIDU地图左边的搜索列表里的商家地图,电话采集出来,导出到EXCEL里。我就开发了一个小软件,专门为快速的实现导出数据到EXCEL。  为了使用方便,已经将全国的所又省份,每个省份里包含的地级市,每个地级市包含的区县,都收集数据集成到......
  • 如何采集高德地图商家电话资料,导出成excel里?
     有很多人问我地图商家电话采集怎么做?怎么样能够快速的把高德地图左边的搜索列表里的商家地图,电话采集出来,导出到EXCEL里?如何快速地将高德地图里的商家电话资料导出EXCEL? 操作步骤:1.选择你要采集的省份,城市列表里就会有相应的省份的城市列表。2.选择要采集的城市,......
  • 地图商家电话采集工具/采集软件
    现在的获客工具有很多,包括地图、抖音、美团、网站等,当然每种获客方式对于不同需求的人来说效果是不一样的,所以对于想获取实体店商家的人来说,采集地图商家手机号是最精准有效的获客方式。为什么推荐地图商家采集呢?因为现在各大对于地图实体店的覆盖率都很高了,实体店本身也都在各......