js高德地圖添加點Marker,添加線段Polyline,添加一個區域Polygon(面)

来源:https://www.cnblogs.com/dreamtt/archive/2023/03/02/17173262.html
-Advertisement-
Play Games

高德地圖JS API 實例 親測可用 參考網站=> 阿裡雲數據可視化平臺(下載json用的):http://datav.aliyun.com/portal/school/atlas/area_selector?spm=a2crr.23498931.0.0.685915dd8QQdlv <script ...


高德地圖JS API 實例  親測可用

參考網站=> 阿裡雲數據可視化平臺(下載json用的):http://datav.aliyun.com/portal/school/atlas/area_selector?spm=a2crr.23498931.0.0.685915dd8QQdlv

<script src="//webapi.amap.com/maps?v=1.4.15&key=564abe9d4eef2535f9cc6ab1c1229cfc&plugin=Map3D,AMap.DistrictSearch,AMap.MarkerClusterer,AMap.Object3DLayer,AMap.MouseTool"></script>

1.渲染地圖

  const [initDataMap, setInitDataMap] = useState({
    centerCity: '拱墅區',
    defaultZoom: 12,
    centerPoint: { lng: 120.165533, lat: 30.329062 },
  });  
  //初始化地圖
  const initMap = () => {
    const { centerPoint } = initDataMap;
    const center = [centerPoint.lng, centerPoint.lat];
    const mzooms = [8, 19];
    const mzoom = 12;

    let map = new AMap.Map("AMapBox", {
      zoom: mzoom, //初始化地圖層級
      zooms: mzooms,
      rotateEnable: false, // 固定視角
      disableSocket: true,
      center: center,
    });

    mapRef.current = map;
    addAreaCoordinate(map); // 這個是渲染塊
  };

2.繪製Marker標記點

  // 繪製點
  const drawMarker = (data: any, map: any) => {
    const infoWindow = new AMap.InfoWindow({
      offset: new AMap.Pixel(5, -30),
      autoMove: true,
      closeWhenClickMap: true,
    });
    let ap: any = []
    data.forEach((item: any) => {
      if (item.lat && item.lng) {
        const ad = [item.lng, item.lat];
        const marker = new AMap.Marker({
          position: ad,
          icon: iconIMg, // 自己的icon
          map: map
        });

        ap.push(marker);
        setMarkerList(ap);

        const content = item.projectName;
        marker.on('click', () => {
          infoWindow.setContent(content);
          infoWindow.open(map, ad);
        });
      }
    });
    map.setFitView();
  }

3.繪製線段Polyline

  // 繪製線段
  const polylineInit = (lineArr: any, map: any, callBack: any) => {
    const infoWindowLine = new AMap.InfoWindow({
      offset: new AMap.Pixel(5, -30),
      autoMove: true,
      closeWhenClickMap: true,
    });

    const polyline = new AMap.Polyline({
      path: lineArr.list,          //設置線覆蓋物路徑
      strokeColor: "#3366FF", //線顏色
      strokeOpacity: 1,       //線透明度
      strokeWeight: 5,        //線寬
      strokeStyle: "solid",   //線樣式
      strokeDasharray: [10, 5] //補充線樣式
    });
    polyline.setMap(map);

    callBack(polyline);

    const content = `
      <div>
        <div style='border-bottom: 1px solid #F0F0F0; margin-bottom: 4px; padding: 4px 0 4px 0; color: #000000; font-size: 16px; '>${lineArr.roadName}</div>
        <div >所屬國企:${lineArr.belongCorpName}</div>
        <div>當前進度:${lineArr.currentStatusStr}</div>
        <a onclick="handleClickDetail(${lineArr.id})">查看詳情信息</a>
      <div>
    `

    if (callBackDetail) {
      polyline.on('click', (e: any) => {
        infoWindowLine.setContent(content);
        infoWindowLine.open(map, e.lnglat);
      });
    }
  }
  // 處理繪製線段  可不看嘎嘎···
  const dealPolylineInit = (arr: any, map: any) => {
    // map.clearMap();
    map.remove(polylineList);

    let ad: any = [];
    arr.forEach((item: any) => {
      const st = JSON.parse(item.locationMark);
      st.forEach((element: any) => {
        element.forEach((ele: any) => {
          ele.roadName = item.roadName;
          ele.belongCorpName = item.belongCorpName;
          ele.currentStatusStr = item.currentStatusStr;
          ele.id = item.roadId;
        });
      });
      ad.push(st);
    });
    const flatArr = ad.flat();

    const cloneDeepData = cloneDeep(flatArr);

    const opd: any = [];
    cloneDeepData.forEach((item: any) => {
      let lineArr: any = [];
      const obj: any = {};
      item.forEach((element: any) => {
        const ad = [element.lng, element.lat];
        obj.roadName = element.roadName;
        obj.belongCorpName = element.belongCorpName;
        obj.currentStatusStr = element.currentStatusStr;
        obj.id = element.id
        lineArr.push(ad);
      });
      obj.list = lineArr;
      polylineInit(obj, map, (v: any) => {
        opd.push(v)
      });
    })

    setPolylineList(opd)
  }

