0

我正在尝试获取地理位置并将其转换为文本。我有代码可以做到这一点,但它给了我一个错误。如何解决此错误?

错误:TypeError:'未定义'不是对象(评估'geocoder.geocode')

编码:

var geocoder;

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
 function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}

function errorFunction(){
alert("Geocoder failed");
}

function initialize() {
geocoder = new google.maps.Geocoder();



}

function codeLatLng(lat, lng) {

var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'location':latlng}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
  console.log(results)
    if (results[1]) {
     //formatted address
     alert(results[0].formatted_address)
    //find country name
         for (var i=0; i<results[0].address_components.length; i++) {
        for (var b=0;b<results[0].address_components[i].types.length;b++) {

        //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
            if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                //this is the object you are looking for
                city= results[0].address_components[i];
                break;
            }
        }
    }
    //city data
    alert(city.short_name + " " + city.long_name)


    } else {
      alert("No results found");
    }
  } else {
    alert("Geocoder failed due to: " + status);
  }
});
}
4

1 回答 1

0

反向地理编码,请求结构包含latLng,而不是location

从文档中的示例稍作修改(未测试):

 function codeLatLng(lat, lng) {
    // remove irrelevant code
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

此外,这是不正确的,如果您要使用第一个结果(result[0]),您应该检查它是否存在(如果 results[0] ... not if results[1]):

if (results[1]) {
 //formatted address
 alert(results[0].formatted_address)     

查看您的 jsfiddle,您没有正确加载 API。请参阅有关加载 API 的正确方法的文档

于 2013-03-31T13:09:05.523 回答