Google Maps Javascript API

  1. Google Maps API
  2. Añadir un marker I
  3. Añadir un marker II
  4. Añadir un marker III
  5. Añadir un marker IV
  6. Añadir un marker V
  7. Geolocalización – detecting support
  8. Geolocalización obteniendo la ubicación del cliente
  9. Ejercicio – integrar geolocalización con la API de google maps

Google Maps API

La API de Google Maps se volvió de pago en mayo del 2018, y aunque los primeros 200€ de uso de la api son gratis (coste por visitas), si tenemos un alto volumen de tráfico es posible que tengamos que pagar. En cualquier caso, será necesario introducir nuestros datos bancarios para usar la API.

Aunque el código fuente de mis ejemplos está comprobado, no estoy pagando por usar la API de Google, y por tanto, los enlaces llevan a un mapa que no funciona.json con direcciónDocumentación oficial

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true">
</script>
 ...

 var myOptions = {
  center:  new google.maps.LatLng(43.5293101753168, -5.6773233792),
  zoom: 18,
  mapTypeId: google.maps.MapTypeId.ROADMAP
 };
 // "mapa" es un div
 var map = new google.maps.Map(document.getElementById("mapa"), myOptions);
 ...

Para hacer la prueba, podremos introducir las coordenadas de Gijón:
Latitude: 43.5293101753168
Longitude: -5.6773233792

Añadir un marker I

Tendremos que añadir el siguiente código al código que ya teníamos

function addMarker(lat, lng){
 var mapMarker = new google.maps.Marker({
  position:new google.maps.LatLng(lat, lng),
  title: "Estás aquí."
 });
 mapMarker.setMap(map);
}

Añadir un marker II

var goldStar = {
 path: 'M 125,5 155,90 245,90 175,145 200,230 125,180 50,230 75,145 5,90 95,90 z',
 fillColor: "yellow",
 fillOpacity: 0.8,
 scale: 0.2,
 strokeColor: "gold",
 strokeWeight: 14
};
var mapMarker = new google.maps.Marker({
 position:latlng,
 title: "Estás aquí.",
 icon:goldStar
}); 

Añadir un marker III

var pinIcon = new google.maps.MarkerImage(
 "Tux.svg",
 null, /* size is determined at runtime */
 null, /* origin is 0,0 */
 null, /* anchor is bottom center of the scaled image */
 new google.maps.Size(42, 68)
);

var mapMarker = new google.maps.Marker({
 position:latlng,
 title: "Estás aquí.",
 icon: pinIcon,
});

Añadir un marker IV con texto

var infoWindowOpts = { content: "bla bla bla..." };
var infoWindow = new google.maps.InfoWindow(infoWindowOpts);

google.maps.event.addListener(mapMarker, 'click', function() {
 infoWindow.open(map,mapMarker); 
});

Añadir un marker V

Recorrer el siguiente array añadiendo una chincheta con el correspondiente texto informativo en cada iteración.

var markerArray = [[43.529492, -5.677978, "texto1"],[43.528921, -5.676688, "texto2"], [43.529522, -5.676489, "texto3"]];

Geolocalización – detecting support

<script>
 var geo;
 
 function getGeoLocation(){
  try{
   if(navigator.geolocation)return navigator.geolocation;
   else return undefined;
  }catch(e){
   return undefined;
  }
 }

 function init(){
  if(geo = getGeoLocation()){
   alert("Geolocalización soportada");
  }else{
   alert("Geolocalización no soportada");
  }
 }
 window.onload = init;
</script>

Geolocalización obteniendo la ubicación del cliente

<script type="text/javascript">
 var geo;

 function showCoords(position){
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  alert("latitude:" + lat);
  alert("longitude: " + lng);
 }

 function getGeoLocation(){
  try{
   if(navigator.geolocation)return navigator.geolocation;
   else return undefined;
  }catch(e){
   return undefined;
  }
 }

 function init(){
  if(geo = getGeoLocation()){
   alert("Geolocalización soportada");
   //El método showCoords tomará el valor de su parámetro position del objeto geo
   geo.getCurrentPosition(showCoords);
  }else{
   alert("Geolocalización no soportada");
  }
 }
 window.onload = init;
</script>

Nota:

Probar los ejercicios utilizando localhost en vez de file:/// y mejor en chrome que en firefox, de lo contrario, funciona de forma intermitente

Ejercicio – integrar geolocalización con la API de google maps