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

使用Google Maps API显示周边学校标记时遇setMap错误求助

问题分析与修复方案

核心错误原因

  • map变量作用域失效:initMap里用const声明的map是局部变量,createMarker函数无法直接访问,导致创建学校标记时传入的map是undefined,触发setMap类型错误。
  • 未定义的marker变量:createMarker中添加点击监听时用到的marker没有声明,会引发未定义错误。
  • 冗余的坐标转换:直接用place.geometry.location作为标记位置即可,无需手动提取lat/lng再重构对象。

修复后的完整代码

<script type="text/javascript">
    function initMap() {
        var lat = $('#lat').val();
        var lng = $('#lng').val();
        var address = $('#address').val();
        var latNumber = Number(lat);
        var lngNumber = Number(lng);
        const myLatLng = {
            lat: latNumber,
            lng: lngNumber
        };
        const map = new google.maps.Map(document.getElementById("map"), {
            zoom: 17,
            center: myLatLng,
        });
        new google.maps.Marker({
                position: myLatLng,
                map,
                title: address,
            });

        infowindow = new google.maps.InfoWindow();
        var service = new google.maps.places.PlacesService(map);
        service.nearbySearch({
                location: myLatLng,
                radius: 500,
                type: ['school']
            },
            // 把map传入回调,再传递给createMarker
            function(results, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    for (var i = 0; i < results.length; i++) {
                        createMarker(results[i], map);
                    }
                }
            }
        );
    }

    function createMarker(place, map) {
        // 直接使用Google Maps原生的LatLng对象作为位置
        const marker = new google.maps.Marker({
            position: place.geometry.location,
            map: map,
            title: 'school'
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(place.name);
            infowindow.open(map, this);
        });
    }

    window.initMap = initMap;
</script>
<script type="text/javascript"
    src="https://maps.google.com/maps/api/js?key='APIKEY'&sensor=true&libraries=geometry,places&callback=initMap">
</script>

关键修复点

  • 传递有效map实例:修改nearbySearch的回调逻辑,将map作为参数传递给createMarker,确保函数能拿到合法的地图对象。
  • 声明marker变量:在createMarker中明确创建并存储标记实例,避免未定义错误。
  • 简化坐标使用:直接复用place.geometry.location(Google Maps内置的LatLng对象)作为标记位置,减少冗余代码。
  • 优化API加载写法:多个libraries用逗号合并(libraries=geometry,places),代码更简洁。

内容的提问来源于stack exchange,提问作者Parteek Kumar Kherpa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:55:29