基本
CSS
以下是 Google 建議你使用的最低 CSS 規則,單獨的 CSS 檔案或 HTML 樣式標記,例如 <style type="text/css">...</style>
。
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 400px;
}
HTML
Google 建議你在 Web 應用程式中宣告真正的 DOCTYPE
。
<!DOCTYPE html>
使用以下指令碼標記在你的應用程式中載入 Google Maps JavaScript API。
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize">
</script>
建立一個 HTML 元素來儲存地圖。
<div id="map"></div>
JavaScript
function initialize() {
// Create a LatLng object
// We use this LatLng object to center the map and position the marker
var center = new google.maps.LatLng(50,0);
// Declare your map options
var mapOptions = {
zoom: 4,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create a map in the #map HTML element, using the declared options
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Create a marker and place it on the map
var marker = new google.maps.Marker({
position: center,
map: map
});
}
完整的例子
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 400px;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initialize() {
// Create a LatLng object
// We use this LatLng object to center the map and position the marker
var center = new google.maps.LatLng(50, 0);
// Declare your map options
var mapOptions = {
zoom: 4,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create a map in the #map HTML element, using the declared options
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Create a marker and place it on the map
var marker = new google.maps.Marker({
position: center,
map: map
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize" async defer></script>
</body>
</html>
演示
更多資訊
有關更多資訊,請閱讀本主題的備註 。