【问题标题】:Setting Google Map Markers in Vue3 / Pinia在 Vue3/Pinia 中设置谷歌地图标记
【发布时间】:2022-12-23 05:20:01
【问题描述】:

我想根据从 vue3 pinia 商店获取的数据显示标记。我很难在地图上设置我的第一个标记:

<script setup>
import { onMounted, ref } from 'vue'
import { Loader } from '@googlemaps/js-api-loader'
import { useDiscoverItemStore } from "@/stores/DiscoverItemStore"
const discoverStore = useDiscoverItemStore()

const MAPS_API_KEY = 'api-key'

const loader = new Loader({ apiKey: MAPS_API_KEY })
const mapDiv = ref(null)
let map = ref(null)

onMounted(async () => {
  await loader.load()
  map.value = new google.maps.Map(mapDiv.value, {
    center: currPos.value,
    zoom: 13,
  })

  await discoverStore.fetchItems()
  let loc = new google.maps.LatLng(discoverStore.items[0].location[0], discoverStore.items[0].location[1])

  console.log(loc)
  let marker = new google.maps.Marker({
    position: loc,
    map, // have also tried `map: map` 
    title: "Hello World!",
  })

  // have also tried `marker.setMap(map)`
})
</script>

我的控制台告诉我setMap: not an instance of Map; and not an instance of StreetViewPanorama。这是我的控制台的完整读数:

为什么我不能将这个标记添加到我的谷歌地图mapref?任何想法将不胜感激。

【问题讨论】:

  • 也试过map: map你有没有试过map: map.value因为你做了map.value = new google.maps.Map这样做是有意义的 - 但为什么map需要成为一个参考?
  • 感谢@JaromandaX,这确实有效。请随时建议将其作为问题的答案。为什么 map 需要是 ref tbh 我是 vue 的新手所以我不确定。但是,没有它,它就不起作用。我关注了this tutorial,这可能会给你更多的见解。
  • 我想 map 也用在你没有展示的其他地方?
  • map ref 是被动的。除非你利用它的反应性,否则它不会从引用中受益,它可能是 onMounted 的本地变量

标签: javascript vue.js google-maps vuejs3 pinia


【解决方案1】:

你的谷歌地图实例在map.value

  let marker = new google.maps.Marker({
    position: loc,
    map: map.value,
    title: "Hello World!",
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    相关资源
    最近更新 更多