从地址到纬度和经度数字的 Javascript 地理编码不起作用 [英] Javascript geocoding from address to latitude and longitude numbers not working

查看:41
本文介绍了从地址到纬度和经度数字的 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".

谁能告诉我怎么了?

<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.

我无法找到的一件事是如何朝另一个方向前进.从坐标到地址.这是我需要使用的代码.请注意,我也使用 jquery.

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 值.
如果您只对整个格式化的地址感兴趣,那么您可以按照 谷歌的例子

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

这篇关于从地址到纬度和经度数字的 Javascript 地理编码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