![](/img/trans.png)
[英]JavaScript - Uncaught ReferenceError: my function is not defined
[英]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.