<!DOCTYPE html>
<html>
<head>
<title>Location</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap&libraries=&v=weekly"
defer
></script>
<style>
#map {
height: 500px;
width: 800px;
border-radius: 15px;
margin: 100px auto;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
align-items: center;
justify-content: center;
}
.custom-map-control-button {
appearance: button;
background-color: #fff;
border: 0;
border-radius: 2px;
box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);
cursor: pointer;
margin: 10px;
padding: 0 0.5em;
height: 40px;
font: 400 18px Roboto, Arial, sans-serif;
overflow: hidden;
}
.custom-map-control-button:hover {
background: #ebebeb;
}
</style>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<center>
<h2>Coordenadas</h2>
<h3>Latitude</h3>
<p id="textLatitude">Latitude</p>
<h3>Longitude</h3>
<p id="textLongitude">Longitude</p>
</center>
<script>
let map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 6.249216, lng: -75.588066 },
zoom: 6,
});
infoWindow = new google.maps.InfoWindow();
const locationButton = document.createElement("button");
locationButton.textContent = "Localizarme";
locationButton.classList.add("custom-map-control-button");
map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
locationButton.addEventListener("click", () => {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
document.getElementById("textLatitude").innerHTML = pos.lat;
document.getElementById("textLongitude").innerHTML = pos.lng;
infoWindow.setPosition(pos);
map.setCenter(pos);
map.setZoom(16);
// The marker, positioned at located
const marker = new google.maps.Marker({
position: pos,
map: map,
});
},
() => {
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>
</body>
</html>
API Key
https://console.developers.google.com/apis/credentials