4.繪製區域Polygon

  const addAreaCoordinate = (map: any) => {
    const obj = gs_json || '';
    const points: any[] = [];
    obj?.features[0]?.geometry?.coordinates[0][0].map((item: any) => {
      points.push(new AMap.LngLat(item[0], item[1]));
    });

    const polygon = new AMap.Polygon({
      path: points,
      color: '#1CB9FF',
      weight: 3,
      opacity: 0.5,
      fillColor: '#1CB9FF',
      fillOpacity: 0.05,
    });

    map.add(polygon);
    map.setFitView(polygon);//視口自適應

  }

5.完整的代碼------(react寫的,但不影響cv)

import React, { useRef, forwardRef, useImperativeHandle, useEffect, useState } from 'react';
//antd
// 第三方組件
//@ts-ignore
import AMap from 'AMap';
import { cloneDeep } from 'lodash';
import gs_json from '@/assets/json/gongshu.json'; // 地圖區域的json數據

import iconIMg from '@/assets/productizationimg/local.png'

const AMapModal = forwardRef((props: any, ref: any) => {
  const { roadMapData, projectMapData, isShowLanLat, callBackDetail } = props;
  const mapRef = useRef<any>();
  const [markerList, setMarkerList] = useState<any>([]);
  const [polylineList, setPolylineList] = useState<any>([]);

  const [initDataMap, setInitDataMap] = useState({
    centerCity: '拱墅區',
    defaultZoom: 12,
    centerPoint: { lng: 120.165533, lat: 30.329062 },
  });

  //@ts-ignore
  window.document.handleClickDetail = function (id: any) {
    if (callBackDetail) {
      callBackDetail(id);
    }
  };

  // 根據levelCode向地圖中畫一個區域輪廓
  const addAreaCoordinate = (map: any) => {
    const obj = gs_json || '';
    const points: any[] = [];
    obj?.features[0]?.geometry?.coordinates[0][0].map((item: any) => {
      points.push(new AMap.LngLat(item[0], item[1]));
    });

    const polygon = new AMap.Polygon({
      path: points,
      color: '#1CB9FF',
      weight: 3,
      opacity: 0.5,
      fillColor: '#1CB9FF',
      fillOpacity: 0.05,
    });

    map.add(polygon);
    map.setFitView(polygon);//視口自適應

  }

  // 繪製點
  const drawMarker = (data: any, map: any) => {
    const infoWindow = new AMap.InfoWindow({
      offset: new AMap.Pixel(5, -30),
      autoMove: true,
      closeWhenClickMap: true,
    });
    let ap: any = []
    data.forEach((item: any) => {
      if (item.lat && item.lng) {
        const ad = [item.lng, item.lat];
        const marker = new AMap.Marker({
          position: ad,
          icon: iconIMg,
          map: map
        });

        ap.push(marker);
        setMarkerList(ap);

        const content = item.projectName;
        marker.on('click', () => {
          infoWindow.setContent(content);
          infoWindow.open(map, ad);
        });
      }
    });
    map.setFitView();
  }


  // 繪製線段
  const polylineInit = (lineArr: any, map: any, callBack: any) => {
    const infoWindowLine = new AMap.InfoWindow({
      offset: new AMap.Pixel(5, -30),
      autoMove: true,
      closeWhenClickMap: true,
    });

    const polyline = new AMap.Polyline({
      path: lineArr.list,          //設置線覆蓋物路徑
      strokeColor: "#3366FF", //線顏色
      strokeOpacity: 1,       //線透明度
      strokeWeight: 5,        //線寬
      strokeStyle: "solid",   //線樣式
      strokeDasharray: [10, 5] //補充線樣式
    });
    polyline.setMap(map);

    callBack(polyline);

    const content = `
      <div>
        <div style='border-bottom: 1px solid #F0F0F0; margin-bottom: 4px; padding: 4px 0 4px 0; color: #000000; font-size: 16px; '>${lineArr.roadName}</div>
        <div >所屬國企:${lineArr.belongCorpName}</div>
        <div>當前進度:${lineArr.currentStatusStr}</div>
        <a onclick="handleClickDetail(${lineArr.id})">查看詳情信息</a>
      <div>
    `

    if (callBackDetail) {
      polyline.on('click', (e: any) => {
        infoWindowLine.setContent(content);
        infoWindowLine.open(map, e.lnglat);
      });
    }
  }
  // 處理繪製線段
  const dealPolylineInit = (arr: any, map: any) => {
    // map.clearMap();
    map.remove(polylineList); // 清除線段的

    let ad: any = [];
    arr.forEach((item: any) => {
      const st = JSON.parse(item.locationMark);
      st.forEach((element: any) => {
        element.forEach((ele: any) => {
          ele.roadName = item.roadName;
          ele.belongCorpName = item.belongCorpName;
          ele.currentStatusStr = item.currentStatusStr;
          ele.id = item.roadId;
        });
      });
      ad.push(st);
    });
    const flatArr = ad.flat();

    const cloneDeepData = cloneDeep(flatArr);

    const opd: any = [];
    cloneDeepData.forEach((item: any) => {
      let lineArr: any = [];
      const obj: any = {};
      item.forEach((element: any) => {
        const ad = [element.lng, element.lat];
        obj.roadName = element.roadName;
        obj.belongCorpName = element.belongCorpName;
        obj.currentStatusStr = element.currentStatusStr;
        obj.id = element.id
        lineArr.push(ad);
      });
      obj.list = lineArr;
      polylineInit(obj, map, (v: any) => {
        opd.push(v)
      });
    })

    setPolylineList(opd)
  }

  const initMap = () => {
    const { centerPoint } = initDataMap;
    const center = [centerPoint.lng, centerPoint.lat];
    const mzooms = [8, 19];
    const mzoom = 12;

    let map = new AMap.Map("AMapBox", {
      zoom: mzoom, //初始化地圖層級
      zooms: mzooms,
      rotateEnable: false, // 固定視角
      disableSocket: true,
      center: center,
    });

    mapRef.current = map;
    addAreaCoordinate(map);
  };

  useEffect(() => {
    initMap();
  }, []);
  // 地圖道路線更新
  useEffect(() => {
    dealPolylineInit(roadMapData, mapRef.current);
  }, [roadMapData]);
  // 地圖點更新
  useEffect(() => {
    if (isShowLanLat == 1) {
      drawMarker(projectMapData, mapRef.current);
    } else {
      if (mapRef.current) {
        mapRef.current.remove(markerList);// 清除markerList點位
      }

    }
  }, [isShowLanLat, projectMapData]);

  return (
    <div>
      <div id='AMapBox' style={{ width: '100%', height: 640 }}></div>
    </div>
  );
})


