2013-11-21 67 views
0

使用的GoogleMap v3可反地理编码samplesource使此源GoogleMap的v3可反向地理编码

var map; 
     var geocoder; 
     var marker; 
     function initialize() { 
      geocoder = new google.maps.Geocoder(); 
      var mapOptions = { 
       zoom : 14, 
       center : new google.maps.LatLng(30, 30) 
      }; 
      map = new google.maps.Map(document.getElementById('map-canvas'), 
        mapOptions); 
     } 

     function codeLatLng() { 
       var latlng = new google.maps.LatLng(30, 30); 
       alert("call codeLatLng() 1"); 
       geocoder.geocode({'latLng': latlng}, function(results, status) { 
        alert("call codeLatLng() 2"); 
       if (status == google.maps.GeocoderStatus.OK) { 
        if (results[1]) { 
        map.setZoom(11); 
        marker = new google.maps.Marker({ 
         position: latlng, 
         map: map 
        }); 
        infowindow.setContent(results[1].formatted_address); 
        infowindow.open(map, marker); 
        } else { 
        alert('No results found'); 
        } 
       } else { 
        alert('Geocoder failed due to: ' + status); 
       } 
       }); 
      } 


     google.maps.event.addDomListener(window, 'load', initialize); 
     codeLatLng(); 

我调用函数codeLatLng();在代码最后一行

这么叫功能codeLatLng()和警报消息“称codeLatLng()1

,但不叫 “呼codeLatLng()2” 的代码不起作用

什么是错误的,我的代码?

+1

任何消息:

这将更好地工作? –

+0

没有控制台干净没有错误 – user2637015

+0

我想尝试从数据处理功能中取出一些代码,只留下警报。另外,我会在数据处理函数之后放置另一个警报,但仍然在codeLatLng()函数中。 – Seano666

回答

2

什么是错在我的代码?

你是在你的地图执行codeLatLng和地理编码变量是初始化(在DOM完成加载时初始化运行,codeLatLng立即运行)。在错误控制台

var map; 
    var geocoder; 
    var marker; 
    function initialize() { 
     geocoder = new google.maps.Geocoder(); 
     var mapOptions = { 
      zoom : 14, 
      center : new google.maps.LatLng(30, 30) 
     }; 
     map = new google.maps.Map(document.getElementById('map-canvas'), 
       mapOptions); 

     // map and geocoder initialized 
     codeLatLng(); 
    } 

    function codeLatLng() { 
      var latlng = new google.maps.LatLng(30, 30); 
      alert("call codeLatLng() 1"); 
      geocoder.geocode({'latLng': latlng}, function(results, status) { 
       alert("call codeLatLng() 2"); 
      if (status == google.maps.GeocoderStatus.OK) { 
       if (results[1]) { 
       map.setZoom(11); 
       marker = new google.maps.Marker({ 
        position: latlng, 
        map: map 
       }); 
       infowindow.setContent(results[1].formatted_address); 
       infowindow.open(map, marker); 
       } else { 
       alert('No results found'); 
       } 
      } else { 
       alert('Geocoder failed due to: ' + status); 
      } 
      }); 
     } 


    google.maps.event.addDomListener(window, 'load', initialize); 
+0

感谢我认为geocoder初始google.maps.event.addDomListener(窗口,'加载',初始化); – user2637015

+0

地址解析器在onload函数中进行初始化。但是,直到页面加载后,codeLatLng运行在原始代码之后才会运行。 – geocodezip