You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在vue-2-leaflet中调用API生成标记点,v-for渲染不显示如何解决

问题原因

你的代码存在两处核心错误导致标记无法正常渲染:

  1. 数据源不匹配:模板中v-for循环遍历的是markers数组,但接口请求成功后你把返回数据赋值给了未在data中声明的this.brews,markers始终为空,自然没有标记生成
  2. 存在两处常规渲染隐患:
    • 未引入Leaflet核心样式文件,会导致标记图标加载异常
    • 直接使用L.latLng但未导入Leaflet的L对象,可能触发L未定义的报错

修正步骤

  • 接口请求成功后把数据赋值给markers数组,替换原有的this.brews = json
  • 导入Leaflet的L对象和核心样式,同时添加默认图标修复逻辑,解决打包后图标路径异常的问题
  • 可以简化lat-lng参数传递,不需要额外封装方法,直接传经纬度数组即可被组件识别

修正后完整代码

<template>
  <div class="containerTest">
    <div style="height: 80vh">
    <LMap :zoom="zoom" :center="center">
      <LTileLayer :url="url"></LTileLayer>
      <l-marker
        :key="index"
        v-for="(brew, index) in markers"
        :lat-lng="[brew.latitude, brew.longitude]"
      ></l-marker>
    </LMap>
  </div>
  </div>
</template>
      
<script>
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { LMap, LTileLayer, LMarker } from "vue2-leaflet";
// 修复leaflet默认图标丢失问题
delete L.Icon.Default.prototype._getIconUrl
L.Icon.Default.mergeOptions({
  iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
  iconUrl: require('leaflet/dist/images/marker-icon.png'),
  shadowUrl: require('leaflet/dist/images/marker-shadow.png')
})

export default {
  name: "Map",
  components: {
    LMap,
    LTileLayer,
    LMarker
  },
  data() {
    return {
      markers: [],
      url: "https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=CFmlXsYmVozAdWKEtdT5",
      zoom: 6,
      center: [46.5322, 2.9482],
      bounds: null
    };
  },
  mounted: function () {
    fetch('https://api.openbrewerydb.org/breweries').then((response) => {
      return response.json();
    }).then(json=>{
        this.markers = json
        console.log(this.markers)
    })
  }
};
</script>

内容的提问来源于stack exchange,提问作者user14832365

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 17:21:02