来自API的Google地图未显示

时间:2015-11-29 19:45:52

标签: javascript google-maps google-maps-api-3

出于某种原因,当我在浏览器中运行我的文件时谷歌地图没有显示它只是给出一个空白区域。这是我的代码:



$(document).ready(function() {

  //google map 
  var map, geocoder;

  function initializeMap() {
    google.maps.event.addDomListener(window, 'load', function() {
      codeAddress('33 W 23rd St, New York, NY');
    });
  }

  function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': address
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          var mapOptions = {
            zoom: 8,
            center: results[0].geometry.location,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };

          map = new google.maps.Map($("#map").get(0), mapOptions);

          var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
          });
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
      )
    };
  }

  initializeMap();

});

#map {
  height: 300px;
  width: 800px;
  border: 1px solid black;
}

<html>

<head>
  <title>Title</title>

  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

  <script src="test.js"></script>
</head>

<body>

  <div id="map"></div>

</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您的代码中存在语法错误(错误的“)”)。工作代码段:

$(document).ready(function() {

  //google map 
  var map, geocoder;

  function initializeMap() {
    google.maps.event.addDomListener(window, 'load', function() {
      codeAddress('33 W 23rd St, New York, NY');
    });
  }

  function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        var mapOptions = {
          zoom: 8,
          center: results[0].geometry.location,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map($("#map").get(0), mapOptions);

        var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
        });
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

  initializeMap();

});
#map {
  height: 300px;
  width: 800px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div id="map"></div>