ccc

Mostrando entradas con la etiqueta Google Maps. Mostrar todas las entradas
Mostrando entradas con la etiqueta Google Maps. Mostrar todas las entradas

Google Maps: Generar varios iconos dentro del maps

<!DOCTYPE html>
<html>
<body>
<h1>Un poco de HTML encima</h1>
<div id="mapaLSG" style="width:100%;height:600px;"></div>
<script>
    function initMap() {
        const myLatLng = { lat: 39.86364, lng: -3.6153887 }; // mapa centrado de España
        var mapProp = {
            zoom:6.55,
            minZoom: 6.55, // para q no se haga grande cuando se click
            center: myLatLng
        };
        var map = new google.maps.Map(document.getElementById("mapaLSG"),mapProp);
        icon = {
              url: 'http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png',
              scaledSize: new google.maps.Size(35, 35)
        };

        // recorrer el array asociativo
        arrAux1.forEach(function(e) {
                var marker = new google.maps.Marker({
                    position: { lat: e["lat"], lng: e["lng"] },
                    map: map,
                    icon: icon
                });
                marker.addListener('click', function() {
                    new google.maps.InfoWindow({
                        content: e['content']
                    }).open(map, marker);
                });
        });
    }

    var arrAux1 = [];
    arrAux1.push({ lat: 40.965, lng: -5.66305, content: '<span>lo que sea 1</span>' });
    arrAux1.push({ lat: 39.4762, lng: -6.37076, content: '<span>lo que sea 2</span>' });
    arrAux1.push({ lat: 40.4163, lng: -3.6934, content: '<span>lo que sea 3</span>' });
</script>
<h1>Aqui debajo mas HTML</h1>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaxxxx&callback=initMap&libraries=&v=weekly"></script>
</body>
</html>

Google Maps: Añadir circulos de diferentes tamaño dependiendo del número de habitantes a una zona

<!DOCTYPE html>
<html>
<body>
<div id="mapaLSG" style="width:100%;height:400px;"></div>
<script>

var citymap = {
  casaLSG: {
    center: {lat: 40.4763202, lng: -3.6615473},
    population: 6
},
  casaAR: {
    center: {lat: 40.4771, lng: -3.6457},
    population: 3
},
  casaAG: {
    center: {lat: 40.4698, lng: -3.6386},
    population: 4
}
};

function initMap() {
  var map = new google.maps.Map(document.getElementById('mapaLSG'), {
    zoom: 14,
    center: {lat: 40.4808253, lng: -3.6440271},
    xmapTypeId: 'terrain'
  });

  for (var city in citymap) {
    var cityCircle = new google.maps.Circle({
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      map: map,
      center: citymap[city].center,
      radius: Math.sqrt(citymap[city].population) * 100
    });
  }
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXXx8JJmUPajgFsJDavU6JD8nbyEkT8i3o&callback=initMap"></script>
</body>
</html>

Google Maps: poner marker y calcular ruta entre dos puntos

Lo más básico, poner un market en un mapa que ocupa toda la web:
<!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>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 40.4410744, lng: -3.6187568},
          zoom: 15
        });
var marker = new google.maps.Marker({
position: {lat: 40.446361599999996, lng: -3.6118527999999994},
map: map,
title: 'Mi Empresa'
});
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXXjgFsJDavU6JD8nbyEkT8i3o&callback=initMap" async defer></script>
  </body>
</html>

Que en vez de ocupar toda la web se cargue en un div concreto:
<!DOCTYPE html>
<html>
<body>
<h1>Un poco de HTML encima</h1>
<div id="mapaLSG" style="width:100%;height:400px;"></div>
<script>
function initMap() {
var mapProp = {
  center:new google.maps.LatLng(40.4410744,-3.6187568),
  zoom:13,
};
var map = new google.maps.Map(document.getElementById("mapaLSG"),mapProp);

var marker = new google.maps.Marker({
position: {lat: 40.446361599999996, lng: -3.6118527999999994},
map: map,
title: 'Mi Empresa'
});
}
</script>
<h1>Aqui debajo mas HTML</h1>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXX8JJmUPajgFsJDavU6JD8nbyEkT8i3o&callback=initMap"></script>
</body>
</html>

