So I have been trying to make an async map of the current area appear in the browser, but I ran into some problems. One of them is totally absurd. document.getElementById
return undefined or null. Secondly navigator.geolocation.getCurrentLocation()
does not place any value in my variable. The weird thing is that it works in the console of the browser but it never displays the map. This is my code:
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>
Edited:
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."));
}
});