export default AMapModal

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 摘要:關係資料庫中提供了一個關於集合的運算符SET操作符,其中包括以下操作:UNION/UNION ALL 並集、INTERSECT 交集、MINUS 差集。 本文分享自華為雲社區《GaussDB 中的SET操作符 (UNION, INTERSECT, MINUS)【玩轉PB級數倉GaussDB(D ...
  • 數據作為企業的核心資產,數據的準確性關於業務可靠性及企業品牌口碑。為此,還是推薦大家線上上主從環境、數據遷移、數據複製等場景中,配套使用可靠的數據校驗工具。平臺工具 NineData 以其完善的校驗能力、產品體驗、校驗速度、穩定性及數據源環境的廣泛適配性成為了市面上比較出彩的校驗工具,推薦大家使用。 ...
  • 在你需要的庫中執行如下存儲過程 CREATE PROCEDURE [dbo].[sp_select_talberowName] (@tablename varchar(max)) AS BEGIN SET NOCOUNT ON; --declare @sql varchar(max) --set @ ...
  • 使用PaginatedDataTable時解決最後一頁不夠當前行的話會有很空白行的問題 解決的場景: 比如下圖,28行數據,每頁5行最後一頁會多出兩行空白。 解決方法: 可以使用PaginatedDataTable中的onPageChanged 來進行操作 onPageChanged (發生翻頁時回 ...
  • block 和 none 問題 一些 CSS 屬性可以是動畫的,也就是說,當它的值改變時,它可以以平滑的方式改變。 做摺疊面板最簡單的方式是改變它的 block 或 none,這兩個屬性值不包含在可動畫屬性中。詳見:CSS animated properties。所以,設置 CSS 動畫(keyfr ...
  • html篇之《標簽分類和嵌套》 一、常用標簽 (1) <div></div> 一個區塊容器標記,可以包含圖片、表格、段落等各種html元素 (2) <span></span> 沒有實際意義,為了應用樣式 二、標簽分類 (1) 塊級標簽 獨占一行,會換行 包含: <div></div>、<ul></u ...
  • 定義 之所以叫簡單工廠是因為真的非常簡單,只要一個工廠(函數)就可以了,如果把被創建的對象稱為產品,把創建產品的對象或者方法稱為工廠,那麼只需要傳入不同的參數,就可以返回不同的產品(實例),這種模式就叫簡單工廠模式。 簡單工廠-餐館點菜 工廠模式其實就是將創建對象的過程單獨封裝在一個工廠中。 它很像 ...
  • html篇之《表單》 一、結構 <form action="url" method="post" name=""> <label>標註</label><input type="text" /> <select name=""> <option value="">選項1</option> <optio ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...