2011-10-08 62 views
0

可能重复:
Google Maps v3 - How to center using an address on initialize?谷歌地图上的加载当前位置

您好我有一张地图,我想和90210加载的邮政编码......警报是在作为一个调试工具..警报给我的坐标,但我得到'myOptions没有定义'的错误。有什么建议么?谢谢。

var geocoder; 
var map; 
function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var lat = ''; 
    var lng = ''; 
    var address = '90210'; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      lat = results[0].geometry.location.lat(); 
      lng = results[0].geometry.location.lng(); 
      //alert(lat + ', ' + lng); 
     } else { 
      alert("Geocode was not successful for the following reason: " + status); 
     }; 

     var latlng = '(' + lat + ', ' + lng + ')'; 
     var myOptions = { 
      zoom: 8, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 
     alert(latlng); 
    }); 

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
} 
+0

这是一个重复的问题,有些..它在这里找到答案:http://stackoverflow.com/questions/6140303/google -maps-V3-如何到中心-使用-一个地址上初始化/ 6140398#6140398] [1] [1]:http://stackoverflow.com/questions/6140303/ google-maps-v3-how-to-center-using-an-address-on-initialize/6140398#6140398 –

+0

“重复”是不同的。不应该关闭。 – Mischa

回答

1

您可以在geocoder.geocode中的匿名函数中创建myOptions。所以它不适用于那个函数以外的代码。如果您在初始化函数的顶部声明VAR myOptions,那么它应该工作:

var geocoder; 
var map; 
function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var lat = ''; 
    var lng = ''; 
    var address = '90210'; 
    var myOptions; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      lat = results[0].geometry.location.lat(); 
      lng = results[0].geometry.location.lng(); 
      //alert(lat + ', ' + lng); 
     } else { 
      alert("Geocode was not successful for the following reason: " + status); 
     }; 

     var latlng = '(' + lat + ', ' + lng + ')'; 
     myOptions = { 
      zoom: 8, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 
     alert(latlng); 
    }); 

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
} 
相关问题