欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

arcgis?js完整懸停效果實(shí)現(xiàn)demo

 更新時(shí)間:2023年02月20日 14:33:22   作者:hopgoldy  
這篇文章主要為大家介紹了arcgis?js完整懸停效果實(shí)現(xiàn)demo詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

arcgis 中的懸停效果

arcgis 中的懸停效果并不如想象中那么容易實(shí)現(xiàn),本文會(huì)介紹如何完整的實(shí)現(xiàn)如下懸停效果,并對相關(guān)的技術(shù)細(xì)節(jié)進(jìn)行解釋,講解如何避免一些小坑。讓你不僅知其然,更知其所以然。

文章正文主要涉及對細(xì)節(jié)和原理的講解,如果你著急的話,文末有完整的使用 demo,需要自取。

效果拆分

從上面的 gif 里可以看的,一個(gè)完整的懸停效果包含三部分:

  • 鼠標(biāo)指針變?yōu)樾∈郑╬ointer)
  • 顯示標(biāo)簽名稱
  • 懸停圖標(biāo)放大

在網(wǎng)上有很多的文章都只是簡單的解釋了某一種效果(大多數(shù)都只是簡單的更新下鼠標(biāo)樣式),但是大概率是滿足不了需求的,下面咱們來一一介紹一下:

1、獲取鼠標(biāo)懸停事件回調(diào)

arcgis 中并不能通過類似 .addEventListener 或者 .on('hover-icon') 的形式直接監(jiān)聽圖標(biāo)的懸停事件,所以我們把這部分內(nèi)容單獨(dú)拿出來講。

我們知道 arcgis js 的實(shí)例化分兩部分:地圖創(chuàng)建和視圖創(chuàng)建:

const map = new Map({ layers: [baseMap] });
const view = new MapView({ container: "viewDiv", map });

map 對象就是地圖實(shí)例,包含了核心的地圖實(shí)現(xiàn),是不包含任何與顯示相關(guān)的功能的。而 view 則是視圖實(shí)例,負(fù)責(zé)把一個(gè)數(shù)字化的地圖顯示在我們眼前的,例如這里使用的 MapView 就是 2D 渲染,而 SceneView 則是負(fù)責(zé) 3D 地圖的渲染。

所以,我們可以通過 view.on('pointer-move', callback) 來監(jiān)聽鼠標(biāo)在視圖上的移動(dòng)操作,并通過另一個(gè)方法 view.hitTest 來檢測某個(gè)事件和那些地圖元素重合:

view.on('pointer-move', async e => {
  const { results = [] } = await view.hitTest(e);
  console.log('懸停到的元素', results);
});

這里可以優(yōu)化一下,使用 lodash 的 throttle 做一個(gè)節(jié)流,因?yàn)?hitTest 畢竟也是有一定消耗的異步操作,如果頻繁觸發(fā)的話不僅會(huì)導(dǎo)致卡頓,也會(huì)因?yàn)楫惒椒祷貙?dǎo)致已經(jīng)從元素上移走了,懸停效果卻出現(xiàn)的問題。注意這里不能用 arcgis 自帶的 promiseUtils.debounce 因?yàn)榉蓝恫⒉贿m合這個(gè)場景,并且它還會(huì)阻塞異步事件,會(huì)導(dǎo)致懸停效果不跟手。

view.on('pointer-move', _.throttle(async e => {
  const { results = [] } = await view.hitTest(e);
  if (results.length <= 0) return;
  // 后續(xù)邏輯
}, 50));

由于 result 是個(gè)數(shù)組,因?yàn)槭髽?biāo)有可能同時(shí)經(jīng)過了多個(gè)元素,所以說我們要在這里元素里匹配到我們要實(shí)現(xiàn)懸停效果的那部分。

注意,這里不能直接取 result[0],因?yàn)槭髽?biāo)可能會(huì)觸及多種類型的元素,例如底圖圖層、或者懸停后顯示的名稱,所以有可能會(huì)出現(xiàn)懸停到了名字上,擋住了后面的圖標(biāo)的情況:

view.on('pointer-move', _.throttle(async e => {
  const { results = [] } = await view.hitTest(e);
  if (results.length <= 0) return;
  // 找到第一個(gè)圖標(biāo),因?yàn)橛锌赡軕彝5搅松弦粋€(gè)圖標(biāo)的名稱 label 上
  const { graphic } = results.find(hit => {
    // 注意這里判斷了是否有 name 這個(gè)屬性,你的場景可能和我不同
    return hit?.graphic?.attributes?.name;
  }) || {};
  if (!graphic) return;
  // 后續(xù)邏輯
}, 50));

