I'm developing a Javascript app. It's my first attempt at a somewhat more complex application and I'm running into issues with Promises.
<!DOCTYPE html>
<html>
<head>
<title>Images</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
...
</style>
<script src="http://js.pusher.com/2.2/pusher.min.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=key&callback=initMap">
</script>
</head>
<body>
<div id="map"></div>
<script>
var map;
//setup Pusher API
var channel = "channel";
var pusher = new Pusher(appid);
var title;
var Channel = pusher.subscribe(channel);
function getTitle() {
return new Promise(function(resolve, reject) {
Channel.bind("new-listing", function(listing) {
title = listing['title'];
resolve(title);
}, 0);
});
}
getTitle().then(function(title) {
return title;
});
// console.log("Title: " + title);
function findCoordinates() {
return new Promise(function(resolve, reject) {
geocoder.geocode( { 'address': address}, function(results, status) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
resolve(latitude, longitude);
}, 0);
});
}
findCoordinates().then(function(latitude, longitude) {
console.log("Latitude: " + latitude);
console.log("Longitude: " + longitude);
});
// console.log("Latitude: " + latitude);
function initMap() {
var postion = {lat: latitude, lng: longitude}; //here I need latitude and longitude
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: postion
});
var marker = new google.maps.Marker({
position: postion,
map: map,
title: title //here I need title
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
</body>
</html>
I have three issues:
- While the promises are working, the problem is that the title is still not available outside that promise
- Same with latitude + I need to have both latitude and longitude available
- Another issue is that my code now complains that geocoder is not defined inside the promise.
Any feedback really appreciated.