1

I am trying to get the opening hours for certain attractions added to my marker info window for each attraction. So far I have managed to get the opening hours from one place into an html element for practice, using it's place ID, I would like to add the opening hours to the info windows to each marker, but I'm struggling to do so. I am fairly new to web development and this is for a project I am currently doing.

    {
        title: "Beamish Museum",
        lat: 54.8849314,
        lng: -1.6673812,
        header: 'Beamish Museum',
        description: "Beamish is a living, working museum, set in 300 acres of beautiful Durham countryside. Costumed folk bring to life the Town, Pit Village, Home Farm and Pockerley Old Hall.",
        image: 'assets/images/beamish_museum.jpg',
        googlePlaceID: 'ChIJGbReleF4fkgRc9FGCn_IVUw'
    },
    {
        title: "Bowes Museum",
        lat: 54.5420335,
        lng: -1.9175423,
        header: 'Bowes Museum',
        description:
            "The Bowes Museum is the jewel in the heart of the historic market town of Barnard Castle in the beautiful Durham countryside.Housing internationally significant collections of fine and decorative arts, the Museum was purpose built in the 19thC by wealthy businessman John Bowes and his French actress wife Josephine.",
        image: 'assets/images/bowes_museum.jpg',
        googlePlaceID: 'ChIJqfRfxtIkfEgR69y3K7lmqs0'
    },
    {
        title: "Durham Cathedral",
        lat: 54.7732329,
        lng: -1.5785808,
        header: 'Durham Cathedral',
        description:
            "Durham Cathedral has been a place of worship, welcome and hospitality for almost a millennium, inspiring all who come. Built in 1093 to house the Shrine of St Cuthbert, Durham Cathedral is renowned for its magnificent Romanesque architecture and spectacular location at the heart of the Durham World Heritage Site. It is also the resting place of the Venerable Bede",
        image: 'assets/images/durham_cathedral_1.jpg',
        googlePlaceID: 'ChIJFRrlxmGHfkgRy8-a4viXKO0'
    },
    {
        title: "High Force Waterfall",
        lat: 54.6506813,
        lng: -2.1889541,
        header: 'High Force Waterfall',
        description:
            "High Force is one of the most impressive waterfalls in England. The River Tees has been plunging into this gorge for thousands of years but the rocks it reveals are far more ancient – with origins dating back over 300 million years!",
        image: 'assets/images/high_force_waterfall.jpg',
        googlePlaceID: 'ChIJydr0nQg6fEgRDx2CrK6oURU'
    },
    {
        title: "Diggerland Durham",
        lat: 54.8014524,
        lng: -1.6782121,
        header: 'Diggerland Durham',
        description: "Diggerland is the UK’s most unique construction-themed adventure park where children and adults can drive, ride and operate earth-moving machinery in a safe and family friendly environment.",
        image: 'assets/images/digger_land.jpg',
        googlePlaceID: 'ChIJ6--NSbF_fkgRc-kFeu4wEtE'
    },
    {
        title: "Raby Castle",
        lat: 54.5915822,
        lng: -1.8041618,
        header: 'Raby Castle',
        description: "Raby Castle offers a brilliant and memorable family day out. It is a jewell in the crown of County Durham and one of England's finest medieval castles.",
        image: 'assets/images/raby_castle.jpg',
        googlePlaceID: 'ChIJR7YOnAEmfEgRk6PBpBOxBDU'
    },
];

window.onload = function () {
    loadMap();
};

function loadMap() {
    var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 9,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    };
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    var service = new google.maps.places.PlacesService(map);

    //Create and open InfoWindow.
    var infoWindow = new google.maps.InfoWindow();

    for (var i = 0; i < markers.length; i++) {
        var data = markers[i];
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: data.title,
        });

        //Attach click event to the marker.
        (function (marker, data) {
            google.maps.event.addListener(marker, "click", function () {
                
                let markerInfoHTML = `<div class='container-fluid text-center'>
                <h4 class="info-window-title">${data.header}</h4>
                <p>${data.description}</p>
                <img class="marker-img" src="${data.image}">
                </div>
                `;
                
                infoWindow.setContent(markerInfoHTML);
                infoWindow.open(map, marker);
                
        });
        })(marker, data);
    }
        
    service.getDetails({
        placeId: 'ChIJqfRfxtIkfEgR69y3K7lmqs0'
    }, function (place, status) {
      
            // Get DIV element to display opening hours
            var opening_hours_div = document.getElementById("opening-hours");

            // Loop through opening hours weekday text
            for (var i = 0; i < place.opening_hours.weekday_text.length; i++) {

                // Create DIV element and append to opening_hours_div
                var content = document.createElement('div');
                content.innerHTML = place.opening_hours.weekday_text[i];
                opening_hours_div.appendChild(content);
            }
        })
    }; ```

1 Answers1

0

Your code seems to be incomplete, so I just created everything from scratch.

What I did is to first create an array of place IDs of the locations you'd like to put a marker on. I used the Place IDs because aside from this being unique per each place, Place IDs can also be cached.

// An array of the locations you'd like to put a marker on
var locations = ["ChIJGbReleF4fkgRc9FGCn_IVUw", //Beamish Museum
               "ChIJqfRfxtIkfEgR69y3K7lmqs0", //Bowes Museum
               "ChIJFRrlxmGHfkgRy8-a4viXKO0", // Durham Cathedral
               "ChIJydr0nQg6fEgRDx2CrK6oURU", //High Force Waterfall
               "ChIJ6--NSbF_fkgRc-kFeu4wEtE", //Diggerland Durham
               "ChIJR7YOnAEmfEgRk6PBpBOxBDU"] //Raby Castle

Next, we'll need to send a Place Details request per each of these locations in order to get the location's name, coordinates (so that we can place a marker) and its business hours.

 function getPlaceDetails(request){
service.getDetails(request, function (place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
  createMarker(place);
    } else {
  alert('Place Details request failed due to: ' + status);
  }
    });
}

After that, we can now create the Marker and InfoWindow for these locations:

// create a marker and infowindow for each of the locations
function createMarker(place){
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });

   // create ordered list for the location's business hours
   var html = "<ol>";
   var placesWeekdayText = place.opening_hours.weekday_text;

   // Loop through array and add list items
   for (var i=0; i<placesWeekdayText.length; i++) {
    html += "<li>" + placesWeekdayText[i] + "</li>";
   }
   html += "</ol>";

   //create info window content
   var content = "<h3>" + place.name + "</h3> <h4>Business hours:</h4>" + html;
    
   //add marker on click listener to open an infowindow
   //with each location's name and opening_hours.weekday_text
    google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
    return function() {
        // To close other infowindows if one is already open
      if (openInfoWindow)
            openInfoWindow.close();
     
     //set the contents of the infowindow
      infowindow.setContent(content);
      openInfoWindow = infowindow;
      //open the infowindow
      infowindow.open(map,marker);
    };
   })(marker,content,infowindow)); 
}

Here is the working fiddle.

Important: Please note that the Places library under the Maps JavaScript API is subject to additional queries per second rate limit as documented here. As suggested on that documentation, for batch requests, you may want to use the web service APIs. Or depending on your use case, you may also want to consider setting timeouts in between each Places details requests to prevent these queries per second rate limits.

annkylah
  • 457
  • 4
  • 11
  • Thank you for this, I have been puzzling over this for some time now – adamparker75 Aug 05 '20 at 09:20
  • You're welcome. If this answer helped you with your question, please mark it as [accepted](https://stackoverflow.com/help/someone-answers) – annkylah Aug 06 '20 at 00:18