谷歌地图,根据输入插入引脚并使其可拖动

时间:2017-06-22 12:10:45

标签: javascript jquery google-maps google-maps-api-3

所以我有一张地图和一张表格,一旦用户填写地址+邮政编码,就会在地图上添加一个标记,但是我想让它可以拖动并保持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);
          }
        });
      }

1 个答案:

答案 0 :(得分:2)

您应该在窗口级别声明var map

var map;

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

然后在你的geocodeAddress函数中你应该参考map for marker map

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

在您的代码中查找标记不应放在地图上,因为您引用了resultsMap