### Start Vite Development Server Source: https://github.com/googlemaps/js-samples/blob/main/shared/cloud_shell_instructions.md Starts the Vite development server to run the web application, specifying the port for the web preview. This command is used both for initial startup and after updating the API key. ```bash npm start -- --port=8080 ``` -------------------------------- ### Install Node.js Dependencies with npm Source: https://github.com/googlemaps/js-samples/blob/main/shared/cloud_shell_instructions.md Installs the necessary Node.js packages and project dependencies using npm. This is a prerequisite for running the application and its development server. ```bash npm i ``` -------------------------------- ### Load Google Maps API with Libraries Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/marker-clustering/playground/index.html This code dynamically loads the Google Maps JavaScript API. It allows specifying libraries to import and sets up a callback function for when the API is ready. The API key is passed as a parameter. ```javascript (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>""+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Load Google Maps JavaScript API with Libraries Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/place-reviews/app/index.html This snippet demonstrates the core logic for dynamically loading the Google Maps JavaScript API. It handles API key management, library loading, and asynchronous initialization. It is designed to be a reusable module for other Google Maps features. ```javascript (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Initialize Google Maps API Key Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/marker-clustering/playground/index.html This snippet shows how to set the Google Maps JavaScript API key, which is required for using the API. It defines the API key within the environment variables. ```javascript const process = { env: {} }; process.env.GOOGLE_MAPS_API_KEY = "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg"; ``` -------------------------------- ### Initialize Google Maps API with Key and Load Libraries (JavaScript) Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/advanced-markers-graphics/playground/index.html This snippet initializes the Google Maps JavaScript API with a provided API key and dynamically loads libraries. It uses a promise-based approach to ensure the API is loaded before attempting to use its features. Dependencies include the Google Maps JavaScript API itself. The input is an object containing API configuration, and the output is the loaded Google Maps API object. ```javascript const process = { env: {} }; process.env.GOOGLE_MAPS_API_KEY = "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg"; (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"$"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"}); ``` -------------------------------- ### Load Google Maps JavaScript API with Libraries and API Key Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/dds-datasets-polygon/playground/index.html This code dynamically loads the Google Maps JavaScript API. It accepts an options object for libraries and the API key. It ensures the API is loaded only once and provides a mechanism to import additional libraries. ```javascript const process = { env: {} }; process.env.GOOGLE_MAPS_API_KEY = "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg"; (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"}); ``` -------------------------------- ### Load Google Maps JavaScript API with Libraries Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/event-properties/docs/index.html This snippet demonstrates how to dynamically load the Google Maps JavaScript API. It supports specifying libraries and an API key. The `importLibrary` function is used to load additional libraries once the API is ready. It handles potential loading errors and ensures the API is loaded only once. ```javascript var google = google || {}; google.maps = google.maps || {}; google.maps.__ib__ = function() {}; (g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}); var r = new Set; var e = new URLSearchParams; u = () => h || (h = new Promise(async (f, n) => { await (a = m.createElement("script")); e.set("libraries", [...r] + ""); for (k in g) e.set(k.replace(/A-Z/g, t => "_" + t[0].toLowerCase()), g[k]); e.set("callback", c + ".maps." + q); a.src = `https://maps.${c}apis.com/maps/api/js?` + e; d[q] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a) })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n)) })({ key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly" }); ``` -------------------------------- ### Initialize Google Maps API with Event Handlers (JavaScript) Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/event-properties/app/index.html This snippet initializes the Google Maps JavaScript API, enabling the dynamic loading of libraries and the ability to attach event handlers. It handles API key configuration and ensures the API loads only once, providing a callback for initialization. ```javascript const googleMapsInitializer = (g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}); var r = new Set, e = new URLSearchParams; u = () => h || (h = new Promise(async (f, n) => { a = m.createElement("script"); e.set("libraries", [...r] + ""); for (k in g) { e.set(k.replace(/["A-Z"]/g, t => "_" + t[0].toLowerCase()), g[k]); } e.set("callback", c + ".maps." + q); d[q] = f; a.src = `https://maps.${c}apis.com/maps/api/js?${e}`; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a) })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n)) })({ key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly" }); ``` -------------------------------- ### Initialize Google Maps JavaScript API with Place Autocomplete Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/place-autocomplete-data-simple/docs/index.html Initializes the Google Maps JavaScript API, loading the 'places' library and configuring it with an API key. This setup is essential for using Place Autocomplete features. ```javascript var g = {key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}; (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window; b=b[c]||(b[c]={});var d=b.maps||(b.maps={});var r=new Set,e=new URLSearchParams; u=()=>h||(h=new Promise(async(f,n)=>{a=m.createElement("script");e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Zª¯²-µ·ºÀ-ÖØ-öø-ˁ-,.-:<-@[-^`{-€-ÿ]*/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q); a.src=`https://maps.${c}apis.com/maps/api/js?`+e; d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)})); d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Initialize Google Maps JavaScript API with Text Search Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/place-text-search/docs/index.html This code snippet initializes the Google Maps JavaScript API, enabling features like text search. It dynamically creates a script tag to load the API with specified parameters, including an API key and libraries. Ensure you replace 'YOUR_API_KEY' with your actual API key. ```javascript /** * Initializes the Google Maps JavaScript API. * @param {object} params - Parameters for loading the API. * @param {string} params.key - Your Google Maps API key. * @param {string} [params.v='weekly'] - The version of the API to load. * @returns {Promise} A promise that resolves with the google.maps object. */ (g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}), r = new Set, e = new URLSearchParams; u = () => h || (h = new Promise(async (f, n) => { await (a = m.createElement("script")); e.set("libraries", [...r] + ""); for (k in g) e.set(k.replace(/[\](?!\[A-Z])([A-Z])/g, t => "_" + t[0].toLowerCase()), g[k]); e.set("callback", c + ".maps." + q); a.src = `https://maps.${c}apis.com/maps/api/js?${e}`; d[q] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a) })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n)) })({ key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly" }); ``` -------------------------------- ### Initialize Google Maps JavaScript API Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/map-simple/app/index.html This snippet initializes the Google Maps JavaScript API with a specified API key and version. It dynamically loads the API script into the document's head. Dependencies include the `key` and `v` parameters for the API. It returns a Promise that resolves when the API is ready. ```javascript var g = { key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly" }; (g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}); var r = new Set, e = new URLSearchParams; u = () => h || (h = new Promise(async (f, n) => { a = m.createElement("script"); e.set("libraries", [...r] + ""); for (k in g) { e.set(k.replace(/(\[A-Z\])/g, t => "_" + t[0].toLowerCase()), g[k]); } e.set("callback", c + ".maps." + q); a.src = `https://maps.${c}apis.com/maps/api/js?` + e; d[q] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a); })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => { r.add(f); return u().then(() => d[l](f, ...n)); }; })(g); ``` -------------------------------- ### Initialize Google Maps API with Key and Libraries (JavaScript) Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/advanced-markers-draggable/playground/index.html This snippet demonstrates how to dynamically load the Google Maps JavaScript API. It allows specifying an API key and a list of libraries to import. The script is appended to the document's head, and a callback function is used for initialization. It handles potential loading errors and ensures the API is loaded only once. ```javascript const process = { env: {} }; process.env.GOOGLE_MAPS_API_KEY = "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg"; (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});var r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Initialize Google Maps with Advanced Marker Library Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/advanced-markers-html-simple/app/index.html Initializes the Google Maps JavaScript API and imports the 'marker' library, which is required for using Advanced Markers. This script tag setup is dynamically generated. ```javascript (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});var r=new Set;var e=new URLSearchParams;var u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Initialize Google Maps with Polyline Styling Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/dds-datasets-polyline/jsfiddle/demo.html Initializes the Google Maps JavaScript API and loads the 'maps' library. This setup is necessary before you can create and style map features like polylines. It includes API key and version parameters. ```javascript var map; function initMap() { map = new google.maps.Map(document.getElementById("map"), { zoom: 13, center: { lat: 29.7604, lng: -95.3698 }, // Define the styles for the map styles: [ { featureType: "poi.business", elementType: "all", stylers: [ { visibility: "off" } ] } ] }); // Add a polyline to the map var lineSymbol = { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW }; var polyline = new google.maps.Polyline({ path: [ { lat: 29.7604, lng: -95.3698 }, { lat: 29.7704, lng: -95.3798 }, { lat: 29.7804, lng: -95.3698 }, { lat: 29.7704, lng: -95.3598 }, { lat: 29.7604, lng: -95.3698 } ], strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 3, map: map, icons: [ { offset: "0", repeat: "25px", icon: lineSymbol } ] }); } window.initMap = initMap; ``` -------------------------------- ### Initialize Google Maps JavaScript API Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/place-reviews/jsfiddle/demo.html Initializes the Google Maps JavaScript API with specified parameters such as API key and version. It dynamically loads the API script into the DOM. This is a foundational step for using any Google Maps features. ```javascript var g = {key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}; (g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__"; var m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}); var r = new Set, e = new URLSearchParams; u = () => h || (h = new Promise(async (f, n) => { a = m.createElement("script"); e.set("libraries", [...r] + ""); for (k in g) { e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]); } e.set("callback", c + ".maps." + q); a.src = `https://maps.${c}apis.com/maps/api/js?` + e; d[q] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a) })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => { r.add(f); return u().then(() => d[l](f, ...n)) } })(g); ``` -------------------------------- ### Configure Google Maps API Key and Load Libraries (JavaScript) Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/advanced-markers-collision/playground/index.html Sets up the Google Maps JavaScript API key and provides a mechanism to dynamically load necessary libraries. It ensures the API is loaded only once and handles potential loading errors. The `importLibrary` function allows for on-demand loading of map features. ```javascript const process = { env: {} }; process.env.GOOGLE_MAPS_API_KEY = "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg"; (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Initialize Google Maps JavaScript API with Libraries Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/web-components-accessibility/docs/index.html This snippet initializes the Google Maps JavaScript API, allowing for dynamic loading of libraries. It sets up a mechanism to load the API script and handle its loading status. Dependencies include the Google Maps JavaScript API itself. It returns a Promise that resolves with the API ready to use. ```javascript var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});var r=new Set,e=new URLSearchParams;var u=()=>h||(h=new Promise(async(f,n)=>{a=m.createElement("script");e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"}); ``` -------------------------------- ### Initialize Google Maps JavaScript API with Place Reviews Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/place-reviews/docs/index.html This snippet initializes the Google Maps JavaScript API, specifically enabling the necessary libraries for place reviews. It handles API key and library loading, with error handling for failed loads. It's designed to be a single-use initialization function. ```javascript var map; var service; var infowindow; function initMap() { const position = { lat: -33.867, lng: 151.195 }; map = new google.maps.Map( document.getElementById("map"), { center: position, zoom: 15, } ); service = new google.maps.places.PlacesService(map); infowindow = new google.maps.InfoWindow(); const request = { placeId: "ChIJN1t_tDeuEmsRUsoyG83fr04", fields: [ "name", "rating", "reviews", ], }; service.getDetails(request, (place, status) => { if (status === google.maps.places.PlacesServiceStatus.OK && place.reviews) { for (let i = 0; i < place.reviews.length; i++) { const review = place.reviews[i]; console.log(review.author_name, review.text); } infowindow.setContent( "
" + "" + place.name + "
" + "Rating: " + place.rating + "
" + "
" ); infowindow.open(map, place); } }); } ``` -------------------------------- ### Load Google Maps JavaScript API with Libraries Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/event-arguments/app/index.html This JavaScript code snippet dynamically loads the Google Maps JavaScript API. It allows specifying libraries and API keys, and handles the asynchronous loading process. It's designed to be a one-time setup for the API. ```javascript var google = window.google || (window.google = {}); var maps = google.maps || (google.maps = {}); const loadGoogleMaps = (async ({ key, v, libraries = [] }) => { let script = document.createElement('script'); const params = new URLSearchParams(); params.set('libraries', libraries.join(',')); params.set('key', key); params.set('v', v); params.set('callback', 'google.maps.__ib__'); script.src = `https://maps.googleapis.com/maps/api/js?${params.toString()}`; script.nonce = document.querySelector('script[nonce]')?.nonce || ''; return new Promise((resolve, reject) => { maps.__ib__ = resolve; script.onerror = () => reject(Error('The Google Maps JavaScript API could not load.')); document.head.append(script); }); }); maps.importLibrary = (libraryName) => { if (maps.importLibrary.loaded) { console.warn('The Google Maps JavaScript API only loads once. Ignoring:', { libraryName }); return; } return loadGoogleMaps({ key: 'AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg', v: 'weekly', libraries: [libraryName] }).then(() => maps.importLibrary = () => Promise.resolve()); }; maps.importLibrary.loaded = false; ``` -------------------------------- ### Initialize Map Web Component with Events (JavaScript) Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/web-components-events/playground/index.html This snippet demonstrates how to add a Google Maps JavaScript API map to a web page and configure it to handle events. It dynamically loads the API script and sets up the map instance. Ensure you have a valid Google Maps API key. ```javascript const process = { env: {} }; process.env.GOOGLE_MAPS_API_KEY = "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg"; (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});var r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"}); ``` -------------------------------- ### Calculate and Display Routes with Directions Service in TypeScript Source: https://context7.com/googlemaps/js-samples/llms.txt Calculates and displays driving routes between two locations using the Google Maps Directions Service. It takes origin and destination inputs from HTML elements and renders the route on the map. Requires HTML elements with IDs 'start', 'end', and 'map'. ```typescript function initMap(): void { const directionsService = new google.maps.DirectionsService(); const directionsRenderer = new google.maps.DirectionsRenderer(); const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 7, center: { lat: 41.85, lng: -87.65 }, } ); directionsRenderer.setMap(map); const onChangeHandler = function () { calculateAndDisplayRoute(directionsService, directionsRenderer); }; document.getElementById("start").addEventListener("change", onChangeHandler); document.getElementById("end").addEventListener("change", onChangeHandler); } function calculateAndDisplayRoute( directionsService: google.maps.DirectionsService, directionsRenderer: google.maps.DirectionsRenderer ) { directionsService .route({ origin: { query: (document.getElementById("start") as HTMLInputElement).value, }, destination: { query: (document.getElementById("end") as HTMLInputElement).value, }, travelMode: google.maps.TravelMode.DRIVING, }) .then((response) => { directionsRenderer.setDirections(response); }) .catch((e) => window.alert("Directions request failed due to " + e)); } window.initMap = initMap; ``` -------------------------------- ### Initialize Google Maps JavaScript API with Place Photos Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/place-photos/jsfiddle/demo.html This snippet shows how to dynamically load the Google Maps JavaScript API, including the 'places' library, which is necessary for using Place Photos. It handles API key management and ensures the API is loaded only once. ```javascript var __ib__ = function() {}; (g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}); var r = new Set(); var e = new URLSearchParams(); u = () => h || (h = new Promise(async (f, n) => { await (a = m.createElement("script")); e.set("libraries", [...r] + ""); for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]); e.set("callback", c + ".maps." + q); a.src = `https://maps.${c}apis.com/maps/api/js?` + e; d[q] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a) })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => { r.add(f); return u().then(() => d[l](f, ...n)) } })({ key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly" }); ``` -------------------------------- ### Initialize Google Maps API with Collision Management Options Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/advanced-markers-collision/docs/index.html Initializes the Google Maps JavaScript API, allowing for advanced marker collision management. This setup is crucial for defining how overlapping markers are handled on the map. It dynamically loads the API with specified options. ```javascript var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});var r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{a=m.createElement("script");e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[\[A-Z\]]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Load Google Maps JavaScript API with Event Handlers Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/event-properties/iframe/index.html This function loads the Google Maps JavaScript API dynamically. It allows specifying API keys, libraries, and other parameters. It also sets up a mechanism to handle potential loading errors and ensures the API is only loaded once. ```javascript var google = google || {}; google.maps = google.maps || {}; google.maps.__ib__ = function() {}; (g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}); var r = new Set; var e = new URLSearchParams; u = () => h || (h = new Promise(async (f, n) => { a = m.createElement("script"); e.set("libraries", [...r] + ""); for (k in g) e.set(k.replace(/[\]A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]); e.set("callback", c + ".maps." + q); a.src = `https://maps.${c}apis.com/maps/api/js?` + e; d[q] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a) })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => { r.add(f); u().then(() => d[l](f, ...n)) } })({ key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly" }); ``` -------------------------------- ### Initialize Google Maps JavaScript API and Load Libraries Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/marker-clustering/jsfiddle/demo.html This snippet initializes the Google Maps JavaScript API with a provided API key and version. It includes a mechanism to dynamically load additional libraries as needed, ensuring efficient API loading. ```javascript (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});var r=new Set;var e=new URLSearchParams;var u=()=>h||(h=new Promise(async(f,n)=>{a=m.createElement("script");e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Create and Style Polygon Overlays Source: https://context7.com/googlemaps/js-samples/llms.txt This TypeScript example demonstrates how to create and style a polygon shape on a Google Map. It defines the coordinates for the polygon's path, creates a new google.maps.Polygon object with specified stroke and fill properties, and adds it to the map. An event listener is included to log information when the polygon is clicked. ```typescript function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", } ); // Define the polygon path const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, { lat: 25.774, lng: -80.19 }, ]; // Create the polygon const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); // Add click listener bermudaTriangle.addListener('click', (event) => { console.log('Polygon clicked at:', event.latLng.toString()); }); } window.initMap = initMap; ``` -------------------------------- ### Initialize Google Map with API Key Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/add-map/playground/index.html This snippet demonstrates how to load the Google Maps JavaScript API with a specified API key. It dynamically creates a script tag and appends it to the document's head. Ensure you replace 'YOUR_API_KEY' with your actual Google Maps API key. ```javascript const process = { env: {} }; process.env.GOOGLE_MAPS_API_KEY = "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg"; (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"}); ``` -------------------------------- ### Initialize Google Maps JavaScript API Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/map-simple/jsfiddle/demo.html This snippet initializes the Google Maps JavaScript API with a provided API key and version. It dynamically creates a script tag to load the API, enabling map functionalities on the webpage. Ensure you have a valid API key. ```javascript const initMap = async () => { const map = new google.maps.Map(document.getElementById("map"), { zoom: 8, center: { lat: -34.397, lng: 150.644 }, }); }; window.initMap = initMap; ``` -------------------------------- ### Load Google Maps JavaScript API - JavaScript Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/event-properties/jsfiddle/demo.html This function dynamically loads the Google Maps JavaScript API script into the DOM. It accepts an object for configuration, including the API key and version. It ensures the API is loaded only once and handles potential loading errors. Dependencies include the browser's DOM manipulation capabilities. ```javascript var b = window["google"] || (window["google"] = {}); var d = b["maps"] || (b["maps"] = {}); var r = new Set(); var e = new URLSearchParams(); var u = () => h || (h = new Promise(async (f, n) => { a = document.createElement("script"); e.set("libraries", [...r] + ""); for (k in g) e.set(k.replace(/["A-Z"]/g, t => "_" + t[0].toLowerCase()), g[k]); e.set("callback", "google.maps.__ib__"); a.src = `https://maps.google.com/maps/api/js?${e}`; d["__ib__"] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = document.querySelector("script[nonce]")?.nonce || ""; document.head.append(a) })); d.importLibrary ? console.warn(p + " only loads once. Ignoring:", g) : d.importLibrary = (f, ...n) => r.add(f) && u().then(() => d.importLibrary(f, ...n)) ``` -------------------------------- ### Initialize Google Maps API with Text Search Library Source: https://github.com/googlemaps/js-samples/blob/main/dist/samples/boundaries-text-search/iframe/index.html This snippet initializes the Google Maps JavaScript API, dynamically loading the 'places' library. It includes options for API key, version, and other parameters. The loading is handled asynchronously, and it ensures the API is loaded only once. Dependencies include the Google Maps JavaScript API itself and the 'places' library for text search functionality. ```javascript (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={});var r=new Set;var e=new URLSearchParams;u=()=>h||(h=new Promise(async(f,n)=>{a=m.createElement("script");e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"}); ```