0

Les comparto el código html y JS que tengo ya me hace la búsqueda de la dirección pero quiero que cuando me dirija a la dirección se pueda mover el marker y que al mover el marker me obtenga la dirección, latitud y longitud y me lo regrese en los inputs

<input id="pac-input" class="controls form-control" name="address" value="{{$data->address}}" type="text" placeholder="Enter a location">
<br>
<div class="row">
<div class="form-group col-md-6"><input type="hidden" name="lat" id="lat" class="form-control" required placeholder="Latitude" value="{{ $data->lat }}"></div>
<div class="form-group col-md-6"><input type="hidden" name="lng" id="lng" class="form-control" required placeholder="Longitude" value="{{ $data->lng }}"></div>
</div>

<div id="map" style="width: 100%;height: 400px;"></div>
<div id="infowindow-content">
  <span id="place-name"  class="title"></span>
  <span id="place-id"></span><br>
  <span id="place-address"></span>
</div>

luego creo el script para visualizar el mapa con la api de google maps la cual me retorna la ciudad con el Marker en medio del mapa y tambien me retorna la latitud y la longitud.

<script>
  function initMap() {
    var map = new google.maps.Map(
        document.getElementById('map'),
        {center: {lat: 31.326015, lng: 75.576180}, zoom: 13});


    var input = document.getElementById('pac-input');

    var autocomplete = new google.maps.places.Autocomplete(input);

    autocomplete.bindTo('bounds', map);

    // Specify just the place data fields that you need.
    autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address']);

    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var infowindow = new google.maps.InfoWindow();
    var infowindowContent = document.getElementById('infowindow-content');
    infowindow.setContent(infowindowContent);

    var geocoder = new google.maps.Geocoder;

    var marker = new google.maps.Marker({map: map,
     });
    marker.addListener('click', function() {
      infowindow.open(map, marker);
    });

    autocomplete.addListener('place_changed', function() {
      infowindow.close();
      var place = autocomplete.getPlace();

      if (!place.place_id) {
        return;
      }
      geocoder.geocode({'placeId': place.place_id}, function(results, status) {
        if (status !== 'OK') {
          window.alert('Geocoder failed due to: ' + status);
          return;
        }

        map.setZoom(11);
        map.setCenter(results[0].geometry.location);

        // Set the position of the marker using the place ID and location.
        marker.setPlace(
            {placeId: place.place_id, location: results[0].geometry.location});

        marker.setVisible(true);

        infowindowContent.children['place-name'].textContent = place.name;
        infowindowContent.children['place-id'].textContent = place.place_id;
        infowindowContent.children['place-address'].textContent = results[0].formatted_address;

        document.getElementById('lat').value = results[0].geometry.location.lat();
        document.getElementById('lng').value = results[0].geometry.location.lng();
        infowindow.open(map, marker);
      });
    });
  }
</script>

como puedo hacer para que al mover el marker obtener automaticamente la longitud, latitud y la dirección y me los regrese en los inputs de arriba?

Gracias de antemano saludos cracks!

2
  • Lee Cómo preguntar, edita y agrega como texto el código, idealmente explica tu código y en qué parte ocupas ayuda
    – user128299
    el 14 oct. 2020 a las 18:06
  • gracias ya edite la pregunta saludos. el 14 oct. 2020 a las 18:21

1 respuesta 1

0

Dentro de tu script, podrías agregar este evento:

google.maps.event.addListener(marker, 'dragend', function(marker){
   var latLng = marker.latLng; 
   currentLatitude = latLng.lat();
   currentLongitude = latLng.lng();
  
   // Colocar currentLatitude y currentLongitude en tus inputs

}); 

Para que este evento funcione, tu marker debe tener la propiedad draggable:true

var marker = new google.maps.Marker({ map: map, draggable: true });
3
  • pero cuando le pongo la propiedad draggable:true solo lo hace cuando carga el mapa pero cuando le paso la direccion se queda fijo y no se mueve el marker :/ el 15 oct. 2020 a las 3:37
  • tengo una duda ya logre hacer que me retorne la longitud y la latitud pero como puedo obtener la dirección hay algún método así como el .latLng para obtener el address? el 15 oct. 2020 a las 23:25
  • Genial! 😁 , para obtener el address te recomiendo que utilices Geocoder, y con las coordenadas de tu marker podrás hacer una búsqueda y obtener varios datos como la dirección formateada. Aquí hay un ejemplo de Geocoder buscando por location(lat & lng)
    – Angy QR
    el 15 oct. 2020 a las 23:41

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.