如何使用Google Javascript v3 Geocoder返回纬度和经度数组
How do you return a latitude and longitude array using the Google Javascript v3 Geocoder?
我正在尝试创建一个函数,该函数利用Google Javascript V3的地理编码功能,并返回一个带有经度和纬度的数组。由于某些原因,没有使用函数填充返回数组。谢谢你的帮助!
代码:
function getCoords(address) {
var latLng = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng.push(results[0].geometry.location.lat());
latLng.push(results[0].geometry.location.lng());
return latLng;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var test_arr;
test_arr = getLatLng('New York');
alert(test_arr[0] + ',' + test_arr[1]) // I'm getting a test_arr is undefined here.
阅读关于在Javascript中使用回调函数的信息。这篇文章可能会有所帮助。
正如Jon所指出的,可以通过将回调函数传递到getCoords方法中来解决这个问题。这是一种等待谷歌回复的方式。您定义了一个函数,该函数将在地理编码完成时调用。您将调用所提供的函数,而不是返回数据,而是将数据作为参数。
类似这样的东西:
function getCoords(address, callback) {
var latLng = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng.push(results[0].geometry.location.lat());
latLng.push(results[0].geometry.location.lng());
callback(latLng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
getCoords('New York', function(latLng) {
var test_arr;
test_arr = latLng;
alert(test_arr[0] + ',' + test_arr[1])
// Continue the rest of your program's execution in here
});
@Matt Ball应该已经发布了答案。:)test_arr未定义的原因是,您在返回结果之前立即对其进行评估。
如果你做了setTimeout(这是不应该做的),你会注意到数组最终会有一些东西
setTimeout(function(){
alert(test_arr) // has stuff...
}, 5000);
相反,您可以将一个匿名函数作为回调传递给getCoords。一旦坐标可用,就会执行此函数。
function getCoords(address, callback) {
...
var lng = results[0].geometry.location.lng();
var lat = results[0].geometry.location.lat();
callback([lat, lng]);
...
}
getCoords("New York", function(coords) {
alert(coords); // works
});
相关文章:
- “可绘制地图”设置地图选项“纬度-经度”
- 如何将纬度经度从HTML表单传递到谷歌地图
- 在D3中确定纬度/经度视图边界
- 地理位置-如何在文本框中显示纬度/经度
- Amcharts-地图:自定义地图上的错误坐标(纬度/经度)(罗马尼亚县级)
- 纬度/经度在D3.js地图上的位置
- 使用 JSON 从数据库检索纬度经度到 PHP 页面
- 纬度/经度 -> x/y,x/y ->纬度/经度
- 海上交通地图 - 纬度/经度 Javascript
- 使用 Javascript 打乱半径 100m 半径内的纬度经度坐标
- 从数据库读取纬度/经度并在地图上放置标记
- 从没有谷歌地理位置的地址获取纬度/经度
- 在数据库中插入纬度经度
- 如何将矢量(X,Y)位置转换为纬度/经度坐标?Javascript
- 地图框:当我尝试更改 geojson 对象的纬度/经度时,该列表不起作用
- 如果定位服务关闭,英特尔 XDK 地理位置将找不到纬度/经度
- 基于点的聚类可在任何给定时间查找图钉聚类纬度经度
- 在阿尔伯斯投影地图上将纬度/经度转换为X/Y坐标
- 如何从外部文件中提取纬度经度组合
- 将纬度/经度转换为地址