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

使用Google API时路线正常但Markers不显示问题求助

问题:Google Maps路线正常但Marker无法显示(无报错)

我使用Google API实现A点到B点的路线展示,目前路线功能正常,但所有公司位置的Marker无法显示,且控制台无任何报错信息。

代码片段

google.maps.event.addDomListener(window, "load", initMap);

function initMap() {
    //create map
    map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);

    ContextMenu = document.getElementById("my-context-menu");
    google.maps.event.addListener(map, "rightclick", function (ev) {
        currentLatLng = ev.latLng;
        console.log(ev.latLng);
        ShowContextMenuGoolge(ContextMenu, ev);

        /** this stop NOT stopping DOM 'context-menu' event from firing */
        ev.stop();
    });

    google.maps.event.addListener(map, "click", function () {
        HideContextMenuGoolge(ContextMenu);
    });

    //create a DirectionsService object to use the route method and get a result for our request
    directionsService = new google.maps.DirectionsService();

    //create a DirectionsRenderer object which we will use to display the route
    directionsDisplay = new google.maps.DirectionsRenderer();

    //bind the DirectionsRenderer to the map
    directionsDisplay.setMap(map);

    $.ajax({
        type: "GET",
        url: getAllMarkers,
        success: function (res) {
            createMarker(res);
        },
        error: function (err) { console.log('请求失败:', err); },
    });
}

function createMarker(companies) {
    console.log('待处理的公司数据:', companies);
    // 提前声明comMarkers
    window.comMarkers = window.comMarkers || [];
    companies.map((el) => {
        console.log('当前公司坐标:', el.lat, el.lng);
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(el.lat, el.lng),
            map: map,
        });
        comMarkers.push(marker);
    });
    console.log('已创建的Marker列表:', comMarkers);

    // 自动调整地图视野以包含所有Marker
    const bounds = new google.maps.LatLngBounds();
    companies.forEach(el => bounds.extend(new google.maps.LatLng(el.lat, el.lng)));
    map.fitBounds(bounds);
}

当前路线展示效果

路线展示效果

排查与修复建议

  • 验证接口返回数据:在createMarker开头打印companies,确认数据是数组格式,且每个元素的lat、lng是有效数值(非字符串、null或undefined)
  • 修正AJAX错误回调:原代码用err不符合jQuery AJAX规范,需改为error才能捕获请求失败,避免接口出错无提示
  • 确保变量作用域正确:map、comMarkers需在全局作用域声明,或通过闭包传递,避免createMarker中访问不到正确的map实例
  • 强制调整地图视野:创建Marker后调用map.fitBounds(),确保Marker在当前地图可视范围内,避免因坐标不在视野内导致看不到Marker
  • 检查坐标格式:若接口返回的经纬度是字符串,需先转为数字(如parseFloat(el.lat)),再传入google.maps.LatLng

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:25:21