在谷歌距离矩阵的代码中输入密钥的位置

时间:2015-09-09 11:48:07

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

我创建了几个使用Google距离的网页。我为Google提供了javascript和HTML的示例代码,并根据我的目的对其进行了调整。他们似乎说我需要一个API密钥来使用该服务,但没有它我的页面工作正常。首先,当我希望每天有几百个请求时,使用API​​密钥是必不可少的。如果必要,我在哪里将API密钥放在Google提供的以下示例代码中?

function initialize() {
  var opts = {
    center: new google.maps.LatLng(55.53, 9.4),
    zoom: 10
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), opts);
  geocoder = new google.maps.Geocoder();
}

function calculateDistances() {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      //origins: [origin1, origin2],
    origins: [origin2],
      //destinations: [destinationA, destinationB],
    destinations,
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
}

function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML = '';
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      addMarker(origins[i], false);
      for (var j = 0; j < results.length; j++) {
        addMarker(destinations[j], true);
        outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
            + ': ' + results[j].distance.text + ' in '
            + results[j].duration.text + '<br>';
      }
    }
  }
}

function addMarker(location, isDestination) {
  var icon;
  if (isDestination) {
    icon = destinationIcon;
  } else {
    icon = originIcon;
  }
  geocoder.geocode({'address': location}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      bounds.extend(results[0].geometry.location);
      map.fitBounds(bounds);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        icon: icon
      });
      markersArray.push(marker);
    } else {
      alert('Geocode was not successful for the following reason: '
        + status);
    }
  });
}

function deleteOverlays() {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="content-pane">
      <div id="inputs">
        <pre>
var origin1 = new google.maps.LatLng(55.930, -3.118);
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = new google.maps.LatLng(50.087, 14.421);
        </pre>
        <p><button type="button"      onclick="calculateDistances();">Calculate
          distances</button></p>
      </div>
      <div id="outputDiv"></div>
    </div>
    <div id="map-canvas"></div>
  </body>

1 个答案:

答案 0 :(得分:0)

我知道没有显式方法将Google地图API密钥插入JavaScript代码(我想你想这样做)。

执行此操作的一般方法是使用标准javascript标记引用密钥,并将其放在 src 属性中。

示例:

<script>
   src="https://maps.googleapis.com/maps/api/js?key=123456ABCDEFG&sensor=false" 
    </script>

由于您使用 DomListener 呼叫您的Google地图,上面的示例调用API密钥是要走的路,除此之外您还可以通过使用此行来调用您的Google地图功能代码总是显示在谷歌地图官方文档中:

<script async defer
      src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initialize">
    </script>

async关键字意味着HTML(网页)不必等待Google Maps API响应才能呈现。基本上,HTML(除了谷歌地图)渲染,然后当实际地图准备好时,它将加载。如果选择此选项,则擦除 DomListener 代码行。

其余的可以在谷歌地图的官方页面找到

网址:https://developers.google.com/maps/documentation/javascript/tutorial#api_key