前面我們學習了地圖和標記的創建。那麼今天我們來學習怎樣在地圖上顯示一個窗口(infowindow)
infowindow構造函數爲:InfoWindow(opts?:InfoWindowOptions)。
InfoWindowOptions對象指定用於顯示信息窗口的初始化參數。
InfoWindowOptions對象屬性:
content:包含一個文本字符串或信息窗口中顯示DOM節點。
pixelOffset:表示信息窗口的位置偏移。
position:infowindow顯示的位置(經緯度)。
maxWidth:指定的像素信息窗口的最大寬度。
下面我們來創建一個infowindow:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Info windows</title> <style> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } </style> </head> <body> <div id="map"></div> <script> // 初始化地圖 function initMap() { var uluru = {lat: -25.363, lng: 131.044}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: uluru }); //infowindow要顯示的內容 var contentString = "this is a infowindow!" //定義infowindow var infowindow = new google.maps.InfoWindow({ content: contentString }); //定義marker var marker = new google.maps.Marker({ position: uluru, map: map, title: 'Uluru (Ayers Rock)' }); //爲marker添加一個點擊事件的監聽函數(即點即marker後將infowindow顯示出來) marker.addListener('click', function() { infowindow.open(map, marker); }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> </script> </body> </html>
以上就是創建infowindow的代碼,當我們點擊地圖上的marker時,infowindow就顯示出來了!
當我們想改變infowindow的內容時,我們可以使用 "infowindow.setContent("要改變的內容");"來改變infowindow的內容,同時我們也可以使用infowindow.getContent()來獲取infowindow的內容。