因此,我有一个地图和一个表单,一旦用户填写地址+邮政编码,它将在地图上放置一个标记,但是我想使其可拖动并保持lat和long的值。

由于某种原因,我为什么不能移动标记?

JS:

function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: {lat: -34.397, lng: 150.644}
        });
        var geocoder = new google.maps.Geocoder();

        document.getElementById('postcode').addEventListener('blur', function() {

          geocodeAddress(geocoder, map);
        });
      }

      function geocodeAddress(geocoder, resultsMap) {
        var address = document.getElementById('address2').value +','+ document.getElementById('postcode').value;
        console.log(address);
        geocoder.geocode({'address': address}, function(results, status) {
          if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
              map: resultsMap,
              position: results[0].geometry.location,
              title: address,
              draggable:true,
            });
                google.maps.event.addListener(marker, 'dragend', function(marker){
        var latLng = marker.latLng;
        currentLatitude = latLng.lat();
        currentLongitude = latLng.lng();
        jQ("#latitude").val(currentLatitude);
        jQ("#longitude").val(currentLongitude);
                });
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });
      }

最佳答案

您应该在窗口级别声明var映射

var map;

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
.....


那么在您的geocodeAddress函数中,您应该参考地图以获取标记地图

         var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          title: address,
          draggable:true,
        });


查看代码,不应将标记放置在地图上,因为您引用了resultsMap

关于javascript - Google map ,根据输入插入图钉并使其可拖动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44699079/

10-11 14:01