Geolocation

by Lawrence Ross

HTML

<div class="paginaPrinc" id="paginaPrinc">
    <div id="latitud"></div>
    <div id="longitud"></div>
    <div id="map" class="map"></div>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

CSS

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
.map, .paginaPrinc {
    height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

var longitud;
var latitud;

var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
};
  
function success(pos) {
    var crd = pos.coords;
    latitud = crd.latitude
    longitud = crd.longitude   
    document.getElementById("latitud").innerHTML = latitud 
    document.getElementById("longitud").innerHTML = longitud 

    console.log(latitud+","+longitud);
    map = new google.maps.Map(document.getElementById("map"), {
        center: {lat: latitud, lng: longitud},
        zoom: 14
    });
};
  
function error(err) {
    document.getElementById("map").innerHTML = ('ERROR(' + err.code + '): ' + err.message);
};
  


function initMap(){
navigator.geolocation.getCurrentPosition(success, error);
}