使用谷歌地图onload显示地址位置

时间:2012-01-06 04:37:10

标签: javascript function google-maps

我正在尝试在页面加载时显示地址的位置,但我的地图根本没有显示。我试图提醒(地址)并且它有效。它显示了我想要的正确地址。但我不确定我这样做是否正确?

<script>
    var geocoder;
    var map;
    function codeAddress() {
    geocoder = new google.maps.Geocoder();
    //var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            var city_state_zip = document.getElementById("city_state_zip").innerHTML;
            var street_address = document.getElementById("street_address").innerHTML;
            var address = street_address + " " + city_state_zip;//document.getElementById(street_addres +" "+ city_state_zip).value;
            geocoder.geocode( { 'address': address}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
              } else {
                alert("Geocode was not successful for the following reason: " + status);
              }
            });
          }



    window.onload = function(){
            codeAddress();
       }
</script>

我将initialize()与此示例中的codeAddress()结合起来:http://code.google.com/apis/maps/documentation/javascript/geocoding.html#GeocodingStatusCodes我之所以要合并这个原因是因为我不想用随机LatLng加载地图,我希望它能加载我已经有了一个地址。

有没有人知道我是否正确地这样做了?

谢谢!

1 个答案:

答案 0 :(得分:4)

脚本的以下修改使其适用于与我在同一条船上的人。这现在允许我在加载页面时加载一个特定的地址,它会自动从我的html中检测lat,lng。

这是谷歌网站的一个小小修改。

<script>
  var geocoder;
  var map;
  function codeAddress() {
    geocoder = new google.maps.Geocoder();
    var lat='';
    var lng=''
    var city_state_zip = document.getElementById("city_state_zip").innerHTML;
    var street_address = document.getElementById("street_address").innerHTML;
    var address = street_address + " " + city_state_zip;
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
       lat = results[0].geometry.location.lat(); //getting the lat
       lng = results[0].geometry.location.lng(); //getting the lng
       map.setCenter(results[0].geometry.location);
       var marker = new google.maps.Marker({
           map: map,
           position: results[0].geometry.location
       });
     } else {
            alert("Geocode was not successful for the following reason: " + status);
            }
     });
     var latlng = new google.maps.LatLng(lat, lng);
     var myOptions = {
         zoom: 8,
         center: latlng,
         mapTypeId: google.maps.MapTypeId.ROADMAP
     }
     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
     }


window.onload = function(){
       codeAddress();
}
</script>