将开放时间添加到 google 地图信息 window

Adding opening hours to google maps info window

我正在尝试将某些景点的开放时间添加到我的每个景点的标记信息 window 中。到目前为止,我已经设法将开放时间从一个地方变成 html 元素进行练习,使用它的地点 ID,我想将开放时间添加到每个标记的信息 windows 中,但是我正在努力这样做。我对网络开发还很陌生,这是我目前正在做的一个项目。

    {
        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);
            }
        })
    }; ```

您的代码似乎不完整,所以我只是从头开始创建所有内容。

我所做的是首先创建一个包含您要放置标记的位置的位置 ID 数组。我使用地点 ID 是因为除了每个地点都是唯一的之外,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

接下来,我们需要为每个位置发送地点详细信息请求,以获取位置的名称、坐标(以便我们可以放置标记)及其营业时间。

 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);
  }
    });
}

之后,我们现在可以为这些位置创建标记和信息窗口:

// 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)); 
}

这里是 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.