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

谷歌地图加载失败:Uncaught TypeError读取geometry属性报错求助

地图加载报错排查求助

错误信息

Uncaught TypeError: Cannot read properties of undefined (reading 'geometry') at Object.success

实现代码

<script>
var mapArea =
    '<p class="note-for-location text-center">Select Your Business location by clicking on map and then save location</p><input type="hidden" name="latitude"  id="latitude"/><input type="hidden" name="longitude"  id="longitude"/><div id="map"></div>';

function get_map() {
    $("#property_google_map").html(mapArea);
    var city_name = escape(document.getElementById("business_cityy").value);
    var subarea_name = escape(document.getElementById("sub_area").value);
    var locality_name = document.getElementById("locality").value;
    if (locality_name == "Unlisted Locality" && subarea_name == "Unlisted Area") {
        var address = city_name + " Pakistan";
        var zoming_view = 8;
    } else if (locality_name == "Unlisted Locality" && subarea_name != "Unlisted Area") {
        var address = subarea_name + " " + city_name + " Pakistan";
        var zoming_view = 12;
    } else {
        var address = locality_name + " " + subarea_name + " " + city_name + " Pakistan";
        var zoming_view = 15;
    }

    $.ajax({
        url: "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&AIzaSyAPpVcdmE4Lr3dPpuWK2GAH8I42rsZz-Io",
        type: "POST",
        success: function (res) {
            $("#latitude").val(res.results[0].geometry.location.lat);
            $("#longitude").val(res.results[0].geometry.location.lng);
            initMap(res.results[0].geometry.location.lat, res.results[0].geometry.location.lng, zoming_view);
        },
    });
}
var map;
var marker;
var infowindow;
var messagewindow;
var confirmForm =
    '<div id="form"><fieldset class="google-field-set"><legend  class="google-legend"> Please confirm your location </legend><table><tr><td></td> <td><input type="hidden" id="name"/></td></tr><tr><td></td><td><input type="hidden" id="address" /></td></tr><tr><td></td><td><input type="hidden" id="type"/></td></td></tr> <tr><td></td><td><input type="button" value="Save" class="google-save-button" onclick="saveData();"/></td></tr></table></fieldset></div>';
var locationSaved = '<div id="message">Location saved</div>';

function initMap(a, b, z) {
    var california = { lat: parseFloat(a), lng: parseFloat(b) };
    map = new google.maps.Map(document.getElementById("map"), {
        center: california,
        zoom: parseInt(z),
    });

    var image = "images/marker-64.png";
    marker2 = new google.maps.Marker({
        position: { lat: parseFloat(a), lng: parseFloat(b) },
        map: map,
        icon: image,
    });

    infowindow = new google.maps.InfoWindow({
        content: confirmForm,
    });

    messagewindow = new google.maps.InfoWindow({
        content: locationSaved,
    });

    var image = "images/marker-64.png";
    google.maps.event.addListener(map, "click", function (event) {
        marker2.setOpacity(0.0);
        if (marker != null) {
            //already set marker to clear
            marker.setMap(null);
            marker = null;
        }
        marker = new google.maps.Marker({
            position: event.latLng,
            map: map,
            icon: image,
            //  draggable: true,
            visible: true,
        });

        if (infowindow) {
            infowindow.close();
        }
        infowindow = new google.maps.InfoWindow({
            content: confirmForm,
            // maxWidth: 300
        });
        infowindow.open(map, marker);

        //google.maps.event.addListener(marker, 'click', function() {
        //  infowindow.open(map, marker);
        //});
    });
}

function saveData() {
    var name = escape(document.getElementById("business_city").value);
    var address = escape(document.getElementById("sub_area").value);
    var type = document.getElementById("locality").value;
    var latlng = marker.getPosition();

    $("#latitude").val(latlng.lat());
    $("#longitude").val(latlng.lng());
    var url = "add_latlng.php?name=" + name + "&address=" + address + "&type=" + type + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();

    downloadUrl(url, function (data, responseCode) {
        if (responseCode == 200) {
            infowindow.close();
            messagewindow.open(map, marker);
        }
    });
}

function downloadUrl(url, callback) {
    var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request.responseText, request.status);
        }
    };

    request.open("GET", url, true);
    request.send(null);
}

function doNothing() {}
</script>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAPpVcdmE4Lr3dPpuWK2GAH8I42rsZz-Io"></script>

我正尝试排查解决该问题,但无法定位问题根源,恳请提供技术帮助。


问题根源与修复方案

核心问题分析

报错Cannot read properties of undefined (reading 'geometry')本质是:代码直接访问res.results[0].geometry时,res.results[0]不存在(为undefined),也就是地理编码请求未返回有效解析结果。具体诱因有两个:

  1. 地理编码请求参数/方法错误

    • API Key参数格式错误:URL里写成了&AIzaSyAPpVcdmE4Lr3dPpuWK2GAH8I42rsZz-Io,正确格式应该是&key=AIzaSyAPpVcdmE4Lr3dPpuWK2GAH8I42rsZz-Io,缺少key=前缀会导致请求被服务端拒绝。
    • 请求方法错误:谷歌地理编码API仅支持GET请求,代码里用了POST,不符合接口规范。
  2. 无错误兜底逻辑
    不管请求成功与否、解析是否有效,代码直接强制访问res.results[0],完全没判断请求状态(比如res.status是否为OK)、results数组是否为空。一旦地址解析失败、密钥无效或请求格式错误,就会触发报错。

修复步骤

1. 修正地理编码请求逻辑

把AJAX请求部分替换为以下代码:

$.ajax({
    url: "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=AIzaSyAPpVcdmE4Lr3dPpuWK2GAH8I42rsZz-Io",
    type: "GET", // 改为GET请求,符合API要求
    success: function (res) {
        // 先校验请求状态
        if (res.status !== "OK") {
            console.error("地理编码失败:", res.status, res.error_message);
            alert("无法解析地址,请检查输入或稍后重试");
            return;
        }
        // 确保results数组有有效内容
        if (!res.results || res.results.length === 0) {
            alert("未找到匹配的地址");
            return;
        }
        // 安全获取坐标数据
        var location = res.results[0].geometry.location;
        $("#latitude").val(location.lat);
        $("#longitude").val(location.lng);
        initMap(location.lat, location.lng, zoming_view);
    },
    // 新增请求失败的错误处理
    error: function(xhr, status, error) {
        console.error("地图服务请求出错:", error);
        alert("地图服务请求失败,请检查网络连接");
    }
});

2. 修复其他潜在问题

  • 变量名不一致:get_map里用了business_cityy,但saveData里用了business_city,请确认DOM元素ID是否统一,避免因获取不到城市名称导致地址无效。
  • 未声明全局变量:initMap里直接使用marker2,建议在全局变量区添加var marker2;,避免隐式全局变量引发的意外问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:01:07