Lat, Lng doesn't update when I drag marker

后端 未结 2 1296
悲&欢浪女
悲&欢浪女 2020-12-22 11:48

Actually, I have a map with a dragable marker. That works fine, but I can\'t update lat and lng of the dragged marker. I\'ve tried it with a few different Event listeners, b

2条回答
  •  时光说笑
    2020-12-22 12:27

    You need to get the position of the marker and update the form fields when the marker is dragged:

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

    code snippet:

    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 7,
        center: {
          lat: 47.532446,
          lng: 14.623283
        }
      });
      var geocoder = new google.maps.Geocoder();
    
      document.getElementById('geolocate').addEventListener('click', function() {
        geocodeAddress(geocoder, map);
      });
    }
    
    function geocodeAddress(geocoder, resultsMap) {
      var address = document.getElementById('street').value + ' ' +
        document.getElementById('zip').value + ' ' +
        document.getElementById('city').value;
    
      geocoder.geocode({
        'address': address
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          resultsMap.setCenter(results[0].geometry.location);
    
          document.getElementById('lat').value = results[0].geometry.location.lat();
          document.getElementById('lng').value = results[0].geometry.location.lng();
    
          var marker = new google.maps.Marker({
            map: resultsMap,
            position: results[0].geometry.location,
            draggable: true
          });
          google.maps.event.addListener(marker, 'dragend', function(evt) {
            document.getElementById('lat').value = this.getPosition().lat();
            document.getElementById('lng').value = this.getPosition().lng();
          });
    
          resultsMap.setZoom(17);
          resultsMap.panTo(marker.position);
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
      });
    }
    google.maps.event.addDomListener(window, 'load', initMap);
    html,
    body,
    #map {
      width: 100%;
      height: 100%;
    }
    
    
    
    
    

提交回复
热议问题