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

如何在Vue+Leaflet项目中调用API生成地图标记Marker

问题排查与修复方案

核心问题

你代码的核心问题是变量赋值不匹配:
模板中标记遍历的数据源是markers数组,但你在接口请求成功后将返回结果赋值给了未在data中声明的brews变量,导致没有可遍历的标记数据,自然不会渲染自定义标记。

额外优化点

  • 接口返回的latitude、longitude字段可能是字符串格式,需转换为数字后再传入L.latLng避免坐标识别异常
  • 新增无效数据过滤逻辑,跳过经纬度为空的条目,避免控制台报错

修正后代码

以下是修改完成的完整代码:

<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="latLng(brew.latitude, brew.longitude)"
      ></l-marker>
    </LMap>
  </div>
  </div>
</template>
      
<script>
import { LMap, LTileLayer, LMarker } from "vue2-leaflet";
// 若项目未全局引入Leaflet核心对象,可取消下面这行的注释
// import L from 'leaflet';

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=>{
        // 过滤有效数据并赋值给markers数组
        this.markers = json.filter(item => item.latitude && item.longitude)
        console.log(this.markers)
    })
  },
  methods: {
    latLng: function(lat, lng) {
      // 经纬度转数字避免格式异常
      return L.latLng(Number(lat),Number(lng));
    },
  }
};
</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 20:30:05