未捕获的ReferenceError:我的函数未定义

Uncaught ReferenceError: my function is not defined

本文关键字:我的 函数 未定义 ReferenceError      更新时间:2023-09-26

我正在尝试构建一个CakePHP应用程序,它将允许用户更新他们的地址信息,然后将新的lat/lon存储在数据库中。我正在使用谷歌的地理编码器来检索纬度/经度信息,但我的功能不起作用。我几乎没有使用Javascript的经验,所以我不确定自己做错了什么。我的代码是我在互联网上看到的东西的一种融合。拜托,如果有人能给我建议,那就太好了。

这是我的地理编码功能:

<script type="text/javascript">
function getLatLong(address){
  var geo = new google.maps.Geocoder;
  var address =<?php echo $this->data['Location']['address'].' '.$this->data['Location']['city'].', '.$this->data['Location']['state'].' '.$this->data['Location']['zip']; ?>;
  geo.geocode({'address':address},function(results, status){
          if (status == google.maps.GeocoderStatus.OK) {
            return results[0].geometry.location;
            alert('The address is' + address);
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
   });
  }
</script>

在我的html上面,下面是调用页面onLoad的脚本:

<script>
if(window.attachEvent) {
window.attachEvent('onload', getLatLong());
} else {
if(window.onload) {
    var curronload = window.onload;
    var newonload = function() {
        curronload();
        getLatLong();
    };
    window.onload = newonload;
} else {
    window.onload = getLatLong();
}
}
</script>

我的文件头上有:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 

当我加载页面并用铬检查时,我看到

Uncaught ReferenceError: getLatLong is not defined   (anonymous function)1:89
1:106      Uncaught SyntaxError: Unexpected identifier

您应该了解生成的代码。我打赌是

var address = address here;

您必须将PHP输出放在引号中,使其成为有效的JavaScript字符串:

var address = "<?php echo ... ?>"; 

对于任何可能遇到这种情况的人来说,我通过更改我的javascript函数来实现它,如下所示:

<script type="text/javascript" >
var geocoder;
function getLatLong(address){
  geocoder = new google.maps.Geocoder();
  var add = document.getElementById("LocationAddress");
  var address =add.value;
  geocoder.geocode({ 'address':address},function(results, status){
          if (status == google.maps.GeocoderStatus.OK) {
            document.getElementById("lat").innerHTML="<strong>"+results[0].geometry.location.lat()+"</strong><br />";
            document.getElementById("lng").innerHTML="<strong>"+results[0].geometry.location.lng()+"</strong>";
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
   });

}

在我使用之前

return results[0].geometry.location;
        alert('The address is' + address);

当我用document.write(results[0]geometry.location)替换它时,它就不起作用了;我的警报开始工作了。我还确保在函数之前定义一个名为geocoder的var。