我在 HTML5 页面中使用谷歌地图。我想在一段中显示地图上方的坐标,但是当执行以下代码时,它会在空白页上显示变量。
如何在同一页面上的地图上方显示坐标?
<!DOCTYPE HTML>
<html>
<head>
<title>Geolocation With a Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
function TestGeo()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition( TestMap, error, {maximumAge: 3000000, timeout: 1000000, enableHighAccuracy: true} );
}
else
{
alert("Sorry, but it looks like your browser does not support geolocation.");
}
}
//Create a new map variable
var map;
function TestMap(position)
{
// Define the coordinates as a Google Maps LatLng Object
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Prepare the map options
var mapOptions =
{
zoom: 10,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map, and place it in the map_canvas div
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// Place the initial marker
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
}
function error() {
alert("Cannot locate user");
}
</script>
</head>
<body onload="TestGeo();">
<header>
<nav>
<ul>
<li><button onclick="location.href='takePicture.html'"><img src="/img/pic_icon.png" alt="Take Picture" /><br />Take<br />Picture</button>
<button onclick="location.href='gallery.html'"><img src="/img/gallery_icon.png" alt="Gallery" /><br />Show<br />Gallery</button>
<button onclick="location.href='recordsound.html'"><img src="/img/rec_icon.png" alt="Audio Recorder" /><br />Record<br />Sound</button>
<button onclick="location.href='more.html'"><img src="/img/more_icon.png" alt="More Options" /><br />More<br />Options</button>
</li>
</ul>
</nav>
</header>
<section>
<article>
<script>
var lat = position.coords.latitude;
var lon = position.coords.longitude;
document.write('<p>Latitude: ' + lat + '<br>Longitude: ' + lon + '</p>');
</script>
<br />
<div id="map_canvas" style="width: 300px; height: 300px; border-right: 1px solid #666666; border-bottom: 1px solid #666666; border-top: 1px solid #AAAAAA; border-left: 1px solid #AAAAAA;"></div>
</article>
</section>
</body>
</html>
编辑
更新代码:
<section>
<article>
<p>Latitude: <span id="lat"></span><br />Longitude: <span id="lon"></span></p>
<script>
var lat = position.coords.latitude;
var lon = position.coords.longitude;
document.getElementById('lat').innerHTML = lat;
document.getElementById('lon').innerHTML = lon;
</script>
<br />
<div id="map_canvas" style="width: 300px; height: 300px; border-right: 1px solid #666666; border-bottom: 1px solid #666666; border-top: 1px solid #AAAAAA; border-left: 1px solid #AAAAAA;"></div>
</article>
</section>
这似乎没有打印出坐标。