In this article

Display the map in a different container.

No matter what you do on the map, when you switch containers, everything you do is synchronized.




Train of thought

Use the method provided by OL to get the current map container and set the map to a new container.

  • Map.getTarget()Gets the container where the current map is located
  • Map.setTarget()Sets the map to the specified container




coding

<template>
  <div class="map__container">
    <! -- Map container 1 -->
    <div id="map1" class="map__x"></div>
      
    <! -- Map container 2 -->
    <div id="map2" class="map__x"></div>
  </div>

  <! -- Toggle map container button -->
  <button class="btn" @click="changeMap">change</button>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import OSM from 'ol/source/OSM' // Note: [OSM cannot be used in actual development because there is a problem with the boundaries of the Chinese map in OSM !!!!]
import 'ol/ol.css'

const map = ref(null) // Bind the map instance variables

// Initialize the map and render
function initMap () {
  // Map instance
  map.value = new Map({
    layers: [ / / layer
      new Tile({
        source: new OSM() // Layer data source})].view: new View({ // Map view
      projection: "EPSG:4326".// Coordinates, EPSG:4326 and EPSG:3857
      center: [114.064839.22.548857].// Shenzhen coordinates
      minZoom:10.// Minimum map zoom level
      zoom: 12 // Map zoom level (default level when opening the page)
    })
  })

  map.value.setTarget('map1') // Use setTarget to bind the map container
}

// Toggle container events
function changeMap() {
  // Get the current map container and judge
  let target = map.value.getTarget() === 'map1' ? 'map2' : 'map1'
  // Reset the map container
  map.value.setTarget(target)
}

onMounted(() = > {
  // Perform map initialization after the element is loaded
  initMap()
})
</script>

<style lang="scss" scoped>
.map__container {
  width: 800px;
  height: 380px;
  margin-bottom: 40px;
  display: flex;
  justify-content: space-between;

  .map__x {
    width: 380px;
    height: 380px;
    box-sizing: border-box;
    border: 1px solid #ccc; }}</style>
Copy the code


let target = map.value.getTarget() === 'map1' ? 'map2' : 'map1'

Returns map2 if currently in map1, map1 otherwise. By doing this you can switch the map back and forth between containers.




More recommended

This example shows address (vite+vue3+ OL)

This example repository (vite+vue3+ OL)

Ol used in VUe2 (preview)

Ol is used in VUe2 (warehouse)

OpenLayers website

WebGIS: OpenLayers (2nd Edition)

If you don’t know what OpenLayers is, read: “Vite + Vue3 + OpenLayers start”