2013-04-09 59 views
0

我有我所分配的ID的「地址」到我的頁面上的元素:檢索地址,並用它創建谷歌地圖

<p id="address">1600 Pennsylvania Ave NW, Washington, DC 20500, United States</p> 

現在我想從它創建一個谷歌地圖使用以下內容:

<script type="text/javascript"> 
    var gecoder, map; 
    var address = document.getElementById('address').innerHTML; 
    function googlemap(address) { 
    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     var myOptions = { 
     zoom: 8, 
     center: results[0].geometry.location, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 
     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

     var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location 
     }); 
     } 
    }); 
    } 
</script> 

但是,這不會返回任何內容。我得到一個空白。任何想法我做錯了什麼?

回答

0

這就是我所做的,它的工作原理。 JavaScript中的頭:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" /> 
<script type="text/javascript"> 
    var geocoder, map; 

    function googlemap() { 
     var address = document.getElementById('address').innerHTML; 

     geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 'address': address }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       var myPosition = results[0].geometry.location; 
       alert(myPosition); 

       var myOptions = { 
        zoom: 8, 
        center: myPosition, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       } 
       map = new google.maps.Map(document.getElementById('map'), myOptions); 

       var marker = new google.maps.Marker({ 
        map: map, 
        position: myPosition 
       }); 
      } else { 
       alert('Geocode was not successful for the following reason: ' + status); 
      } 
     }); 
    } 
</script> 

身體:

<body onload="googlemap()"> 
<form id="form1" runat="server"> 
<div> 
    <p id="address">1600 Pennsylvania Ave NW, Washington, DC 20500, United States</p> 
    <div id="map" style="overflow:hidden; width:400px; height:400px"></div> 
</div> 
</form>