繁体   English   中英

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

[英]Uncaught ReferenceError: my function is not defined

我正在尝试构建一个CakePHP应用程序,该应用程序将允许用户更新其地址信息,然后将新的经纬度存储在数据库中。 我正在使用Google的地址解析器来检索经/纬度信息,但是我的功能无法正常工作。 我几乎没有Java方面的经验,所以我不确定自己做错了什么。 我的代码有点像我在互联网上看到的东西的混合物。 请,如果有人可以建议我,那太好了。

这是我的地址解析功能:

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

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

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的变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM