前端PC端使用地图步骤(高德)

注册地图key

使用地图前,需要到对应官网申请key
1.首先,注册开发者账号,成为高德开放平台开发者
2. 登陆之后,在进入「应用管理」 页面「创建新应用」
3. 为应用添加 Key,「服务平台」一项请选择「 Web 端 ( JSAPI )」

项目中引用

申请完key之后,这里已后台系统为例,使用地图。
1.在index.html,一般在public文件夹下或根目录


image.png

引用相关文件,这里使用了地图工具,有兴趣可以官网可以了解下AMap.Geocode

    <link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css"/>
    <script src="https://cache.amap.com/lbs/static/es5.min.js"></script>
    <script src="https://webapi.amap.com/maps?v=1.4.8&key=你申请的key&plugin=AMap.MouseTool&plugin=AMap.Geocoder"></script>
    <script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>

2.引用完之后,项目基本可以使用了,这里使用组件的方式引入


image.png
utils.js,这里将地图对象的创建和一些需要的功能的方法统一起来,后续方便调用
const _clickMarker = Symbol('_clickMarker');
const _addPolygon = Symbol('_addPolygon');
const _addOtherPolygon = Symbol('_addOtherPolygon');
const _deleteNode = Symbol('_deleteNode');
let polylines = [];
let polyEditor;
let polygon;
let markerPoint = [];
class Amap {
  constructor(map, amap) {
    if (!map || !amap) {
      throw new Error('map or amap is required');
    }
    this.map = map;
    this.amap = amap;
    this.path = [];
  }


  addTeamPoint (points) {  // 通过坐标以红点显示
    const {
      map,
      amap
    } = this;
    var markerContent = "<div style='width:10px;height:10px;background:red;border-radius:50%'></div>";
    points.forEach(item => {
      const notMarker = new amap.Marker({
        position: item,
        content: markerContent,
      });
      map.add(notMarker);
      notMarker.setLabel({
        offset: new amap.Pixel(-60, -20), // 修改label相对于maker的位置
        content: 123123141231
      });
      map.setFitView(notMarker);
    });
  }
  addPoint (lnglat, labelShow) {
    const {
      map,
      amap
    } = this;
    map.remove(markerPoint);
    markerPoint = [];
    const position = new amap.LngLat(lnglat.lng, lnglat.lat);
    const marker = new amap.Marker({
      position,
      // 以 icon 的 [center bottom] 为原点
      offset: new amap.Pixel(-13, -30)
    });
    if (labelShow === 1) {
      marker.setLabel({
        offset: new amap.Pixel(-60, -20), // 修改label相对于maker的位置
        content: 123123141231
      });
    }
    // 将 markers 添加到地图
    map.add(marker);
    markerPoint.push(marker);
    map.setFitView(marker);
  }

  startPoint (callback) {
    polygon.on('click', (e) => {
      this.addPoint(e.lnglat);
      callback(e.lnglat);
    });
  }

  setData ({
    path,
    point,
  }) {
    const {
      amap
    } = this;
    if (point) {
      this[_addPolygon](path);
      this.addPoint(new amap.LngLat(point[0], point[1]));
    } else {
      this[_addOtherPolygon](path);
    }
  }

  // 画圆
  circleDrawing ({
    point,
    deliverRange,
    labelShow
  }) {
    const {
      map,
      amap
    } = this;
    const circle = new amap.Circle({
      center: [point[0], point[1]], // 圆心位置
      radius: deliverRange, // 半径
      fillColor: '#1791fc40',
      strokeColor: '#FF33FF'
    });
    this.addPoint(new amap.LngLat(point[0], point[1]), labelShow);
    circle.setMap(map);
  }

  selectionPoint (callback) {
    this.map.on('click', (e) => {
      this.addPoint(e.lnglat);
      callback(e.lnglat);
    });
  }

  setPoint (point) { // 设置地图标点
    const {
      amap
    } = this;
    this.addPoint(new amap.LngLat(point[0], point[1]));
  }

