天天看點

react+typescript+高德地圖react項目中使用高德地圖

react項目中使用高德地圖

基本項目使用create-react-app建立項目,并引入typescript

1. 申請高德key

2. 在index.html中引入高德地圖

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=申請的key&plugin=AMap.Geocoder"></script> 
           

3. 在頁面中使用

因為使用了ts是以需要先聲明一下高德地圖的AMap

不聲明的話會出現下圖錯誤

react+typescript+高德地圖react項目中使用高德地圖
import React, { Component } from 'react';
// 聲明AMap,也可以選擇在d.ts中聲明
declare let AMap: any;
           

接下來就能愉快的使用高德地圖了

const carImg = require('@/assets/img/car.png');

componentDidMount() {
    // console.log('window.AMap', window.AMap);
    const map = new AMap.Map('container', {
      // zoom:11,//級别
      // center: [116.4,39.92],
      resizeEnable: true
      // viewMode:'3D'//使用3D視圖
    });

    map.clearMap();  // 清除地圖覆寫物

    // 建立一個 Icon
    var carIcon = new AMap.Icon({
      // 圖示尺寸
      size: new AMap.Size(35, 35),
      // 圖示的取圖位址
      image: carImg,
      // 圖示所用圖檔大小
      imageSize: new AMap.Size(35, 35),
      // 圖示取圖偏移量
      imageOffset: new AMap.Pixel(0, 0)
    });

    var markers = [{
      icon: carIcon,
      position: [116.397428, 39.90923]
    }, {
      icon: carIcon,
      position: [116.368904, 39.913423]
    }, {
      icon: carIcon,
      position: [116.305467, 39.807761]
    }];

    // 添加一些分布不均的點到地圖上,地圖上添加三個點标記,作為參照
    markers.forEach(function(marker) {
      new AMap.Marker({
        map: map,
        icon: marker.icon,
        position: [marker.position[0], marker.position[1]],
        // 以 icon 的 [center bottom] 為原點
        offset: new AMap.Pixel(-13, -30)
      });
    });

    map.setFitView();
  }
           

詳細使用看高德官網了

4.效果

react+typescript+高德地圖react項目中使用高德地圖