JavaScript函数未返回谷歌地图lat/long的值
JavaScript function not returning value for google maps lat/long
我使用此函数从谷歌地图中获取纬度/经度:
function getLatLong(address){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
return (results[0].geometry.location.k + ',' + results[0].geometry.location.D);
} else {
return;
}
});
}
它做了我想让它做的事情,但当我在另一个函数中使用它时,比如getLatLong('new york, times square')
,我会得到undefined
作为回报。如果我设置了console.log(results[0].geometry.location.k + ',' + results[0].geometry.location.D);
而不是return
,我会在控制台中获得位置(如果我调用函数,例如document.ready
)。
为什么是这样?我应该如何正确使用它?
这里的笑话是geoCode不返回任何内容,但它希望您直接处理函数回调中显示的映射。您可以将它正确地放在console.log中并执行任何操作,但不能返回和处理函数外的内容。
例如https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple你就会明白这是怎么回事。
编辑:
一些变通方法仍然存在,看看这个代码:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
codeLatLng(function(addr){
alert(addr);
});
}
function codeLatLng(callback) {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
上面的代码片段告诉如何使用显式回调。
来源:如何从Google Maps JavaScript地理编码器回调返回变量?
第2版:
您的代码相应修改:
function getLatLong(address, callback){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
callback (results[0].geometry.location.k + ',' + results[0].geometry.location.D);
} else {
// do sth with error.
}
});
}
并称之为:
getLatLong(address, function(addr){
// do whatever with addr attribute
alert(addr);
});
也许这有助于你想出一个主意。
您正在调用getLantLong('new york, times square');
而不是getLatLong('new york, times square');
检查您的拼写
相关文章:
- 如何使用jquery在填充自动完成的值后使文本框只读
- 如何使用jQuery选择下拉列表的值
- 如何在angularJS中编辑时,如果DB中的值为true,则设置复选框,如果值为false,则取消选中复选框
- 如何在php文件中获取$.post-ajax传递的值
- Javascript计数器变量未显示正确的值
- 从Rally获取一个特定的标记,以便计算另一个字段中的值
- 接受不在列表中的值-引导组合框
- 提交后保留下拉选择的值
- JavaScript 检查隐藏字段中的值并将其设置为隐藏字段值
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- 使用元素的值与innerHTML
- 获取HTML属性中CSS声明的值
- 如何在 Javascript 中将变量的值从字符串转换为整数
- Lodash 从值数组中查找数组中的值
- 从键值结构中获取数据,并将其与AngularJS中ng重复的值进行比较
- 将数组中的值插入到表中
- 使用Javascript使用数组检查文本框中的值
- 无法使用PHP动态设置下拉列表中的值
- 对具有ui typeahead的对象中的值执行orderBy
- JavaScript函数未返回谷歌地图lat/long的值