現(xiàn)在我們就能準(zhǔn)確且輕量的獲取到當(dāng)前懸停到了哪個(gè)圖標(biāo)上。

2、懸停時(shí)修改鼠標(biāo)指針

這個(gè)效果其實(shí)是最簡單的,在懸停時(shí)修改 css 的 cursor 屬性就行了,我們可以封裝一下:

const setCoursor = (type) => {
  // 這個(gè) viewDiv 要換成你的
  const containerDom = document.getElementById('viewDiv');
  if (containerDom) containerDom.style.cursor = type;
}

注意,這里獲取的目標(biāo) dom 是地圖的容器,不是 document.body,網(wǎng)上有很多文章都是直接設(shè)置 body 或其他全局樣式,這其實(shí)是不太合適的,因?yàn)榭倳?huì)出現(xiàn)鼠標(biāo)樣式?jīng)]有正確復(fù)原的情況,例如點(diǎn)擊地圖圖標(biāo)后彈出一個(gè) html 的彈窗,此時(shí)是不會(huì)觸發(fā) pointer-leave 事件的,如果這時(shí)候通過彈窗跳轉(zhuǎn)到的地圖之外的路由,就會(huì)發(fā)現(xiàn)鼠標(biāo)指針會(huì)一直卡在小手的樣式。

話說回來,封裝好后我們在對應(yīng)的地方都調(diào)用一下這個(gè)方法就可以了:

view.on('pointer-move', _.throttle(async e => {
  const { results = [] } = await view.hitTest(e);
  if (results.length <= 0) {
    setCoursor('default');
    return;
  }
  // 找到第一個(gè)圖標(biāo),因?yàn)橛锌赡軕彝5搅松弦粋€(gè)圖標(biāo)的名稱 label 上
  const { graphic } = results.find(hit => {
    return hit.graphic && hit.graphic.attributes && hit.graphic.attributes.name;
  }) || {};
  if (!graphic) {
    setCoursor('default');
    return;
  }
  setCoursor('pointer');
}, 50));
view.on('pointer-leave', () => {
  setCoursor('default');
});

然后就可以實(shí)現(xiàn)第一個(gè)效果了:

3、懸停時(shí)顯示標(biāo)簽名稱

這個(gè)的思路就是懸停時(shí)新建一個(gè) text symbol,進(jìn)行偏移并把圖標(biāo)的名稱設(shè)置上去,并在離開圖標(biāo)的時(shí)候移除這個(gè) symbol。

首先實(shí)現(xiàn)添加名字標(biāo)簽的方法,接受一個(gè) graphic 并生成對應(yīng)位置的名稱標(biāo)簽:

currentHoverLabel = null
const createHoverLabel = graphic =&gt; {
  const symbol = {
    type: 'text',
    text: graphic.attributes.name,
    font: { size: 14 },
    haloColor: 'white',
    haloSize: 2,
    color: 'black',
    // 這里進(jìn)行了偏移
    yoffset: -30,
  };
  // 如果已經(jīng)有了就復(fù)用之前的懸停圖例
  if (currentHoverLabel) {
    currentHoverLabel.geometry = graphic.geometry;
    currentHoverLabel.symbol = symbol;
  } else {
    currentHoverLabel = new Graphic({
      geometry: graphic.geometry,
      symbol,
    });
    view.graphics.add(currentHoverLabel);
  }
}

注意這里使用了緩存,如果已經(jīng)存在標(biāo)簽的話,就更新其位置和內(nèi)容而不是直接銷毀。

然后實(shí)現(xiàn)移除名稱的方法:

const removeHover = () => {
  view.graphics.remove(currentHoverLabel);
  currentHoverLabel = null;
}

最后塞進(jìn)我們剛才的回調(diào)里:

view.on('pointer-move', _.throttle(async e => {
  const { results = [] } = await view.hitTest(e);
  if (results.length <= 0) {
    setCoursor('default');
    removeHover();
    return;
  }
  const { graphic } = results.find(hit => {
    return hit.graphic && hit.graphic.attributes && hit.graphic.attributes.name;
  }) || {};
  if (!graphic) {
    setCoursor('default');
    removeHover();
    return;
  }
  setCoursor('pointer');
  createHoverLabel(graphic);
}, 50));
view.on('pointer-leave', () => {
  setCoursor('default');
  removeHover();
});

