我对 JS 和 Jquery 很陌生,想知道是否有人可以帮忙:)
我正在使用以下代码来创建地图,它可以很好地内联
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Google Map with GPX track</title>
<style type="text/css">
html, body, #map_display { width: 100%; height: 100%; margin: 0; padding: 0 }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function gpx() {
var map = new google.maps.Map(document.getElementById("map_display"), {
mapTypeId: google.maps.MapTypeId.HYBRID
});
$.ajax({
type: "GET",
url: "/alan.gpx",
dataType: "xml",
success: function(xml) {
var points = [];
var bounds = new google.maps.LatLngBounds ();
$(xml).find("trkpt").each(function() {
var lat = $(this).attr("lat");
var lon = $(this).attr("lon");
var p = new google.maps.LatLng(lat, lon);
points.push(p);
bounds.extend(p);
});
var route = new google.maps.Polyline({
path: points,
strokeColor: "#FF00AA",
strokeOpacity: .7,
strokeWeight: 4
});
route.setMap(map);
map.fitBounds(bounds);
}
});
}
</script>
</head>
<body onload="gpx()">
<div id="map_display"></div>
</body>
</html>
我希望将其放入外部 .js 文件中,但它只是不想工作
这是 JS 文件,那里的警报告诉我正在调用脚本
alert ("hello from script");
function gpx() {
var map = new google.maps.Map(document.getElementById("map_display"), {
mapTypeId: google.maps.MapTypeId.TERRAIN
});
$.ajax({
type: "GET",
url: "alan.gpx",
dataType: "xml",
success: function(xml) {
var points = [];
var bounds = new google.maps.LatLngBounds ();
$(xml).find("trkpt").each(function() {
var lat = $(this).attr("lat");
var lon = $(this).attr("lon");
var p = new google.maps.LatLng(lat, lon);
points.push(p);
bounds.extend(p);
});
var poly = new google.maps.Polyline({
// use your own style here
path: points,
strokeColor: "#FF00AA",
strokeOpacity: .7,
strokeWeight: 4
});
poly.setMap(map);
// fit bounds to track
map.fitBounds(bounds);
}
});
}
$(document).on("ready", gpx);
我正在使用的html文件是
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Import GPX file to Google Maps</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="map_display"></div>
</body>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="ac-gpxscript.js"></script>
</html>
当我这样做时,我得到一个错误 Uncaught TypeError: Cannot read property 'offsetWidth' of null
我很确定我只是在 js 文件中遗漏了一些小东西,但对于我的生活,我无法弄清楚是什么了
我确定在 DOM 准备好之前调用了 JS,但我认为 $(document) 命令只会在 DOM 准备好时调用它