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

时间:2012-02-27 17:40:41

标签: javascript cakephp-2.0

我正在尝试构建一个CakePHP应用程序,它允许用户更新其地址信息,然后将新的lat / lon存储在数据库中。我正在使用Google的地理编码器来检索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之上,这是在页面的负载上调用它的脚本:

<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> 

当我加载页面并使用chrome检查它时,我看到

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

2 个答案:

答案 0 :(得分:1)

您应该查看生成的代码。我打赌它是

var address = address here;

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

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

答案 1 :(得分:0)

对于任何可能遇到此问题的人,我通过改变我的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。

相关问题