JSFiddle - React, Tailwind, and code Playground
by Hugo Lizama
HTML
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&signed_in=true"></script>
<input id="pac-input" class="controls" type="text" placeholder="Buscar dirección">
<input id="marcador_eliminar" type="button" value="Eliminar marcador" class="btn btn-default">
<div id="map"></div>
<div>
LAT <input id="lat" type="text" /> <br/>
LON <input id="lng" type="text" /> <br/>
</div>
CSS
#map {
width: 100%;
height: 400px;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
/*font-family: Roboto;*/
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
/*font-family: Roboto;*/
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
/*font-family: Roboto;*/
font-size: 13px;
font-weight: 300;
}
#target {
width: 345px;
}
#marcador_eliminar{
position: absolute;
z-index: 2;
left: 430px;
top: 15px;
font-size: 12px;
padding: 7px 10px;
}
JavaScript
$(document).ready(function(){
/*******INICIA MAPA *********/
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(13.802994, -88.9053364),
//center: new google.maps.LatLng(13.939648549337509, -89.02305901050568), //prueba
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
//inicializamos marcadores
var markers = [];
//funcion para iniciar buscador de lugares
function initAutocomplete() {
// crea el buscador
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// enlaza la busqueda con el mapa
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
// listener de eventos en el buscador
// se dispara al escribir y seleccionar texto predictivo
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
//limpia los marcadores
cleanAllMarkers();
// para cada lugar recupera la locacion
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
//latitud y longitud a cajas de texto
$('#lat').val(place.geometry.location.lat());
$('#lng').val(place.geometry.location.lng());
// crea el marcador para cada lugar.
markers.push(new google.maps.Marker({
map: map,
position: place.geometry.location,
animation: google.maps.Animation.DROP
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
//mueve el foco hasta el lugar buscado
map.fitBounds(bounds);
...