如何使用Google地图显示地图?

时间:2015-07-12 14:00:03

标签: javascript google-maps

我想要显示Google地图,我有这个代码无效:

<div id="map" style="width: 300px; height: 240px;">Loading map, please wait...</div>
...
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MY_KEY_is_setup_correctly"></script>
<script type="text/javascript">
    function initialize(){
        var map_container = document.getElementById('map');
        var settings = {
            zoom: 7,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: new google.maps.LatLng(-18.893384076844953, -48.25330985812758),
        };
        var map = google.maps.Map(map_container, settings);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

当我刷新页面时,我看不到地图,JavaScript控制台会抛出这条消息:

GET http://csi.gstatic.com/csi?v=2&s=mapsapi3&action=apiboot2&rt=main.102 [HTTP/1.1 204 No Content 428ms]

为什么我的代码失败了?

2 个答案:

答案 0 :(得分:3)

您需要创建Map类的新实例。

而不是:

var map = google.maps.Map(map_container, settings);

写:

var map = new google.maps.Map(map_container, settings);

答案 1 :(得分:3)

您的代码中有拼写错误,您在new构造函数之前缺少google.maps.Map。你的代码应该是:

function initialize() {
    var map_container = document.getElementById('map');
    var settings = {
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(-18.893384076844953, -48.25330985812758)
    };
    // add "new" before google.maps.Map constructor
    var map = new google.maps.Map(map_container, settings);
}
google.maps.event.addDomListener(window, 'load', initialize);

working fiddle

代码段

function initialize() {
  var map_container = document.getElementById('map');
  var settings = {
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: new google.maps.LatLng(-18.893384076844953, -48.25330985812758)
  };
  var map = new google.maps.Map(map_container, settings);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map" style="width: 300px; height: 240px;">Loading map, please wait...</div>