Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 防止Geocoder Google Maps API内部循环_Javascript_Loops_Google Maps Api 3_Google Geocoder - Fatal编程技术网

Javascript 防止Geocoder Google Maps API内部循环

Javascript 防止Geocoder Google Maps API内部循环,javascript,loops,google-maps-api-3,google-geocoder,Javascript,Loops,Google Maps Api 3,Google Geocoder,我正在使用谷歌地图API。我想得到一个给定地址的长和长。是我干的 var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': 'Stockholm' }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var latitude = results[0].geom

我正在使用谷歌地图API。我想得到一个给定地址的长和长。是我干的

var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': 'Stockholm' }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.nb;
            var longitude = results[0].geometry.location.ob;
            console.log(latitude);
        }
});

但是,我会反复运行控制台日志。我只想让它运行一次,但我没有找到任何想法

声明一个新变量,显示是否调用了地理编码,并在第一次调用时将其更改为true

var geoCalled = false;

var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': 'Stockholm' }, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.nb;
    var longitude = results[0].geometry.location.ob;
    if (!geoCalled) {
      console.log(latitude);
      geoCalled = true;
    }
  }
});

您在此处添加的代码将在每个地理代码请求中运行一次。如果您将整个代码添加到JSFIDLE中,我们可能会更好地了解发生了什么。有没有办法只运行第一个请求?我以前考虑过这个问题,但它不会工作,因为回调函数是异步运行的。所以,GeoVar是未定义的,因为它在不同的范围内,我不这么认为
geocall
将始终为
false
true
;范围无关紧要。看看这个,看看我的意思。