google-maps-api-3
#google-
maps-api-3
Tabla de contenido
Acerca de 1
Capítulo 1: Primeros pasos con google-maps-api-3 2
Observaciones 2
Documentación oficial de Google 2
Sobre los ejemplos en este tema. 2
Examples 2
Lo esencial 2
CSS 2
HTML 2
JavaScript 3
Ejemplo completo 3
Manifestación 4
Más información 4
Coloque el pin del usuario en el mapa. 4
Puede volver a colocar YOUR_API_KEY en el código con una clave de la API de Google. El es 5
Ahora normalmente tienes un mapa básico en tu pantalla. Puedes encontrar el código complet 5
La función de geolocalización que utilizamos aquí es muy simple. Puedes tener la documenta 6
Capítulo 2: API de JavaScript de Google Maps v3 - Avanzado 10
Observaciones 10
Documentación oficial de Google 10
Sobre los ejemplos en este tema. 10
Examples 10
Mapa de estilo personalizado 10
Creditos 13
Acerca de
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: google-maps-api-3
It is an unofficial and free google-maps-api-3 ebook created for educational purposes. All the
content is extracted from Stack Overflow Documentation, which is written by many hardworking
individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official google-maps-
api-3.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/es/home 1
Capítulo 1: Primeros pasos con google-
maps-api-3
Observaciones
Documentación oficial de Google
• Descripción general de la API de JavaScript de Google Maps
• Ejemplos de código API de JavaScript de Google Maps
• Referencia de API de JavaScript de Google Maps
Sobre los ejemplos en este tema.
• YOUR_API_KEYdebe ser reemplazado por su propia clave de API de aplicación. Puede obtener
una clave de API y configurarla en la Consola de API de Google .
Examples
Lo esencial
CSS
Estas son las reglas de CSS mínimas que Google recomienda usar, en un archivo CSS separado
o dentro de una etiqueta de estilo HTML, por ejemplo, <style type="text/css">...</style> .
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 400px;
}
HTML
Google recomienda que declare un DOCTYPE verdadero dentro de su aplicación web.
<!DOCTYPE html>
Use la siguiente etiqueta de script para cargar la API de JavaScript de Google Maps en su
https://riptutorial.com/es/home 2
aplicación.
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize">
</script>
Crea un elemento HTML para mantener el mapa.
<div id="map"></div>
JavaScript
Aquí hay un ejemplo muy simple que muestra un mapa y un marcador .
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
});
}
Ejemplo completo
<!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;
}
https://riptutorial.com/es/home 3
#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>
Manifestación
Demostración de JSFiddle
Más información
Por favor, lea los Comentarios de este tema para obtener más información.
Coloque el pin del usuario en el mapa.
Tenga en cuenta que si no está familiarizado con la API de Google Maps, puede leer el ejemplo
anterior (conceptos básicos) para comprender este pequeño ejemplo.
• Primero, inicialice el mapa .
https://riptutorial.com/es/home 4
Puedes agregar un elemento de mapa en tu código HTML y una porción de CSS como esta:
<!DOCTYPE html>
<html>
<head>
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
Ahora, debe agregar la biblioteca de Google Maps en su código con un script de balise como
este:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
Puede volver a colocar YOUR_API_KEY en el código con
una clave de la API de Google. El es un enlace para obtener
una clave.
A continuación, debe escribir en su código una función que sirva como devolución de llamada (o
una función de inicialización) para su mapa. Aquí, solo agregamos una pequeña función que
puede encontrar en google aquí :
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
Ahora normalmente tienes un mapa básico en tu pantalla.
Puedes encontrar el código completo en google .
• En segundo lugar, encontrar la posición del usuario.
https://riptutorial.com/es/home 5
Para solicitar la posición del usuario, hay una función muy simple que proporciona el navegador:
navigator.geolocation.getCurrentPosition(showPosition);
Tenga en cuenta que esta función acepta un parámetro. Es una función a la que llamar si la
geolocalización es exitosa.
Tenemos que crear esta función. :)
function showPosition(position) {
alert (position);
}
Esta función es muy simple y tendremos que actualizarla después para poder trazar un marcador
en la posición del usuario.
La función de geolocalización que utilizamos aquí es muy
simple. Puedes tener la documentación completa en
w3schools .
En su punto el código se ve así:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
navigator.geolocation.getCurrentPosition(showPosition);
function initMap() {
https://riptutorial.com/es/home 6
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
function showPosition(position) {
console.log(position);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
</body>
</html>
• Y tercero, mostrar la posición del usuario en el mapa con un marcador.
Para mostrar un marcador en el mapa, puede utilizar la función en el ejemplo "conceptos
básicos":
// Create a marker and place it on the map
var marker = new google.maps.Marker({
position: position,
map: map
});
No voy a detallar estas líneas de códigos con mucha precisión. Solo debes saber que cuando
crees un marcador con este código: new google.maps.Marker({}); , pasas las 'opciones de
marcador' introduciendo los abrazos. Puedes consultar la documentación de google aquí .
También tenga en cuenta que puede especificar la posición del marcador muy fácilmente con el
parámetro de posición.
Ahora tenemos que modificar la función showPosition .
Puede acceder simplemente a la latencia y la posición de la variable como esta:
var markerPosition={};
markerPosition.lat=position.coords.latitude;
markerPosition.lng=position.coords.longitude;
De esta manera, Google entiende cómo simplemente acceder al valor de lat y lng.
Ahora agregamos para modificar la función showPosition para agregar un marcador en la posición
del usuario.
function showPosition(position) {
var markerPosition={};
markerPosition.lat=position.coords.latitude;
markerPosition.lng=position.coords.longitude;
// Create a marker and place it on the map
var marker = new google.maps.Marker({
position: markerPosition,
https://riptutorial.com/es/home 7
map: map
});
}
• Finalmente, su código debería verse así:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
navigator.geolocation.getCurrentPosition(showPosition);
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
function showPosition(position) {
var markerPosition={};
markerPosition.lat=position.coords.latitude;
markerPosition.lng=position.coords.longitude;
// Create a marker and place it on the map
var marker = new google.maps.Marker({
position: markerPosition,
map: map
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
</body>
</html>
https://riptutorial.com/es/home 8
Lea Primeros pasos con google-maps-api-3 en línea: https://riptutorial.com/es/google-maps-api-
3/topic/3504/primeros-pasos-con-google-maps-api-3
https://riptutorial.com/es/home 9
Capítulo 2: API de JavaScript de Google
Maps v3 - Avanzado
Observaciones
Documentación oficial de Google
• Descripción general de la API de JavaScript de Google Maps
• Ejemplos de código API de JavaScript de Google Maps
• Referencia de API de JavaScript de Google Maps
Sobre los ejemplos en este tema.
• YOUR_API_KEYdebe ser reemplazado por su propia clave de API de aplicación. Puede obtener
una clave de API y configurarla en la Consola de API de Google .
Examples
Mapa de estilo personalizado
<!DOCTYPE html>
<html>
<head>
<title>Styled Maps</title>
<meta charset="utf-8">
<style>
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">
function initialize() {
// Create an array of styles.
var styles = [{
stylers: [{
hue: "#4679BD"
}, {
saturation: 100
}]
}, {
featureType: "poi",
elementType: "labels",
stylers: [{
visibility: "off"
}]
https://riptutorial.com/es/home 10
}, {
featureType: "administrative",
elementType: "labels",
stylers: [{
color: "#"
}]
}, {
featureType: "road.local",
elementType: "geometry",
stylers: [{
visibility: "off"
}]
}, {
featureType: "road",
elementType: "labels",
stylers: [{
visibility: "off"
}]
}, {
featureType: "land",
elementType: "geometry",
stylers: [{
hue: "#e4cc55",
saturation: 100
}]
}, {
featureType: "water",
elementType: "geometry",
stylers: [{
color: "#C5E7FF"
}]
}, {
featureType: "transit.station.airport",
elementType: "geometry",
stylers: [{
hue: "#FF00CA"
}]
}];
// Create a new StyledMapType object, passing it the array of styles, as well as
the name to be displayed on the map type control.
var styledMap = new google.maps.StyledMapType(styles, {
name: "Styled Map"
});
// Create a map object, and include the MapTypeId(s) to add to the map type
control.
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(46.13, 6.14),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'custom_map_style']
}
};
// Create the map.
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('custom_map_style', styledMap);
https://riptutorial.com/es/home 11
map.setMapTypeId('custom_map_style');
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize"
async defer></script>
</body>
</html>
Para crear su propio estilo de mapa, consulte la documentación de Referencia de estilo y / o use
la excelente herramienta Asistente de mapas con estilo .
Demostración de JSFiddle
Lea API de JavaScript de Google Maps v3 - Avanzado en línea: https://riptutorial.com/es/google-
maps-api-3/topic/6781/api-de-javascript-de-google-maps-v3---avanzado
https://riptutorial.com/es/home 12
Creditos
S.
Capítulos Contributors
No
Abhishek, Abrar Jahin, bamnet, Community, Daniel Nugent, Mr.
Primeros pasos con
1 J, MrUpsidown, Praveen Kumar, Rachel Gallen, RamenChef,
google-maps-api-3
S.P.H.I.N.X, Sarah Maddox, Shuvo Habib, Soldeplata Saketos
API de JavaScript de
2 Google Maps v3 - MrUpsidown, RamenChef
Avanzado
https://riptutorial.com/es/home 13