【问题标题】:click handler leaflet on Vue 3 composition API单击 Vue 3 组合 API 上的处理程序传单
【发布时间】:2022-11-29 09:06:56
【问题描述】:

你好我想问一下 vue 3 组合 API 中的传单,当我点击地图时如何获取值 latlng。当鼠标在地图上单击时,我尝试了很多方法来获取 latlng。当我使用 @click="handleClick" 时,它只会获取鼠标事件,而不是我想要的值 latlng。 我尝试使用 map.on('click', function(e)) 但出现错误“无法读取未定义的属性(读取'on')” 任何人都可以帮助我解决问题吗?

  import { computed, ref, onMounted, onUnmounted, watch, reactive } from 'vue'
  import marker from '../../assets/mapMarker.svg'
  import leaflet from 'leaflet'

  let map
  // map = leaflet.map('map').setView([0, 0], 13)
  onMounted(() =>{
    map = leaflet.map('map').setView([0, 0], 13)
    leaflet.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
      maxZoom: 19,
      doubleClickZoom: 'false',
      attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    }).addTo(map);
    getGeoLocation()
  })
  
  const coords = ref(null)
  const fetchCoords = ref(null)
  const geoMarker = ref(null)

  const initGeoLocation = (lat, lng) => {
    map.setView([lat, lng], 13);
    leaflet.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
      maxZoom: 19,
      attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    }).addTo(map);
  }

  const plotGeoLocation = (lat, lng) => {
    const customMarker = leaflet.icon({
      iconUrl: marker,
      iconSize: [35,35],
    })
    geoMarker.value = leaflet.marker([lat, lng], { icon: customMarker }).addTo(map)
    map.setView([lat, lng], 10)
  }

  const getGeoLocation = () => {
    fetchCoords.value = true
    navigator.geolocation.getCurrentPosition(setCoords, getLocError)
  }

  const setCoords = (pos) => {
    fetchCoords.value = null
    initGeoLocation(pos.coords.latitude, pos.coords.longitude)
    const setSessionCoords = {
      lat: pos.coords.latitude,
      lng: pos.coords.longitude,
    }
    sessionStorage.setItem('coords', JSON.stringify(setSessionCoords))

    coords.value = setSessionCoords

    plotGeoLocation(pos.coords.latitude, pos.coords.longitude)

  } 

  const getLocError = (err) => {
    console.log(err)
  }

  map.on('click', function(e){
  var coord = e.latlng;
  var lat = coord.lat;
  var lng = coord.lng;
  console.log("You clicked the map at latitude: " + lat + " and longitude: " + lng);
  });
<template>
  <div class="h-96">
    <div id="map" class="h-full z-[1]">
    </div>
  </div>
</template>

【问题讨论】:

  • 对于初学者,您不应该在 onMounted 之外使用 map.on。您可以清楚地看到 let map 在设置中未定义

标签: javascript vue.js leaflet vuejs3 vue-composition-api


【解决方案1】:

只需分配: 让地图=未定义 然后使用您的方法获取 latlng 示例:

getLatLng(){map.on('click', function(e){console.log(e.latlng) }}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-09
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    相关资源
    最近更新 更多