  // 画线
  addPolyline (path) {
    const {
      map,
      amap
    } = this;
    map.remove(polylines);
    polylines = [];
    const polyline = new amap.Polyline({
      path,
      isOutline: true,
      outlineColor: '#ffeeff',
      borderWeight: 3,
      strokeColor: '#3366FF',
      strokeOpacity: 1,
      strokeWeight: 6,
      strokeStyle: 'solid',
      strokeDasharray: [10, 5],
      lineJoin: 'round',
      lineCap: 'round',
      zIndex: 50
    });
    polyline.setMap(map);
    polylines.push(polyline);
    // 缩放地图到合适的视野级别
    map.setFitView([polyline]);
  }

  // 清除地图上所有的覆盖物
  clearMap () {
    this.map.clearMap();
  }

  // 开始编辑
  polyEditorStart () {
    if (polyEditor) {
      polyEditor.open();
    }
  }

  // 关闭编辑
  polyEditorClose (callback) {
    if (polyEditor) {
      polyEditor.close();
      callback(this.path);
    }
  }

  // 检查点是否在多边形内
  isPointInRing (point, path) {
    const {
      amap
    } = this;
    if (polyEditor) {
      polyEditor.close();
    }
    const isPointInRing = amap.GeometryUtil.isPointInRing(point, path);
    return isPointInRing;
  }

  autocomplete () { // 输入相关关键字,联想相关地点
    const {
      map,
      amap
    } = this;
    console.log(amap);
    amap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], () => {
      const autoOptions = {
        city: '广州', // 城市,默认全国
        input: 'pickerInput' // 使用联想输入的input的id
      };
      const autocomplete = new amap.Autocomplete(autoOptions);
      amap.event.addListener(autocomplete, 'select', (e) => {
        map.setCenter(e.poi.location);
      });
    });
  }

  geolocation () { // 获取当前位置
    const {
      map,
      amap
    } = this;
    map.plugin('AMap.Geolocation', () => {
      const geolocation = new amap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位,默认:true
        timeout: 10000, // 超过10秒后停止定位,默认:无穷大
        maximumAge: 0, // 定位结果缓存0毫秒,默认:0
        convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
        showButton: true, // 显示定位按钮,默认:true
        buttonPosition: 'LB', // 定位按钮停靠位置,默认:'LB',左下角
        buttonOffset: new amap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
        showMarker: true, // 定位成功后在定位到的位置显示点标记,默认:true
        showCircle: true, // 定位成功后用圆圈表示定位精度范围,默认:true
        panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
        zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition();
      amap.event.addListener(geolocation, 'complete', (e) => {
        console.log(e);
      }); // 返回定位信息
    });
  }

  [_clickMarker] (path, finishCallback) {
    if (path.length > 2) {
      this.clearMap();
      this[_addPolygon](path, finishCallback);
    }
  }

  [_deleteNode] (index, callback) {
    callback(index, this);
  }

  [_addPolygon] (path, finishCallback) { // 编辑构建多边形,可以通过点击的方式点与点连线构成多边形
    const {
      map,
      amap
    } = this;
    polygon = new amap.Polygon({
      path,
      isOutline: true,
      borderWeight: 3,
      strokeColor: '#FF33FF',
      strokeWeight: 6,
      strokeOpacity: 0.2,
      fillOpacity: 0.4,
      // 线样式还支持 'dashed'
      fillColor: '#1791fc',
      zIndex: 50
    });
    polygon.setMap(map);
    if (finishCallback) {
      finishCallback(path);
    }
    map.plugin(['AMap.PolyEditor'], () => {
      polyEditor = new amap.PolyEditor(map, polygon);
      polyEditor.on('end', (event) => {
        this.path = event.target.getPath();
      });
    });
  }

  [_addOtherPolygon] (path) { //绘制多边形图案
    const {
      map,
      amap
    } = this;
    const otherPolygon = new amap.Polygon({
      path,
      isOutline: true,
      borderWeight: 3,
      strokeColor: '#FF33FF',
      strokeWeight: 6,
      strokeOpacity: 0.2,
      fillOpacity: 0.4,
      fillColor: '#1791fc',
      zIndex: 50
    });
    otherPolygon.setMap(map);
  }

  getLocalBylnlt (data) { // 返回经纬度和地址转换的对象
    const {
      map,
      amap
    } = this;
    const geocoder = new amap.Geocoder({
      city: '010'
    });
    return geocoder;
  }
}

export default Amap;