第二個(gè)效果也就做好了:

4、懸停時(shí)圖標(biāo)放大

這個(gè)效果會(huì)麻煩一點(diǎn)。首先明確一點(diǎn),懸停時(shí)不是修改 FeatureLayer 里的被懸停的圖標(biāo),而是在相同的位置放置一個(gè)更大的相同圖標(biāo),所以這里要求圖標(biāo)內(nèi)部不能是透明的,起碼放大后的圖標(biāo)要能整個(gè)覆蓋掉原先的圖標(biāo),不然就露餡了。

至于為什么我們下面會(huì)解釋,這里首先講解怎么實(shí)現(xiàn)。

如果你的圖標(biāo)類型都是一樣的話,那么就很簡單了,和上面創(chuàng)建名字標(biāo)簽一樣就行。

但是事與愿違,大多數(shù)場景下我們都會(huì)通過 UniqueValueRenderer 針對不同類型的元素顯示不同的圖標(biāo)。比如設(shè)備的類型、是否在線。所以說這里需要模擬 UniqueValueRenderer 的行為,讓顯示的大圖標(biāo)可以和原來一致。

有人可能會(huì)想,那我通過懸停事件拿到當(dāng)前懸停的圖標(biāo)對象,然后就可以直接調(diào)整大小或者復(fù)制,其實(shí)并不行,我們可以看到懸停事件里拿到的 graphic 并沒有對應(yīng)的 symbol:

因?yàn)?FeatureLeayer 并不是把每個(gè) symbol 和其對應(yīng)的要素綁定在一起的,而是交由 renderer 統(tǒng)一繪制,所以我們并不能在這里控制其顯示圖標(biāo)。

回歸正題,要想實(shí)現(xiàn)手動(dòng)區(qū)分顯示圖標(biāo),首先要把 UniqueValueRenderer 里控制渲染的字段獨(dú)立出來以便復(fù)用:

// 渲染使用的字段
const RENDER_FIELDS = ['f1', 'f2'];
// 渲染配置項(xiàng)
const RENDER_CONFIG = [
  { value: '1, 2', color: 'green' },
  { value: '2, 1', color: 'red' },
  { value: '1, 1', color: 'yellow' },
  { value: '2, 2', color: 'blue' },
]
// 生成渲染器
const renderer = new UniqueValueRenderer({
  field: RENDER_FIELDS[0],
  field2: RENDER_FIELDS[1],
  fieldDelimiter: ', ',
  defaultSymbol: { type: "simple-fill" },
  uniqueValueInfos: RENDER_CONFIG.map(({ value, color }) => {
    return {
      value,
      symbol: { type: "simple-marker", color },
    };
  }),
});
// 生成圖層
const pointLayer = new FeatureLayer({
  renderer,
  // ...
});

核心就是上面的 RENDER_FIELDS 和 RENDER_CONFIG,這一部分相對成熟的項(xiàng)目基本都有對應(yīng)的封裝了。接下來則是使用這兩個(gè)配置項(xiàng)渲染對應(yīng)的圖標(biāo):

const createHoverLegend = graphic => {
  const graphicMarkValue = RENDER_FIELDS
    .map(key => graphic.attributes[key])
    .filter(Boolean)
    .join(', ');
  const matchedLegend = RENDER_CONFIG.find(item => item.value === graphicMarkValue);
  if (!matchedLegend) return;
  const symbol = { type: "simple-marker", color: matchedLegend.color, size: 20 };
  // 如果已經(jīng)有了就復(fù)用之前的懸停圖例
  if (currentHoverLegend) {
    currentHoverLegend.geometry = graphic.geometry;
    currentHoverLegend.symbol = symbol;
  } else {
    currentHoverLegend = new Graphic({
      geometry: graphic.geometry,
      symbol,
    });
    view.graphics.add(currentHoverLegend);
  }
}

簡單來說就是按照這些字段名把值組裝起來,然后根據(jù)配置項(xiàng)找到對應(yīng)的圖標(biāo),并用剛才標(biāo)簽名字那一套添加到地圖里。

刪除懸停圖例的方法也要修改下:

