This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
// 引入餐廳 Dummy data | |
import dummyRestaurants from "../dummy_data/xinyi.json"; | |
export default { | |
name: "Restaurants", | |
data() { | |
return { | |
map: null, | |
lat: 25.0325917, | |
lng: 121.5624999, | |
restaurants: [], | |
// 存放目前開啟的訊息視窗 | |
infowindow: null | |
}; | |
}, | |
mounted() { | |
this.initMap(); | |
// 取得餐廳假資料 | |
this.fetchRestaurants(); | |
// 使用餐廳假資料建立地標 | |
this.setMarker(); | |
}, | |
methods: { | |
fetchRestaurants() { | |
this.restaurants = dummyRestaurants.restaurants; | |
this.lat = dummyRestaurants.center.lat; | |
this.lng = dummyRestaurants.center.lng; | |
}, | |
initMap() { | |
this.map = new google.maps.Map(document.getElementById("map"), { | |
center: { lat: this.lat, lng: this.lng }, | |
zoom: 15, | |
maxZoom: 20, | |
minZoom: 3, | |
streetViewControl: false, | |
mapTypeControl: false | |
}); | |
}, | |
setMarker() { | |
// 為每間餐廳都建立地標、訊息視窗、事件監聽 | |
this.restaurants.forEach(location => { | |
const marker = new google.maps.Marker({ | |
// 設定為該餐廳的座標 | |
position: { lat: location.lat, lng: location.lng }, | |
map: this.map | |
}); | |
// 建立訊息視窗 | |
const infowindow = new google.maps.InfoWindow({ | |
content: ` | |
<div id="content"> | |
<p id="firstHeading" class="firstHeading">${location.name}</p> | |
</div> | |
`, | |
maxWidth: 200 | |
}); | |
// 綁定點擊事件監聽 | |
marker.addListener("click", () => { | |
// 如果目前有開啟中的訊息視窗,先將其關閉 | |
if (this.infowindow) this.infowindow.close(); | |
// 顯示被點擊地標的訊息視窗 | |
infowindow.open(this.map, marker); | |
// 存入目前開啟的訊息視窗 | |
this.infowindow = infowindow; | |
}); | |
}); | |
} | |
} | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment