【问题标题】:Uncaught TypeError: Cannot read properties of undefined (reading 'geometry') at Object.success未捕获的 TypeError:无法在 Object.success 处读取未定义的属性(读取 \'geometry\')
【发布时间】:2023-02-02 18:46:28
【问题描述】:

由于该错误,地图未显示

未捕获的类型错误:无法在 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>

我试图找到解决方案但不了解问题所在。

【问题讨论】:

  • 它告诉您 res.results[0] 未定义。可能是 results 不是一个数组或者它是一个空数组。调试精确的res 的价值。
  • 在尝试使用 res 之前检查 res.status === "REQUEST_DENIED"
  • 亲爱的,我照你说的做了……错误已删除,但地图仍未显示
  • 你是否理解你所做的改变?
  • 您的一个 DOM 元素 (business_cityy) 拼写错误 - 这可能是问题的原因吗?

标签: php html jquery


【解决方案1】:

要使 res.results[0].geometry 正常工作,您的服务器需要支持该结构。

例如,如果您尝试:

console.log('my-response type:', typeof res);
console.log('my-response content:', JSON.stringify(res, null, 2));

输出应该是这样的:

my-response type: object

my-response content: {
  "results": [
    "geometry": {
      "location": {
        "lat": 123,
        "lng": 456
      }
    }
  ] 
}

但正如 cmets 中提到的,您的回答是:

{
  "results": [],
  "status": "REQUEST_DENIED"
}

笔记:

如果 stringify 失败,那是无效的 JSON,但尝试:

const filterRecursion = function () {
  const seen = new WeakSet();
  return function (key, value) {
    if (value && typeof value === "object") {
      if (seen.has(value)) {
        // Ignore:
        return;
      }
      seen.add(value);
    }

    // Include:
    return value;
  };
};

console.log('my-response content:', JSON.stringify(res, filterRecursion(), 2));

【讨论】:

  • OP 得到 { "results" : [], "status" : "REQUEST_DENIED" } 的回报 - results 是一个有效的数组,它只是空的。他们检查了 request_denied 现在没有给出错误 - 但他们似乎不明白为什么没有几何......因为结果是空的。
猜你喜欢
  • 2023-01-14
  • 2023-01-25
  • 1970-01-01
  • 2022-12-21
  • 2018-05-30
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多