一、Google Maps 簡介
Google Maps 是谷歌提供的地圖服務,通過其 JavaScript API,開發者可以在網頁中嵌入地圖,添加標記、路徑、地理編碼、路線導航等功能,適用于位置展示、物流追蹤、LBS 應用等場景。
二、獲取 Google Maps API Key
- 登錄 Google Cloud 平臺:https://console.cloud.google.com/
- 創建項目
- 啟用 Maps JavaScript API、Geocoding API 等所需服務
- 獲取 API 密鑰(API Key)
- 設置配額限制和安全域名
三、引入 Google Maps 腳本
方式一:通過 <script>
標簽加載
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
YOUR_API_KEY
替換為實際的 API 密鑰callback=initMap
表示在加載完成后調用initMap
函數
四、基本地圖使用示例
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Google 地圖示例</title><style>#map {height: 400px;width: 100%;}</style></head><body><h3>我的地圖</h3><div id="map"></div><script>function initMap() {const location = { lat: 39.9042, lng: 116.4074 }; // 北京坐標const map = new google.maps.Map(document.getElementById("map"), {zoom: 10,center: location,});const marker = new google.maps.Marker({position: location,map: map,title: "北京"});}</script><script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script></body>
</html>
五、常用功能介紹
5.1 添加標記(Marker)
new google.maps.Marker({position: { lat: 31.2304, lng: 121.4737 },map: map,title: "上海"
});
5.2 信息窗口(InfoWindow)
const infowindow = new google.maps.InfoWindow({content: "<h4>這里是上海</h4>"
});
marker.addListener("click", () => {infowindow.open(map, marker);
});
5.3 繪制路線(DirectionsService)
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);directionsService.route({origin: "Beijing",destination: "Shanghai",travelMode: "DRIVING"
}, (result, status) => {if (status === "OK") {directionsRenderer.setDirections(result);}
});
六、使用注意事項
- Google Maps 在中國大陸部分網絡環境可能無法訪問
- 建議綁定域名進行 API Key 限制
- 免費配額有限(每月 200 美元額度)
七、學習資源推薦
- Google Maps JavaScript API 官網
- Google Maps 示例庫
- Google Cloud Console
- 菜鳥教程 Google 地圖
本文由“小奇Java面試”原創發布,轉載請注明出處。
可以搜索【小奇JAVA面試】第一時間閱讀,回復【資料】獲取福利,回復【項目】獲取項目源碼,回復【簡歷模板】獲取簡歷模板,回復【學習路線圖】獲取學習路線圖。