gpt4 book ai didi

asynchronous - 如何等待google geocoder.geocode?

转载 作者:行者123 更新时间:2023-12-04 05:27:27 28 4
gpt4 key购买 nike

请帮我与Google geocoder.geocode。我知道此函数运行异步,但我不知道如何处理它。

如何等待结果?这是我的代码:
我的代码不等待geocode.geocoder,所以我得到的是undefined而不是geolocation。

<!DOCTYPE html>
<html>
<head>
<title>Geocoding service
</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="cs" />

<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<link href="http://code.google.com//apis/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>

function codeAddress(callback) {

var address = document.getElementById('address').value;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
},callback);
}


function geocoder(result) {
alert(codeAddress());
}

function button() {
geocoder(codeAddress) ;
}



</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="address">
<input type="button" value="Go" onclick="button()">
</div>
<div id="map-canvas">
</div>
</body>
</html>

最佳答案

I found solution thank to web page http://recurial.com/programming/understanding-callback-functions-in-javascript/ where is callback step by step explained.

Here is working code:


<!DOCTYPE html>
<html>
<head>
<title>Geocoding service
</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="cs" />

<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<link href="http://code.google.com//apis/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>

function codeAddress(callback) {

var address = document.getElementById('address').value;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
souradnice = [results[0].geometry.location.lat(),results[0].geometry.location.lng()];
callback(souradnice);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}


function gogo(){
codeAddress(function(num) {
alert(num);

});
}






</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="address">
<input type="button" value="Go" onclick="gogo()">
</div>
<div id="map-canvas">
</div>
</body>
</html>
  • Dolik
  • 关于asynchronous - 如何等待google geocoder.geocode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18253680/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com