从地址到纬度和经度数字的Javascript地址解析不起作用

问题描述:

我正在使用以下地理编码功能将文本地址转换为经度和纬度数字,但这并不正确。警报写入未定义。

I'm using the following geocoding function to convert a textual address into latitude and longitude numbers, but it's not working right. The alert writes "undefined".

任何人都可以说出了什么问题吗?

Can anyone say what's wrong?

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.latitude;
    var longitude = results[0].geometry.location.longitude;
    alert(latitude);
    } 
}); 
</script>


尝试使用它:

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

使用Google的api很难,但这里是相关文件。

It's bit hard to navigate Google's api but here is the relevant documentation.

我很难找到如何去往另一个方向。从坐标到地址。这是我使用upp的代码。

One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.

$.each(results[0].address_components, function(){
    $("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});

我正在循环所有返回的 address_components 并测试它们的类型是否与表单中的任何输入元素名称匹配。如果他们将元素的值设置为 address_components 值。

如果您只对整个地址感兴趣,那么您可以请按照 Google的示例操作。

What I'm doing is to loop through all the returned address_components and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components value.
If you're only interrested in the whole formated address then you can follow Google's example