9

根据 API ref,地图对象应该有一个 getProjection 方法:
http ://code.google.com/apis/maps/documentation/v3/reference.html#Map

在此示例中加载地图时应提醒 x,y 点,但会将值作为未定义抛出。这是在 onload 中调用的以下示例代码。

function initialize() {
    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(-34.397, 150.644),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    alert("projection:" + map.getProjection());
}
4

1 回答 1

42

在地图完成初始化之前它不可用。在访问它之前,您必须等待“projection_changed”事件。

function initialize() {
 var mapOptions = {
   zoom: 8,
   center: new google.maps.LatLng(-34.397, 150.644),
   mapTypeId: google.maps.MapTypeId.ROADMAP
   };
 map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);
 google.maps.event.addListenerOnce(map,"projection_changed", function() {
   alert("projection:"+map.getProjection());
 });
}

概念证明小提琴

代码片段:

function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
  google.maps.event.addListenerOnce(map, "projection_changed", function() {
    console.log("projection:" + map.getProjection());
    document.getElementById('output').innerHTML = "map.getProjection()=" + JSON.stringify(map.getProjection(), null, ' ');
  });
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map-canvas {
  height: 80%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Simple Map</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="output"></div>
  <div id="map-canvas"></div>

  <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=&v=weekly" async></script>
</body>

</html>

于 2013-06-19T13:00:22.160 回答