创建组件
<template>
  <div
    :id="mapId"
    class="map-content"
    :style="{'height':height+'px'}"
  >
    <div id="pickerBox">
      <input
        id="pickerInput"
        ref="seach"
        placeholder="输入键字选取地点"
      >
      <div id="poiInfo" />
    </div>
  </div>
</template>
<script>
import MapUtils from './utils';

export default {
  props: {
    mapId: {
      type: String,
      required: true
    },
    type: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 500
    }
  },
  data () {
    return {
      map: null,
      AMap: window.AMap,
      utils: null,
      path: [],
      clickListener: null
    };
  },

  mounted () {
    const { mapId, AMap } = this;
    const map = new AMap.Map(mapId, {
      resizeEnable: true,
      // center: this.localMarker,
      zoom: 20,
      mapStyle: 'amap://styles/whitesmoke'
    });
    this.map = map;
    const utils = new MapUtils(map, AMap);
    this.utils = utils;
    if (!this.type) {
      utils.placeSearch();
    }
    // 加载BasicControl,loadUI的路径参数为模块名中 'ui/' 之后的部分
    window.AMapUI.loadUI(['control/BasicControl'], function (BasicControl) {
      // 缩放控件
      map.addControl(new BasicControl.Zoom({
        position: 'rb', // right bottom,右下角
        showZoomNum: true // 显示zoom值
      }));
    });
    const _this = this;
    AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], () => {
      const autoOptions = {
        city: '广州', // 城市,默认全国
        input: 'pickerInput' // 使用联想输入的input的id
      };
      const autocomplete = new AMap.Autocomplete(autoOptions);
      AMap.event.addListener(autocomplete, 'select', (e) => {
        const { lng, lat } = e.poi.location;
        utils.setPoint([lng, lat]);
        _this.getLocalBylnlt([lng, lat] , false);
      });
    });


  },
  methods: {
    // 地图选点 开启选点
    startPoint (callback) {
      const { utils } = this;
      this.$refs.seach.value = '';
      utils.selectionPoint(callback);
    },
    // 显示已有的标记
    setPoint (callback) {
      const { utils } = this;
      utils.setPoint(callback);
    },
    getLocalBylnlt (data, boolOpen) {
      const { utils } = this;
      let geocoder = null;
      if (!geocoder) {
        geocoder = utils.getLocalBylnlt();
      }
      if (boolOpen) {
        geocoder.getAddress(data, (status, result) => {
          if (result.info === "OK") {
            this.$emit("getLocalhost", { address: result.regeocode.formattedAddress, local: data });
          }
        })
      } else {
         this.$emit("getLocalhost", { address: "", local: data });
      }

    },
  }
};
</script>

<style>
.custom-content-marker {
  position: relative;
  width: 25px;
  height: 34px;
}

.custom-content-marker img {
  width: 100%;
  height: 100%;
}
#pickerBox {
  position: absolute;
  z-index: 9999;
  top: 2%;
  right: -5%;
  width: 300px;
}

#pickerInput {
  width: 200px;
  padding: 5px 5px;
}

#poiInfo {
  background: #fff;
}

.amap_lib_placeSearch .poibox.highlight {
  background-color: #cae1ff;
}

.amap_lib_placeSearch .poi-more {
  display: none !important;
}
.amap-sug-result {
  z-index: 9999;
}
</style>

引用


image.png
// 引用该组件文件所对应的方法
 // 开始选点
    selectionPoint () {
      this.$nextTick(() => {
        this.$refs.maps.startPoint((point) => {
          if (point) {
            this.latitude = point.lat;
            this.longitude = point.lng;
          }
        });
      })
    },
    getLocal () {
      this.localMapVis = true;
      this.selectionPoint();
      const longitude = 113.280353;
      const latitude = 23.125223;
      this.$nextTick(() => {
        this.$refs.maps.setPoint([longitude, latitude]);
      })
    },
    getMapInfo () {
      const { longitude, latitude } = this;
      this.$refs.maps.getLocalBylnlt([longitude, latitude], true);
    },
    getLocalhost (res) {
      console.log(res);
      this.latitude = res.local[1];
      this.longitude = res.local[0];
    }

功能方法描述
1.该组件可以在地图标记点
2.该组件可以通过选择联想输入的地址,设置标点
3.该组件可以通过标点获得当前地址详细信息和经纬度

image.png

其他方法示例


image.png

相关方法
画圆 、显示附近点

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354