Que permita meter una dirección y calcular la ruta desde ese punto hasta nuestro market (antes asegúrate que en https://console.developers.google.com/ tengas habilitadas las API de Places API, Maps Javascript API, Geocoding API y Directions API):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaXXXXzKBgw9hboDblFlodk3aA3J_QXPs0aPs"></script>
</head>
<body>
<h1>Un poco de HTML encima</h1>
<div id="mapaLSG" style="width:100%;height:400px;"></div>
<script>
var map;
var gdir;
var geocoder = null;
var addressMarker;
var marker;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay;
// *********************************
function initMap() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapProp = {
  center:new google.maps.LatLng(40.4410744,-3.6187568),
  zoom:13,
};
var map = new google.maps.Map(document.getElementById("mapaLSG"),mapProp);

var marker = new google.maps.Marker({
position: {lat: 40.446361599999996, lng: -3.6118527999999994},
map: map,
title: 'Mi Empresa'
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}

// ****************************
function calcRoute(irDe, irA) {
  var start = irDe;
  var end = irA;
  var request = {
    origin:start,
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
  /*marker.setMap(null);*/
  $('#directionsPanelContainer').css('display', 'block');
}

// *********************************
function CalcRutaVerificarTecla(e, f){
  tecla = (document.all) ? e.keyCode : e.which;
  if((tecla == 13)){
    //abrir_ruta(f);
    setDirections(document.forms['form-mapa'].from.value, document.forms['form-mapa'].to.value, document.forms['form-mapa'].locale.value);
    return false;
  }
}
</script>

<form action="" id="form-mapa" action="" method="post" class="col-md-12">
<input type="hidden" id="toAddress" name="to" value="Calle de Alcalá, 540, 28037 Madrid" />
<input type="hidden" id="locale" name="locale" value="es"/>
<input type="hidden" id="locale" name="calcular_ruta" value="1"/>
<input type="hidden" name="ubicacion" value="xxxx" />
<p class="section-title color-navy text-center"><strong> Calcula tu ruta,<br>como llegar desde... </strong> </p>
<div class="form-group">
  <input class="form-control" style="height:42px;" id="fromAddress" name="from" type="text" placeholder="¿Cuál es tu dirección?"
    onkeypress="javascript:return CalcRutaVerificarTecla(event, document.forms['form-mapa'])" value="" required>
</div><!--form-group-->
<div class="form-group">
<button type="button" class="btn btn-default btn-block"
onclick="javascript:calcRoute(document.forms['form-mapa'].from.value, document.forms['form-mapa'].to.value, document.forms['form-mapa'].locale.value);"
value="Calcular ruta">CALCULAR RUTA</button>
</div><!--form-group-->
</form>

<h1>Aqui debajo mas HTML</h1>

<script>
$(function() {
initMap();
});
</script>
</body>
</html>

Google Maps: Buscar cualquier dirección con un autocomplete y que te proporcione el ID y toda la demás información

<h1>Obtener el ID de la empresa</h1>
<input id="autocomplete_search" style="width: 50%" name="autocomplete_search" type="text" class="form-control" placeholder="Search" />
<p>ID: <span id="id_company">----------------</span></p>

<script async src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXX978RZrgxsHoSrfyXPtDjzNHxM3ntdU0&amp;libraries=places"></script>

<script>
    google.maps.event.addDomListener(window, 'load', initialize);
    function initialize() {
        var input = document.getElementById('autocomplete_search');
        var autocomplete = new google.maps.places.Autocomplete(input);
        autocomplete.addListener('place_changed', function () {
            var place = autocomplete.getPlace();
            // place variable will have all the information you are looking for.
            //$('#lat').val(place.geometry['location'].lat());
            //$('#long').val(place.geometry['location'].lng());
console.log(place);
            $('#id_company').html(place.reference);
        });
    }
</script>

Especial agradecimiento a Carlos Sierra García

Google Maps: cargar el maps a partir de una dirección que escribamos (por ejemplo: Alcalá 122, Madrid)

<!DOCTYPE html>
<html>
  <head>
    <title>Geocoding Service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <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;
      }
      #floating-panel {
        position: absolute;
        top: 10px;
        left: 25%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }
    </style>
  </head>
  <body>
    <div id="floating-panel">
      <input id="address" type="textbox" value="Alcalá 122, Madrid">
      <input id="submit" type="button" value="Buscar calle">
    </div>
    <div id="map"></div>
    <script>
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 18,
          center: {lat:40.440590, lng: -3.618640}
        });

        var geocoder = new google.maps.Geocoder();
address = "Cronos 63, Madrid";
// geocodeAddress(geocoder, map, address);

        document.getElementById('submit').addEventListener('click', function() {
          geocodeAddress(geocoder, map);
        });
      }

      function geocodeAddress(geocoder, resultsMap) {
        var address = document.getElementById('address').value;
        geocoder.geocode({'address': address}, function(results, status) {
          if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
              map: resultsMap,
              position: results[0].geometry.location
            });
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXXx8JJmUPajgFsJDavU6JD8nbyEkT8i3o&callback=initMap" async defer></script>
    </script>
  </body>
</html>

Google Maps: Añadir market a partir de coordenadas

<!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>
    <script>

      var map;
      function initMap() {
  var myLatLng = {lat: <?=$_GET["lat"];;?>, lng: <?=$_GET["long"];?>};
 
        map = new google.maps.Map(document.getElementById('map'), {
          center: myLatLng,
          zoom: 18
        });

var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hola'
});
      }
    </script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBxx8JJmUPajgFsJDavU6JD8nbyXXXXi3o&callback=initMap" async defer></script>