const removeHover = () => {
  const needRemoveItem = [
    currentHoverLabel,
    currentHoverLegend,
  ].filter(Boolean);
  if (needRemoveItem.length <= 0) return;
  view.graphics.removeMany(needRemoveItem);
  currentHoverLabel = null;
  currentHoverLegend = null;
}

操作時(shí)盡量使用一個(gè) removeMany 而不是多個(gè) remove,這樣性能會(huì)更好點(diǎn)。最后把 createHoverLegend 添加到對應(yīng)的位置就行了。

arcgis 為什么這么設(shè)計(jì)

現(xiàn)在來介紹下為什么不能直接修改 FeatureLayer 中的點(diǎn)位,其實(shí)修改是可以修改的,通過 FeatureLayer.applyEdits 可以更新一個(gè)要素的屬性。

但是一方面這個(gè)修改是異步的,可能要很久才能看到效果,另一方面這個(gè)操作的性能損耗也不小,所以并不適合這個(gè)場景。

而從本質(zhì)上來說,arcgis js 是 web 版本的 arcgis server。所以你在 arcgis 的文檔里能看到很多 server 端實(shí)現(xiàn) / client 端實(shí)現(xiàn)。

server-side 是指直接通過 url 連接到對應(yīng)的 arcgis server 服務(wù),而 client-side 則是指在本地模擬創(chuàng)建一個(gè) arcgis server 的對應(yīng)服務(wù),這也是為什么其他的前端地圖庫創(chuàng)建圖層很快而 arcgis 創(chuàng)建圖層就要好幾秒的原因,arcgis 會(huì)完整的模擬一個(gè)龐大的 FeatureLayer。

這里就能發(fā)現(xiàn)一點(diǎn)端倪了,arcgis server 在發(fā)布時(shí)可以執(zhí)行很多“預(yù)烘焙”處理,這樣在查詢時(shí)就可以效率更高,但是這種操作在提升查詢速度的同時(shí)也降低了更新效率,所以沒法提供細(xì)粒度和快速的更新操作。

完整 demo 代碼:

下面代碼直接塞到一個(gè) html 里運(yùn)行即可:

<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta
    name="viewport"
    content="initial-scale=1,maximum-scale=1,user-scalable=no"
  />
  <title>
    懸停效果 demo
  </title>
  <style>
    html,
    body,
    #viewDiv {
      padding: 0;
      margin: 0;
      height: 100%;
      width: 100%;
    }
  </style>
  <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
  <link
    rel="stylesheet"
     rel="external nofollow" 
  />
  <script src="https://js.arcgis.com/4.25/"></script>
