Introducción
En este instructivo, se muestra cómo agregar un mapa simple de Google Maps con un marcador a una página web. Está destinado a personas con conocimientos básicos o intermedios de HTML y CSS, y un poco de JavaScript. Si deseas obtener una guía avanzada para crear mapas, consulta la guía para desarrolladores.
A continuación, se muestra el mapa que crearás con este instructivo. El marcador se ubica en Uluru (también conocido como Ayers Rock) en el Parque Nacional Uluru-Kata Tjuta.
TypeScript
// Initialize and add the map let map; async function initMap(): Promise<void> { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } ); // The marker, positioned at Uluru const marker = new AdvancedMarkerView({ map: map, position: position, title: 'Uluru' }); } initMap();
JavaScript
// Initialize and add the map let map; async function initMap() { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerView } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", }); // The marker, positioned at Uluru const marker = new AdvancedMarkerView({ map: map, position: position, title: "Uluru", }); } initMap();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html> <head> <title>Add Map</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <div id="map"></div> <!-- prettier-ignore --> <script>(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"});</script> </body> </html>
Prueba la muestra
Cómo comenzar
Para crear un mapa de Google Maps con un marcador en tu página web, sigue estos tres pasos:
Necesitas un navegador web. Elige uno conocido, como Google Chrome (recomendado), Firefox, Safari o Edge, según la plataforma de la lista de navegadores compatibles.
Paso 1: Crea una página HTML
Este es el código para una página web HTML básica:
<!DOCTYPE html> <!-- @license Copyright 2019 Google LLC. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 --> <html> <head> <title>Add Map</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <div id="map"></div> <!-- prettier-ignore --> <script>(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"});</script> </body> </html>
Ten en cuenta que esta es una página muy básica con un título de nivel tres (h3
) y un solo elemento div
. Puedes agregar el contenido que desees a la página web.
Comprende el código
El siguiente código crea una página HTML que contiene un título y un cuerpo.
<html> <head> </head> <body> </body> </html>
Puedes agregar un título de nivel tres encima del mapa con el siguiente código.
<h3>My Google Maps Demo</h3>
El siguiente código define un área de la página para tu mapa de Google Maps.
<!--The div element for the map --> <div id="map"></div>
En esta etapa del instructivo, el elemento div
aparece como un bloque gris, porque todavía no agregaste un mapa. En el siguiente código, se describe el CSS que establece el tamaño y el color del elemento div
.
/* Set the size of the div element that contains the map */ #map { height: 400px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ }
En el código anterior, el elemento style
establece el tamaño div
de tu mapa. Configura el ancho y la altura de div
en más de 0 px para que el mapa sea visible. En este caso, se configura el div
con una altura de 400 píxeles y un ancho del 100% para que se muestre a lo ancho de tu página web.
El cargador de arranque prepara la API de Maps JavaScript para la carga (no se cargarán bibliotecas hasta que se llame a importLibrary()
).
<script> (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: "YOUR_API_KEY_HERE", // Add other bootstrap parameters as needed, using camel case. // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.) }); </script>
Consulta el Paso 3: Obtén una clave de API para ver instrucciones sobre cómo obtener tu propia clave.
Paso 2: Agrega un mapa con un marcador
En esta sección, se muestra cómo cargar la API de Maps JavaScript en tu página web y cómo escribir tu propio código JavaScript que use la API para agregar un mapa con un marcador.
TypeScript
// Initialize and add the map let map; async function initMap(): Promise<void> { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } ); // The marker, positioned at Uluru const marker = new AdvancedMarkerView({ map: map, position: position, title: 'Uluru' }); } initMap();
JavaScript
// Initialize and add the map let map; async function initMap() { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerView } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", }); // The marker, positioned at Uluru const marker = new AdvancedMarkerView({ map: map, position: position, title: "Uluru", }); } initMap();
En el código anterior, las bibliotecas Map
y AdvancedMarkerView
se cargan cuando se llama a la función initMap()
.
Comprende el código
En el siguiente código, se construye un nuevo objeto de mapa de Google Maps y se agregan propiedades al mapa, incluidos el centro y el nivel de zoom. Consulta la documentación para conocer otras opciones de propiedades.
TypeScript
// The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } );
JavaScript
// The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerView } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", });
En el código anterior, new Map()
crea un nuevo objeto de mapa de Google Maps. La propiedad center
le indica a la API dónde debe centrar el mapa.
Obtén más información sobre cómo obtener coordenadas de latitud y longitud o convertir una dirección en coordenadas geográficas.
La propiedad zoom
especifica el nivel de zoom del mapa. 0 es el valor de zoom más bajo y muestra todo el planeta. Define un valor de zoom más alto para acercarte en el globo con resoluciones más altas.
El siguiente código coloca un marcador en el mapa. La propiedad position
define la posición del marcador.
TypeScript
// The marker, positioned at Uluru const marker = new AdvancedMarkerView({ map: map, position: position, title: 'Uluru' });
JavaScript
// The marker, positioned at Uluru const marker = new AdvancedMarkerView({ map: map, position: position, title: "Uluru", });
Obtén más información sobre los marcadores:
- Cómo configurar un marcador para que sea accesible
- Marcadores con íconos gráficos
- Animaciones de marcadores
Paso 3: Obtén una clave de API
En esta sección, se explica cómo autenticar tu app en la API de Maps JavaScript con tu propia clave de API.
Sigue estos pasos para obtener una clave de API:
Ve a la consola de Google Cloud.
Crea o selecciona un proyecto.
Haz clic en Continuar para habilitar la API y los servicios relacionados.
En la página Credenciales, obtén una clave de API (y configura sus restricciones). Si ya tienes una clave de API sin restricciones o una clave con restricciones de navegador, puedes usarla.
Para evitar el robo de cuota y proteger tu clave de API, consulta Cómo usar las claves de API.
Habilita la facturación. Consulta Uso y facturación para obtener más información.
Copia todo el código del instructivo de esta página en tu editor de texto.
Reemplaza el valor del parámetro
key
en la URL con tu propia clave de API (es decir, la clave de API que acabas de obtener).<script> (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: "YOUR_API_KEY_HERE", // Add other bootstrap parameters as needed, using camel case. // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.) }); </script>
Guarda este archivo con un nombre que termine en
.html
, comoindex.html
.Para cargar el archivo HTML en un navegador web, arrástralo del escritorio al navegador. También puedes hacer doble clic en el archivo en la mayoría de los sistemas operativos.
Sugerencias y solución de problemas
- Puedes modificar determinadas opciones, como los diseños y las propiedades, para personalizar el mapa. Si deseas obtener más información sobre cómo personalizar mapas, consulta las guías de diseño y dibujos en el mapa.
- Usa la consola de Herramientas para desarrolladores en tu navegador web para probar y ejecutar tu código, leer los informes de errores y resolver los problemas.
- Usa las siguientes combinaciones de teclas para abrir la consola en Chrome:
Comando + Opción + J (en Mac) o Control + Mayúsculas + J (en Windows). Sigue los pasos que se indican a continuación para obtener las coordenadas de latitud y longitud de una ubicación en Google Maps.
- Abre Google Maps en un navegador.
- Haz clic con el botón derecho en la ubicación exacta del mapa para la que necesitas las coordenadas.
- Selecciona ¿Qué hay aquí? en el menú contextual que aparece. El mapa mostrará una tarjeta en la parte inferior de la pantalla. Busca las coordenadas de latitud y longitud en la última fila de la tarjeta.
Puedes convertir una dirección en coordenadas de latitud y longitud mediante el servicio Geocoding. Las guías para desarrolladores brindan información detallada sobre cómo comenzar a usar el servicio Geocoding.