</body>
</html>

Google Maps: Geocoder (dibujar maps a partir de una dirección exacta)

Primero en https://console.developers.google.com habilita (si no están ya habilitado de antes) las siguientes API:

Google Street View Image API
Google Places API Web Service
Google Maps Geocoding API
Google Maps Directions API
Google Maps Distance Matrix API
Google Maps Geolocation API

Una vez habilitado obtener una Api Key (aconsejable restringirla para un dominio concreto)
Para crear una Api Key ir a Credential -> Create Credentials -> Api Key
El código:
<!DOCTYPE html>
<html>
  <head>
    <title>Geocoding Service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <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;
      }
      #floating-panel {
        position: absolute;
        top: 10px;
        left: 25%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }
    </style>
  </head>
  <body>
    <div id="floating-panel">
      <input id="address" type="textbox" value="Sydney, NSW">
      <input id="submit" type="button" value="Geocode">
    </div>
    <div id="map"></div>
    <script>
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: {lat:40.440590, lng: -3.618640}
        });
        var geocoder = new google.maps.Geocoder();

        document.getElementById('submit').addEventListener('click', function() {
          geocodeAddress(geocoder, map);
        });
      }

      function geocodeAddress(geocoder, resultsMap) {
        var address = document.getElementById('address').value;
        geocoder.geocode({'address': address}, function(results, status) {
          if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
              map: resultsMap,
              position: results[0].geometry.location
            });
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });
      }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAWW2n9NCWLXG3qnjMJMXXXQMd-0sqGsNk&callback=initMap">
    </script>
  </body>
</html>

Google Maps: Poner icono localizador a partir de la IP del usuario

Lógicamente el usuario tiene que dar permiso para en su navegador para poder obtener su IP:
<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <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>
      // Dibujarlo a partir de mi IP
      var map, infoWindow;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 16
        });
        infoWindow = new google.maps.InfoWindow;

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);

var marker = new google.maps.Marker({
position: {lat: position.coords.latitude, lng:position.coords.longitude },
map: map,
title: 'Mi Empresa'
  });


          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
 
 
 
 
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXXx8JJmUPajgFsJDavU6JD8nbyEkT8i3o&callback=initMap"></script>
  </body>
</html>