</head>
<script>
  require([
    "esri/Map",
    "esri/views/MapView",
    "esri/layers/TileLayer",
    "esri/renderers/UniqueValueRenderer",
    "esri/Graphic",
    "esri/layers/FeatureLayer",
  ], (Map, MapView, TileLayer, UniqueValueRenderer, Graphic, FeatureLayer) => {
    // 當(dāng)前懸停的圖標(biāo)名稱
    let currentHoverLabel = null
    // 當(dāng)前懸停的圖標(biāo)
    let currentHoverLegend = null
    const baseMap = new TileLayer({
      url: 'http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer',
    });
    const map = new Map({ layers: [baseMap] });
    const view = new MapView({
      container: "viewDiv",
      map,
      zoom: 7,
      center: [110, 36]
    });
    // 所有點(diǎn)位
    const POINTS = [
      { geo: { longitude: 110, latitude: 36 }, attr: { f1: '1', f2: '2', name: '綠色的標(biāo)簽' } },
      { geo: { longitude: 111, latitude: 36 }, attr: { f1: '2', f2: '1', name: '紅色的標(biāo)簽' } },
      { geo: { longitude: 110, latitude: 36.3 }, attr: { f1: '1', f2: '1', name: '黃色的標(biāo)簽' } },
      { geo: { longitude: 111, latitude: 36.3 }, attr: { f1: '2', f2: '2', name: '藍(lán)色的標(biāo)簽' } },
    ]
    const source = POINTS.map((item, index) => new Graphic({
      geometry: { type: 'point', ...item.geo },
      attributes: { pointId: index, ...item.attr },
    }))
    // 渲染使用的字段
    const RENDER_FIELDS = ['f1', 'f2'];
    // 渲染配置項(xiàng)
    const RENDER_CONFIG = [
      { value: '1, 2', color: 'green' },
      { value: '2, 1', color: 'red' },
      { value: '1, 1', color: 'yellow' },
      { value: '2, 2', color: 'blue' },
    ]
    // 生成渲染器
    const renderer = new UniqueValueRenderer({
      field: RENDER_FIELDS[0],
      field2: RENDER_FIELDS[1],
      fieldDelimiter: ', ',
      defaultSymbol: { type: "simple-fill" },
      uniqueValueInfos: RENDER_CONFIG.map(({ value, color }) => {
        return {
          value,
          symbol: { type: "simple-marker", color },
        };
      }),
    });
    // 生成圖層
    const pointLayer = new FeatureLayer({
      source,
      objectIdField: 'pointId',
      renderer,
      fields: [
        { name: 'pointId', type: 'oid' },
        { name: 'f1', type: 'string' },
        { name: 'f2', type: 'string' },
        { name: 'name', type: 'string' },
      ],
      outFields: ['*'],
    });
    map.add(pointLayer);
    const setCoursor = (type) => {
      const containerDom = document.getElementById('viewDiv');
      if (containerDom) containerDom.style.cursor = type;
    }
    /**
     * 創(chuàng)建懸停名稱提示
     */
    const createHoverLabel = graphic => {
      const symbol = {
        type: 'text',
        text: graphic.attributes.name,
        font: { size: 14 },
        haloColor: 'white',
        haloSize: 2,
        color: 'black',
        yoffset: -30,
      };
      // 如果已經(jīng)有了就復(fù)用之前的懸停圖例
      if (currentHoverLabel) {
        currentHoverLabel.geometry = graphic.geometry;
        currentHoverLabel.symbol = symbol;
      } else {
        currentHoverLabel = new Graphic({
          geometry: graphic.geometry,
          symbol,
        });
        view.graphics.add(currentHoverLabel);
      }
    }
    /**
     * 創(chuàng)建懸停圖例
     * 這里會(huì)找到對應(yīng)的圖例,創(chuàng)建一個(gè)新的圖例然后添加到地圖上
     */
    const createHoverLegend = graphic => {
      const graphicMarkValue = RENDER_FIELDS
        .map(key => graphic.attributes[key])
        .filter(Boolean)
        .join(', ');
      const matchedLegend = RENDER_CONFIG.find(item => item.value === graphicMarkValue);
      if (!matchedLegend) return;
      const symbol = { type: "simple-marker", color: matchedLegend.color, size: 20 };
      // 如果已經(jīng)有了就復(fù)用之前的懸停圖例
      if (currentHoverLegend) {
        currentHoverLegend.geometry = graphic.geometry;
        currentHoverLegend.symbol = symbol;
      } else {
        currentHoverLegend = new Graphic({
          geometry: graphic.geometry,
          symbol,
        });
        view.graphics.add(currentHoverLegend);
      }
    }
    /**
     * 移除懸停展示的圖標(biāo)和名稱
     */
    const removeHover = () => {
      const needRemoveItem = [
        currentHoverLabel,
        currentHoverLegend,
      ].filter(Boolean);
      if (needRemoveItem.length <= 0) return;
      view.graphics.removeMany(needRemoveItem);
      currentHoverLabel = null;
      currentHoverLegend = null;
    }
    view.on('pointer-move', _.throttle(async e => {
      const { results = [] } = await view.hitTest(e);
      if (results.length <= 0) {
        setCoursor('default');
        removeHover();
        return;
      }
      // 找到第一個(gè)圖標(biāo),因?yàn)橛锌赡軕彝5搅松弦粋€(gè)圖標(biāo)的名稱 label 上
      const { graphic } = results.find(hit => {
        return hit.graphic && hit.graphic.attributes && hit.graphic.attributes.name;
      }) || {};
      if (!graphic) {
        setCoursor('default');
        removeHover();
        return;
      }
      setCoursor('pointer');
      createHoverLabel(graphic);
      createHoverLegend(graphic);
    }, 50));
    view.on('pointer-leave', () => {
      setCoursor('default');
      removeHover();
    });
  });
</script>
<body>
  <div id="viewDiv"></div>
</body>
</html>

以上就是arcgis js完整懸停效果實(shí)現(xiàn)demo的詳細(xì)內(nèi)容,更多關(guān)于arcgis js 懸停效果的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論