This is the 19th day of my participation in the August Wenwen Challenge.More challenges in August

Introduction to the

This article mainly explains the layer perspective function by controlling the layer, level and size. Use the layer listener event PRERender to listen for layers before rendering and Postrender to listen for layers after rendering.

To realize the DEMO

Initialize the map

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>Document</title>
  </head>
  <style type="text/css">
    .map {
      height: 500px;
      width: 100%;
    }
  </style>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/css/ol.css" />
  <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/build/ol.js"></script>
  <body>
    <div id="map" class="map"></div>
  </body>
  <script>
    / / layer
    var roads = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: 'https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}'})})/ / the layer 2
    var imagery = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'})})/ / instance
    const container = document.getElementById('map')

    var map = new ol.Map({
      target: container,
      layers: [roads, imagery],
      view: new ol.View({
        center: ol.proj.fromLonLat([37.41.8.82]),
        zoom: 4})})</script>
</html>
Copy the code

  • Here we have created two layers. Remember that the default layer is the one added later than the one in front.
  • In order to achieve the effect of layer perspective, it is necessary to draw a layer in a fixed area on the base layer to achieve the effect.

Gets the coordinate position of the mouse on the map

    // Map pixel position
    let mousePosition = null

    container.addEventListener('mousemove'.function (event) {
      // getEventPixel(event) returns the location of the map pixel based on the current location of the event.
      mousePosition = map.getEventPixel(event)

      // render()
      map.render()
    })

    container.addEventListener('mouseout'.function () {
      mousePosition = null
      map.render()
    })
Copy the code
  1. Create global variables (mousePosition) Save mouse location in real time.
  2. By listening on the containerMouse over eventsGets the current location window position, usinggetEventPixel()Convert to geographic location.
  3. Listen for the container’s mouse out event to cancel the location.
  4. Each time you listen, you need to redraw the map to update the perspective layer content.

Listen to layer events


    / / radius
    let radius = 75
    // Before rendering the layer
    imagery.on('prerender'.function (event) {
      const ctx = event.context
      ctx.save() / / save
      ctx.beginPath()
      if (mousePosition) {
        ctx.arc(mousePosition[0], mousePosition[1], radius, 0.2 * Math.PI)
        ctx.lineWidth = (5 * radius) / radius
        ctx.strokeStyle = 'rgba (0,0,0,0.5)'
        ctx.stroke()
      }
      // Use clipping to load only data inside the circle
      ctx.clip()
    })

    // After the layer is rendered
    imagery.on('postrender'.function (event) {
      const ctx = event.context
      ctx.restore()
    })
Copy the code
  1. This is a circle, you can customize other shapes.
  2. By Layer eventprerenderLayer instance returned in Listener before layer renderingcanvas. Make sure you save the state herectx.save()Through themousePositionGet the coordinates of the mouse, drawing graphics at will, usingclip()Crop the canvas to show only the clipped content.
  3. throughpostrenderAfter rendering the layer. Restorative savedcanvasContent presentation.

Additional features

document.addEventListener('keydown'.function (evt) {
      console.log(100)
      if (evt.keyCode === 38) {
        console.log(1)
        // If the user presses '↑', the radius of the telescope increases by 5 pixels
        radius = Math.min(radius + 5.150)
        map.render()
        evt.preventDefault()
      } else if (evt.keyCode === 40) {
        // If the user presses the '↓' key, the telescope radius is reduced by 5 pixels
        radius = Math.max(radius - 5.25)
        map.render()
        evt.preventDefault()
      }
    })
Copy the code
  • Listen for the global keyboard event to change the shape of the perspective layer we drew. Of course, we also need to pay attention to this after modificationmap.render()Redraw the map to show the latest effects.