<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps JavaScript API v3 Example: Reverse Geocoding</title>
<link
href="https://developers.google.com/maps/documentation/javascript/examples/default.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var variablejs;
geocoder = new google.maps.Geocoder();
var input = "41.021355,-96.020508";
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
variablejs = results[0].formatted_address; * * //document.write(variablejs); Not working**
*
//window.location.href = "http://localhost/test2.php?ad="+ variablejs; Working*
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
}); * * document.write(variablejs); * * //writes undefined variable (not working)
</script>
</head>
<body></body>
</html>
该部分(//document.write(variablejs); Not working)不会写入变量“variablejs”,但是当我使用该方法时(//window.location.href = "http://localhost/test2. php?ad="+ variablejs; Working ),它会写入 url 并转发将变量作为参数传递的页面。我想要做的是在同一 HTML 的正文中打印该变量。我尝试先初始化变量然后写入正文,但看起来该部分无法像全局变量或类似的东西那样访问。请帮忙。