单独的Google Maps JS文件不会加载到HTML文件中

时间:2015-11-17 15:30:01

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

我正在使用Google Maps API加载具有可拖动路线的地图。当我在html文件中写出javascript时,它工作得很好,但我仍然在添加函数和可读性。因此,我决定将两者分开。我得到的是:

HTML:

<!doctype html>
<html>
<head>
<link href="../CSS/main.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="initial-scale=1.0">
<meta charset="UTF-8">
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Create Route</title>
<script src="https://maps.googleapis.com/maps/api/js?key=XXXX" defer></script>
<script src="../JavaScript/create_route_map.js" defer></script>
</head>
<body>

<table>
<td>
<div id="map_canvas" name="map_canvas"></div>
</td>
<td>
<input size="25" id="hometown" type="text">
<input type = "button" value="Get Directions" onclick="calcRoute();">
</td>
</table>
</body>
</html>

JavaScript的:

var rendererOptions = {
    draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;

function initMap() {

  var town = new google.maps.LatLng(46.8133,-100.7790);
  var mapOptions = {
    center: town,
    zoom: 7
  };
  map = new google.maps.Map(document.GetElementByID('map_canvas'), mapOptions);
  directionsDisplay.setMap(map);

  google.maps.event.addListener(directionsDisplay, 'directions_changed', function(){
    computeTotalDistance(directionsDisplay.getDirections());
    });

calcRoute();
}

function calcRoute() {
  var start = "Town"
  var end = document.getElementById('hometown').value;
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

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

我尝试使用函数loadscript()但是没有用。

function loadScript() {
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'https://maps.googleapis.com/maps/api/js?key=XXXX' +
  'callback=initMap';
 document.body.appendChild(script);
}

我也尝试删除api密钥,因为v3不再需要它,但这也不起作用。

思考?建议?我错过了什么?

(我认为重要的一点是.css文件包含map-canvas div的高度和宽度。)

更新 在重新输入getElementById并放置上面的脚本之后,我从浏览器控制台获得的错误是: ReferenceError:未定义谷歌 NetworkError:发生网络错误

我如何修复参考错误?

0 个答案:

没有答案