我有这样的功能
function geokod(district){
var c= new Array();
//declare geocoder
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': district}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//c.push(results[0].geometry.location.lat());
//c.push(results[0].geometry.location.lng());
c[0]=results[0].geometry.location.lat();
c[1]=results[0].geometry.location.lng();
} //endif
});
return c;
}
我这样称呼这个函数
var loc = new Array();
loc = geokod('Kuala Lumpur, Malaysia');
我尝试测试它
console.log(loc.length) //failed to get the length, output 0
console.log(loc) //success, output the coordinate
我尝试将它分配给其他数组
var location = ["Kuantan",0.0,0.0];
location[1] = loc[0];
location[2] = loc[1];
数组位置[1]和[2]内容未定义值。
我有点混淆为什么会发生这种情况。请帮忙,谢谢。
---经过一些建议并做了一些功课后,我将上面的代码改为此---
function foo(address, fn){
var c= new Array();
//declare geocoder
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
c[0]=results[0].geometry.location.lat();
c[1]=results[0].geometry.location.lng();
fn(c);
} //endif
});
}
我的回调
foo(locations[i][0], function(lokasi){
alert(lokasi[0]); // this will alarm content
loc = lokasi; // this not assign the content
});
仍然没有解决我如何将返回值分配给新的var。