Почему я не могу получить координаты от маркера карт Google Maps API? - PullRequest
0 голосов
/ 01 октября 2018

Я хочу получить широту и долготу от маркера в картах Google, когда он перемещается в другую позицию.

Я искал и нашел ответ, но я действительно не знаю, что я делаю неправильно,Я могу получить координаты, когда вы выбираете адрес результата поиска, но когда маркер перетаскивается на новую позицию, координаты не меняются ...

    <script>

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 38.241997, lng: 21.736244},
      zoom: 13
    });
    var card = document.getElementById('pac-card');
    var input = document.getElementById('pac-input');
    var types = document.getElementById('type-selector');
    var strictBounds = document.getElementById('strict-bounds-selector');

    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

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

    // Bind the map's bounds (viewport) property to the autocomplete object,
    // so that the autocomplete requests use the current map bounds for the
    // bounds option in the request.
    autocomplete.bindTo('bounds', map);

    // Set the data fields to return when the user selects a place.
    autocomplete.setFields(
        ['address_components', 'geometry', 'icon', 'name']);

    var infowindow = new google.maps.InfoWindow();
    var infowindowContent = document.getElementById('infowindow-content');
    infowindow.setContent(infowindowContent);
    var marker = new google.maps.Marker({
      map: map,
  draggable: true,
      anchorPoint: new google.maps.Point(0, -29)
    });

google.maps.event.addListener(marker, 'dragend', function() {
document.getElementById('Lat').value = marker.getPosition().lat();
    document.getElementById('Lng').value = marker.getPosition().lng();
});

    autocomplete.addListener('place_changed', function() {
      infowindow.close();
      marker.setVisible(true);
      var place = autocomplete.getPlace();
  document.getElementById('Lat').value = place.geometry.location.lat();
      document.getElementById('Lng').value = place.geometry.location.lng();

      if (!place.geometry) {
        window.alert("No details available for input: '" + place.name + "'");
        return;
      }

      // If the place has a geometry, then present it on a map.
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }
      marker.setPosition(place.geometry.location);
      marker.setVisible(true);


      var address = '';
      if (place.address_components) {
        address = [
          (place.address_components[0] && place.address_components[0].short_name || ''),
          (place.address_components[1] && place.address_components[1].short_name || ''),
          (place.address_components[2] && place.address_components[2].short_name || '')
        ].join(' ');
      }

      infowindowContent.children['place-icon'].src = place.icon;
      infowindowContent.children['place-name'].textContent = place.name;
      infowindowContent.children['place-address'].textContent = address;
      infowindow.open(map, marker);
    });


    document.getElementById('use-strict-bounds')
        .addEventListener('click', function() {
          console.log('Checkbox clicked! New state=' + this.checked);
          autocomplete.setOptions({strictBounds: this.checked});
        });
  }



</script>

Затем я назначаю координаты в двух входах формы(Lat и Lng), но я не публикую этот код, потому что уверен, что проблем нет.Как я уже говорил вам с place_changed, он отлично работает.Только с маркером перетаскивания ничего не происходит.Спасибо.

1 Ответ

0 голосов
/ 15 октября 2018

Используйте это, чтобы получить координаты

var item_lat = place.geometry.location.lat();
      var item_lng = place.geometry.location.lng();
      var getloc = place.name;

      alert("Lat "+item_lat+ "___Lng "+item_lng + " Location "+getloc);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...