JS变量“;消失”;没有理由,变得空虚

JS variable "disappear" with no reason and gets empty

本文关键字:空虚 有理由 变量 消失 JS      更新时间:2024-03-21

我正试图从Google Geocoder中获取lat和long信息,但尽管在正在进行的调用中正确提取了信息,但由于某种原因,js变量在收到关于这段代码的第二个警报("if"条件之外的警报)后立即变空:

var map, marker, latLong;
var geocoderlat = new google.maps.Geocoder();  	
var addresslat = '<?php echo str_replace(" ","+",$address);?>';
function initMap() {
	
	geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
	  if (status == google.maps.GeocoderStatus.OK) {
		latLong = results[0].geometry.location;
		alert("Inside IF: "+latLong);
	  } else {
		latLong = '<?php echo $latitude.",".$longitude;?>';
	  }
	})
	
	alert("Outside: "+latLong);
    var isDraggable = !('ontouchstart' in document.documentElement);
	var mapOptions = { 
	  center: new google.maps.LatLng(latLong),
	  zoom: 12,
      (...)

显然,除了这一部分之外还有很多代码,但在这种情况下,代码的其余部分并不重要,因为这个变量在我的代码中再也没有使用过(我甚至用代理Ransack搜索了所有文件,所以请确保这个变量没有在其他地方使用)。

编辑:

好吧,这真的,真的很奇怪。。。

function getGeoLatLong(addresslat) {
  geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      return results[0].geometry.location;
    } else {
      return '<?php echo $latitude.",".$longitude;?>';
    }
  })
}
alert("Outside function: "+getGeoLatLong(addresslat));

这仍然会在警报中返回"未定义"。

geocoderlat.geocode需要更多的时间执行,而代码执行已经达到第二个警报。您需要使用setTimeout来检查结果或尝试此操作。

function initMap() {    
    geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        latLong = results[0].geometry.location;
        alert("Inside IF: "+latLong);
        alert("Outside: "+latLong);
    var isDraggable = !('ontouchstart' in document.documentElement);
    var mapOptions = { 
      center: new google.maps.LatLng(latLong),
      zoom: 12,
      (...)
      } else {
        latLong = '<?php echo $latitude.",".$longitude;?>';
      }
    })

此外,如果要使用latLong = '<?php echo $latitude.",".$longitude;?>';作为默认的latLong,则需要在顶部声明它。那么当地理编码完成加载时,它无论如何都会被覆盖

编辑试试这个。

function getGeoLatLong(addresslat) {
 geocoderlat.geocode( { 'address': addresslat}, checkresults)
}
function checkresults(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      alert("Outside function: " + results[0].geometry.location);
    //declare the big chunk of code as a function and make a call to it.
    } else {
      alert("Outside function: <?php echo $latitude.','.$longitude;?>");
     //declare the big chunk of code as a function and make a call to it.
    }
  }
   getGeoLatLong(addresslat);