Google Maps: Personalizar mapa con tus propios estilos

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();

  var mapDiv = document.getElementById('map_canvas');
  var map = new google.maps.Map(mapDiv, {
    center: center,
    zoom: 15,
    draggable: false,
    scrollwheel: false,
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var image = "https://www.midominio.com/imagenes/icono-paises.png";
  var marker = new google.maps.Marker({
      position: center,
      map: map,
      icon: image
  });


  var styles = [
  {
    "featureType": "landscape",
    "stylers": [
      {
        "hue": "#FF0300"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 4
      },
      {
        "gamma": 1
      }
    ]
  },
 
  {
    "featureType": "road.highway",
    "stylers": [
      {
        "hue": "#FF0300"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 21.39999999999999
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "road.arterial",
    "stylers": [
      {
        "hue": "#FF0300"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 11.200000000000017
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "road.local",
    "stylers": [
      {
        "hue": "#FF0300"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 12.000000000000014
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "water",
    "stylers": [
      {
        "hue": "#FF0300"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 12.000000000000014
      },
      {
        "gamma": 1
      }
    ]
  },

  {
    "featureType": "poi",
    "stylers": [
      {
        "hue": "#FF0300"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 12.000000000000014
      },
      {
        "gamma": 1
      }
    ]
  },
  {
        featureType: "poi",
        elementType: "labels",
        stylers: [
              { visibility: "off" }
        ]
    }

 
];


map.setOptions({styles: styles});


  marker = new google.maps.Marker({
      position: center,
      map: map
  });

  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById("directionsPanel"));

}

Google Maps: Ocultar los iconos de los museos, parques, etc

Cuando inicializas en maps:

var styles = [
  {
        featureType: "poi",
        elementType: "labels",
        stylers: [
              { visibility: "off" }
        ]
    }
];

map.setOptions({styles: styles});

Google Maps: Poner varias localizaciones, personalizar icono y mostrar texto al hacer click sobre el marker

<!DOCTYPE html>
<html>
  <head>
    <title>Varios Marker en un mapa</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
var infoWindow = new google.maps.InfoWindow();
 
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 40.440819, lng: -3.618624},
          zoom: 17
        });

function createMarker(options, html) { // ojo, una función dentro de otra función
var marker = new google.maps.Marker(options);
if (html) {
google.maps.event.addListener(marker, "click", function () {
infoWindow.setContent('<textarea id="infoarea"></textarea>');
infoWindow.setContent(html);
infoWindow.open(options.map, this);
});
}
return marker;
}
marker = createMarker({
            position: new google.maps.LatLng(40.440819, -3.618624),
            map: map,
            icon: 'images/icono.jpg',
        }, "<h4>Información sobre Cronos 63</h4>");

marker = createMarker({
            position: new google.maps.LatLng(40.443652, -3.616994),
            map: map,
            icon: 'images/icono.jpg',
        }, "<h4>Información sobre Metro Torre Arias</h4>");
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXXj_62-Lv2lfaA4IIekpX_KWGNj-5nJy0&callback=initMap"
    async defer></script>
  </body>
</html>

Maps: Obtener datos geográficos a partir de una IP

Obtener datos geográficos a partir de una IP:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.ipdata.co"); // manda nuestra IP
// Si queremos pasarle nosotros una IP en concreta sería:
curl_setopt($ch, CURLOPT_URL, "https://api.ipdata.co/213.229.183.42");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Accept: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);

Te proporciona la ciudad, región, país, continente, latitud, longitud, bandera del país, etc

Si quisieramos obtener el nombre de la calle debe hacerse con este otro código a partir de la longitud y latitud dada:

Debes crearte en la console de Google una API Key y habilitar la API de Google Maps

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXX_62-Lv2lfaA4IIekpX_KWGNj-5nJy0&callback=initMap">
    </script>

<div id="datos"></div>

<script>
function initMap() {
var geocoder = new google.maps.Geocoder;
coordenadas = "40.4086,-3.6922";
var latlngStr = coordenadas.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};

geocoder.geocode({'location': latlng}, function(results, status) {
  if (status === 'OK') {
  // console.log(results);
  html = "";
 
  for (var i=0; i<results.length-1; i++) {
  html += "<br>Calle: "+results[i]["address_components"][0]["long_name"];
  html += "<br>Ciudad: "+results[i]["address_components"][1]["long_name"];
  html += "<br>Provincia: "+results[i]["address_components"][2]["long_name"];
  html += "<br>Comunidad: "+results[0]["address_components"][3]["long_name"];
  html += "<br>País: "+results[0]["address_components"][4]["long_name"];
  html += "<br>CP: "+results[0]["address_components"][5]["long_name"];
  html +="<hr>";
  // html += "<br>Cinco: "+results[i]["address_components"][4]["long_name"];

 
  }
  $("#datos").html(html);
 
} else {
  window.alert('No hay resultados');
}
});
}
</script>

Google Maps: Geolocalización

Crear un Api Key para Geolocalización:

https://developers.google.com/maps/documentation/javascript/get-api-key?hl=es

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <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>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.

      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 6
        });
        var infoWindow = new google.maps.InfoWindow({map: map});

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
      }
    </script>

    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaXXXXj_62-Lv2lfaA4IIekpX_KWGNj-5nJy0&callback=initMap">
    </script>

  </body>
</html>

Más información en: https://developers.google.com/maps/documentation/javascript/geolocation?hl=es

Google Maps: Sacar el listado de todo lo que esté en un radio menor a una distancia que se le pase

$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($direccion.' Espana')."&sensor=false";
$detalles = file_get_contents($url);
$resultado = json_decode($detalles,true);

$latitud = $resultado['results'][0]['geometry']['location']['lat'];
$longitud = $resultado['results'][0]['geometry']['location']['lng'];

$db->query("select * from mi_tabla");

while ($db->next_record()) {
    $latitudtal = $db->Record['latitud'];
    $longitudtal = $db->Record['longitud'];
    $grados = rad2deg(acos((sin(deg2rad(floatval($latitud)))*sin(deg2rad(floatval($latitudtal)))) + (cos(deg2rad(floatval($latitud)))*cos(deg2rad(floatval($latitudtal)))*cos(deg2rad(floatval($longitud)-(floatval($longitudtal)))))));
    $kms = $grados * 111.302; // lo convierte a kms

    if (kms <= $distancia) {
      ...
    }
}

Google Maps: Poner varias localizaciones

<script src='http://maps.google.com/maps/api/js?sensor=false&libraries=geometry&v=3.7'></script>
<script src='js/maplace.js'></script>

<div id='gmap' style='width:894px;height:450px;margin:auto;'></div>                       
  <script>
  $(function() {
       new Maplace({
                locations: [{lat:40.413825, lon:-3.707045}, {lat:39.4752012, lon:-6.371665900000039}, {lat:41.6789391, lon:-0.9675417999999354}, {lat:37.4125937, lon:-5.926850699999932}, {lat:42.2934056, lon:-5.520870000000059}],
                controls_on_map: false
        }).Load();
  });
  </script>