
En este post veremos como obtener un la coordenadas latitud y longitud a partir de una dirección dada, en el video 13. Sistema para reserva de hoteles en ASPNET Core - Agregar Hoteles: HTML, js, jquery, ajax y c#, me pidieron que explicara cómo implementar esta funcionalidad.
Vamos a obtener unas coordenadas de Google maps a partir de una dirección en formato texto, con javascript.
Si desea encontrar obtener la latitud y longitud de Google Maps con jquery y javascript. Entonces estas en el lugar correcto. Este tutorial explica cómo obtener la latitud y la longitud de la dirección utilizando las API de Google Map con jquery y javascript.
Obtener la Latitud y Longitud de una dirección con jQuery Javascript
- Obtenga una clave de API de Google Maps
- Crear un archivo llamado index.html
- Llame a la API de Google con dirección para lat y long
1. Obtén una clave de API de Google Maps
Necesitarás una clave API antes de poder realizar llamadas al servicio de Geocodificación de Google Maps.
Primero, deberás visitar: https://cloud.google.com/maps-platform/?_ga=2.27293823.277869946.1577356888-568469380.1576660626#get-started y obtener la clave API.
Para obtener una clave API sigue los siguientes pasos:
- Visite la consola de Google Cloud Platform.
- Haz clic en el menú desplegable del proyecto y seleccione o crea el proyecto para el que desea agregar una clave API.
- Hz clic en el botón de menú y seleccione API y servicios > Credenciales .
- En la página Credenciales, haz clic en Crear credenciales> Clave API.
- El cuadro de diálogo de la clave API creada, se muestra tu clave API recién creada.
- Haz clic en Cerrar.
- La nueva clave API aparece en la página Credenciales en Claves API.
- (Recuerde restringir la clave API antes de usarla en producción).
2. Crear el archivo index.html
Siguiente paso, crea un archivo html simple y pega el siguiente código en tu archivo:
<div class="container d-flex w-100 h-100 p-3 mx-auto flex-column">
<header class="masthead mb-auto">
<div class="inner">
<h3 class="masthead-brand">Estrada Web Group</h3>
<div class="nav nav-masthead justify-content-center">
<div class="row">
<div class="col-md-4">
<input type="text" id="txtDireccion" class="form-control" placeholder="direccion">
</div>
<div class="col-md-4">
<input type="text" id="txtCiudad" class="form-control" placeholder="ciudad">
</div>
<div class="col-md-4">
<input type="text" id="txtEstado" class="form-control" placeholder="estado">
</div>
</div>
</div>
</div>
</header>
<main role="main" class="inner cover">
<div class="row">
<div class="col-md-4">
<input type="text" id="txtLat" class="form-control" placeholder="latitude">
</div>
<div class="col-md-4">
<input type="text" id="txtLng" class="form-control" placeholder="longitud">
</div>
</div>
<div id="map_canvas" style="height:350px">
</div>
</main>
<footer class="mastfoot mt-auto">
<div class="inner">
<p><a href="https://estradawebgroup.com">Estrada Web Group</a>.</p>
</div>
</footer>
</div>
3. Llama la API de Google con dirección para obtener la latitud y longitud
En el paso final, en este paso, crearemos un código JavaScript para llamar a la API de Google Geocode con la dirección capturada por el usuario para obtener la latitud y la longitud de la dirección.
Nota: - No olvides poner tu clave de API de Google Map aquí:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=Klave API Key"></script>
<script>
var vMarker
var map
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
center: new google.maps.LatLng(19.4326296, -99.1331785),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
vMarker = new google.maps.Marker({
position: new google.maps.LatLng(19.4326296, -99.1331785),
draggable: true
});
google.maps.event.addListener(vMarker, 'dragend', function (evt) {
$("#txtLat").val(evt.latLng.lat().toFixed(6));
$("#txtLng").val(evt.latLng.lng().toFixed(6));
map.panTo(evt.latLng);
});
map.setCenter(vMarker.position);
vMarker.setMap(map);
$("#txtCiudad, #txtEstado, #txtDireccion").change(function () {
movePin();
});
function movePin() {
var geocoder = new google.maps.Geocoder();
var textSelectM = $("#txtCiudad").text();
var textSelectE = $("#txtEstado").val();
var inputAddress = $("#txtDireccion").val() + ' ' + textSelectM + ' ' + textSelectE;
geocoder.geocode({
"address": inputAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
vMarker.setPosition(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
map.panTo(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
$("#txtLat").val(results[0].geometry.location.lat());
$("#txtLng").val(results[0].geometry.location.lng());
}
});
}
</script>
Código fuente completo:
Puedes ver el código fuente completo para obtener la latitud y longitud de la dirección utilizando la API de geocodificación de google.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<style>
/*
* Globals
*/
/* Links */
a,
a:focus,
a:hover {
color: #fff;
}
/* Custom default button */
.btn-secondary,
.btn-secondary:hover,
.btn-secondary:focus {
color: #333;
text-shadow: none; /* Prevent inheritance from `body` */
background-color: #fff;
border: .05rem solid #fff;
}
/*
* Base structure
*/
html,
body {
height: 100%;
background-color: #333;
}
body {
display: -ms-flexbox;
display: flex;
color: #fff;
text-shadow: 0 .05rem .1rem rgba(0, 0, 0, .5);
box-shadow: inset 0 0 5rem rgba(0, 0, 0, .5);
}
.cover-container {
max-width: 42em;
}
/*
* Header
*/
.masthead {
margin-bottom: 2rem;
}
.masthead-brand {
margin-bottom: 0;
}
.nav-masthead .nav-link {
padding: .25rem 0;
font-weight: 700;
color: rgba(255, 255, 255, .5);
background-color: transparent;
border-bottom: .25rem solid transparent;
}
.nav-masthead .nav-link:hover,
.nav-masthead .nav-link:focus {
border-bottom-color: rgba(255, 255, 255, .25);
}
.nav-masthead .nav-link + .nav-link {
margin-left: 1rem;
}
.nav-masthead .active {
color: #fff;
border-bottom-color: #fff;
}
@media (min-width: 48em) {
.masthead-brand {
float: left;
}
.nav-masthead {
float: right;
}
}
/*
* Cover
*/
.cover {
padding: 0 1.5rem;
}
.cover .btn-lg {
padding: .75rem 1.25rem;
font-weight: 700;
}
/*
* Footer
*/
.mastfoot {
color: rgba(255, 255, 255, .5);
}
</style>
</head>
<body>
<div class="container d-flex w-100 h-100 p-3 mx-auto flex-column">
<header class="masthead mb-auto">
<div class="inner">
<h3 class="masthead-brand">Estrada Web Group</h3>
<div class="nav nav-masthead justify-content-center">
<div class="row">
<div class="col-md-4">
<input type="text" id="txtDireccion" class="form-control" placeholder="direccion">
</div>
<div class="col-md-4">
<input type="text" id="txtCiudad" class="form-control" placeholder="ciudad">
</div>
<div class="col-md-4">
<input type="text" id="txtEstado" class="form-control" placeholder="estado">
</div>
</div>
</div>
</div>
</header>
<main role="main" class="inner cover">
<div class="row">
<div class="col-md-4">
<input type="text" id="txtLat" class="form-control" placeholder="latitude">
</div>
<div class="col-md-4">
<input type="text" id="txtLng" class="form-control" placeholder="longitud">
</div>
</div>
<div id="map_canvas" style="height:350px">
</div>
</main>
<footer class="mastfoot mt-auto">
<div class="inner">
<p><a href="https://estradawebgroup.com">Estrada Web Group</a>.</p>
</div>
</footer>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=Key API"></script>
<script>
var vMarker
var map
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
center: new google.maps.LatLng(19.4326296, -99.1331785),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
vMarker = new google.maps.Marker({
position: new google.maps.LatLng(19.4326296, -99.1331785),
draggable: true
});
google.maps.event.addListener(vMarker, 'dragend', function (evt) {
$("#txtLat").val(evt.latLng.lat().toFixed(6));
$("#txtLng").val(evt.latLng.lng().toFixed(6));
map.panTo(evt.latLng);
});
map.setCenter(vMarker.position);
vMarker.setMap(map);
$("#txtCiudad, #txtEstado, #txtDireccion").change(function () {
movePin();
});
function movePin() {
var geocoder = new google.maps.Geocoder();
var textSelectM = $("#txtCiudad").text();
var textSelectE = $("#txtEstado").val();
var inputAddress = $("#txtDireccion").val() + ' ' + textSelectM + ' ' + textSelectE;
geocoder.geocode({
"address": inputAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
vMarker.setPosition(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
map.panTo(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
$("#txtLat").val(results[0].geometry.location.lat());
$("#txtLng").val(results[0].geometry.location.lng());
}
});
}
</script>
</body>
</html>