2012-04-23 34 views
2

我有这个JavaScript在我的HTML什么,我想在这里做的是让地图表示给定位置尝试使用谷歌API V3从地址获得位置

<script type="text/javascript"> 
var geocoder; 
var map; 
function getmaploc() { 
    geocoder = new google.maps.Geocoder(); 
    var myOptions = { 
     zoom: 8, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    geocoder.geocode('cairo', 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); 
     } 
     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    }); 
} 
</script> 

<body onload="getmaploc()"> 
    <div id="map_canvas" style="width: 320px; height: 480px;"></div> 
</body> 

我无法弄清楚什么是错与此任何帮助?

+0

请格式化你的代码,很多人(包括我在内),将无法读取未格式良好的 – 2012-04-23 22:58:22

+0

固定它对不起进出口新的计算器 – 2012-04-23 23:05:55

+0

格式化也为你的代码,你*修复*仍然不是很可读。这里有另一个提示:“它不起作用”没有错误信息使其他人更难以帮助。 – 2012-04-24 00:37:37

回答

4

有多个错误,

  • 一个省略支架
  • 初始化地图第一
  • 地理编码()需要使用GeocoderRequest对象作为参数

固定代码:

var geocoder; 
var map; 
function getmaploc() { 
    geocoder = new google.maps.Geocoder(); 
    var myOptions = { 
     zoom : 8, 
     mapTypeId : google.maps.MapTypeId.ROADMAP 
    }; 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

    geocoder.geocode({ 
     address : 'cairo' 
    }, function(results, status) { 
     console.log(results); 
     if(status == google.maps.GeocoderStatus.OK) { 
      map.setCenter(results[0].geometry.location); 
      new google.maps.Marker({ 
       map : map, 
       position : results[0].geometry.location 
      }); 
     } else { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 

    }); 
} 
+0

+1并重新格式化!大声笑 – 2012-04-24 00:12:22

+1

请不要抱怨我的缩进,我喜欢它^^ – 2012-04-24 00:17:30

+0

非常感谢修复Dr.Molle – 2012-04-24 01:21:24