谷歌地理编码 - 无法拉坐标

时间:2013-05-11 18:06:31

标签: javascript jquery google-maps google-maps-api-3 geolocation

我在这里得到了一些帮助,我试图将两段代码放在一起以获得以下结果:

用户点击地理位置按钮 向用户提供以下信息(类型地址,城市,州,国家,坐标)

这是我拼凑的代码和一些帮助: http://jsfiddle.net/QA7Xr/25/

这是完整的代码:

 var myLatlng = new google.maps.LatLng(31.272410, 0.190898);


 // INITALIZATION
 function initialize() {
     var mapOptions = {
         zoom: 4,
         center: myLatlng,
         mapTypeId: google.maps.MapTypeId.ROADMAP
     }
     var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
 }

 // GEOCODE
 function codeAddress() {
     var address = document.getElementById("address").value;
     geocoder.geocode({
         'address': address
     }, function (results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
             var address = "",
                 city = "",
                 state = "",
                 zip = "",
                 country = "";
             for (var i = 0; i < results[0].address_components.length; i++) {
                 var addr = results[0].address_components[i];
                 if (addr.types[0] == 'country') country = addr.long_name;
                 else if (addr.types[0] == 'street_address') // address 1
                 address = address + addr.long_name;
                 else if (addr.types[0] == 'establishment') address = address + addr.long_name;
                 else if (addr.types[0] == 'route') address = address + addr.long_name;
                 else if (addr.types[0] == 'postal_code') zip = addr.short_name;
                 else if (addr.types[0] == ['administrative_area_level_1']) state = addr.long_name;
                 else if (addr.types[0] == ['locality']) city = addr.long_name;
             }
             alert('City: ' + city + '\n' + 'State: ' + state + '\n' + 'Zip: ' + zip + '\n' + 'Country: ' + country);
         }
     }
     });
 } else {
     alert("Geocode was not successful for the following reason: " + status);
 };
 });
 } 

 initailize();
 document.getElementById("codeAddress").onclick = function () {
     codeAddress();
     return false;
 };

我是javascript编程的新手,但它应该工作的方式是如果地理编码成功它会抓取变量并将它们转储到对话框中,但它只是没有这样做。是因为简单的括号错误还是写得更糟糕?

1 个答案:

答案 0 :(得分:1)

initailize();。只是说。

再次纠正小提琴:http://jsfiddle.net/d5DBh/

这一次,我已经分叉了,所以没有人会覆盖它。修复:

  • 你附近还有一个额外的支架。清零。
  • 您也从未定义或实例化geocoder。已添加
  • Typo on initialize

请简化您的代码并实际阅读其他问题的更正。三个错误中的一个,我已经纠正过了。

相关问题