所以我一直试图在浏览器中显示当前区域的异步映射,但是我遇到了一些问题。其中一个是完全荒谬的。 document.getElementById
返回undefined或null。其次navigator.geolocation.getCurrentLocation()
不会在我的变量中放置任何值。奇怪的是它在浏览器的控制台中工作,但它从不显示地图。这是我的代码:
var mapDiv = document.getElementById("map");
var p = document.getElementById("msg");
var coordsObj;
var promise = new Promise((resolve, reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(location => {
coordsObj = {
latitude: location.coords.latitude,
longitude: location.coords.longitude
};
});
resolve(coordsObj);
}
else {
reject("Please update your browser to support location.");
}
});
promise.then(value => {
showPosition(value);
},
value => {
p.innerHTML = value;
});
function showPosition(position) {
var latLonString = position.latitude + "," + position.longitude;
var imgHref = "https://maps.googleapis.com/maps/api/staticmap?center="
+ latLonString + "&zoom=14&size=400x300&sensor=false&key=AIzaSyDCIONKZUw8jsxtdS_ISoZe6tGZOtEwdWY";
mapDiv.innerHTML = "<img src='" + imgHref + "'>";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDCIONKZUw8jsxtdS_ISoZe6tGZOtEwdWY&callback=initMap"
type="text/javascript"></script>
<script src="./task 1.js"></script>
</head>
<body>
<p id="msg"></p>
<div id="map"></div>
</body>
</html>
编辑:
var promise = new Promise((resolve, reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(location => {
coordsObj = {
latitude: location.coords.latitude,
longitude: location.coords.longitude
};
resolve(coordsObj);
}, reject("Please update your browser to support location."));
}
});