【问题标题】:Retrieving GPS Coordinates with addListener(dragend) When Map is Redrawn to Find Address重绘地图以查找地址时使用 addListener(dragend) 检索 GPS 坐标
【发布时间】:2020-11-05 16:17:26
【问题描述】:

我正在尝试从客户最后拖动可移动 Pin 的地方检索 GPS 坐标。

如果客户使用原始 Pin,我可以检索坐标,但如果客户输入地址,例如“321 Elk Road, Page, AZ, USA”,我无法检索坐标。

我结合了来自JavaScript API Docs 和这个Stackoverflow post 的建议。

 /* JavaScript */
function initAutocomplete() {

  var uluru = {lat: 36.8737979, lng: -111.510586};
  
  var map = new google.maps.Map(
   document.getElementById('map'), {zoom: 6
   , center: uluru});

   
  var marker = new google.maps.Marker({
   position: uluru,
   map: map,
   draggable:true,
   title:"Drag me!"
 });

// This addListener works:

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


// Create the search box and link it to the UI element.
var input = document.getElementById("pac-input");
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);


// Bias the SearchBox results towards current map's viewport.
map.addListener("bounds_changed", function() {
  searchBox.setBounds(map.getBounds());
});

  var newMarkers = [];
  // Listen for the event fired when the user selects a prediction and retrieve
  // more details for that place.
   searchBox.addListener("places_changed", function() {
   var places = searchBox.getPlaces();

if (places.length == 0) {
  return;
}

// Clear out the old markers.
newMarkers.forEach(function(marker) {
  marker.setMap(null);
});
newMarkers = [];

// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
  if (!place.geometry) {
    console.log("Returned place contains no geometry");
    return;
  }
  var icon = {
    url: place.icon,
    size: new google.maps.Size(71, 71),
    origin: new google.maps.Point(0, 0),
    anchor: new google.maps.Point(17, 34),
    scaledSize: new google.maps.Size(25, 25)
  };

  // Create a marker for each place.
  newMarkers.push(
    new google.maps.Marker({
      map: map,
      icon: icon,
      draggable:true,
     title: "Drag Me!",
      position: place.geometry.location
    })
  );

  if (place.geometry.viewport) {
    // Only geocodes have viewport.
    bounds.union(place.geometry.viewport);
  } else {
    bounds.extend(place.geometry.location);
  }

  // This addListener does not work:
   
  google.maps.event.addListener(newMarkers, 'dragend', (function(marker, i) {
       return function() {
       document.getElementById("latbox").value = this.getPosition().lat();
       document.getElementById("lngbox").value = this.getPosition().lng();
       }
  })(marker, i));

});

map.fitBounds(bounds);
});
}

这里是JSFiddle

我想我错过了一些简单的东西。

【问题讨论】:

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


    【解决方案1】:

    我在您的 fiddle:Uncaught ReferenceError: i is not defined 的控制台中收到一个 javascript 错误,因为 i 未在此行中定义:})(marker, i));

    另一个问题是您尝试将事件侦听器添加到数组中,但这是行不通的,您必须将其添加到各个标记中:

      searchBox.addListener("places_changed", function() {
        var places = searchBox.getPlaces();
    
        if (places.length == 0) {
          return;
        }
    
        // Clear out the old markers.
        newMarkers.forEach(function(marker) {
          marker.setMap(null);
        });
        newMarkers = [];
    
        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function(place) {
          if (!place.geometry) {
            console.log("Returned place contains no geometry");
            return;
          }
          var icon = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
          };
    
          // Create a marker for each place.
    
          var marker = new google.maps.Marker({
            map: map,
            icon: icon,
            draggable: true,
            title: "Drag Me!",
            position: place.geometry.location
          })
          google.maps.event.addListener(marker, 'dragend', function() {
            document.getElementById("latbox").value = this.getPosition().lat();
            document.getElementById("lngbox").value = this.getPosition().lng();
          });
          newMarkers.push(marker);
          if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
          } else {
            bounds.extend(place.geometry.location);
          }
        });
    

    请注意,此代码将保留原始标记,您可能希望将其删除,以便您只拥有该标记或给定时间在地图上最后一次搜索的标记。

    proof of concept fiddle

    代码 sn-p:

    function initAutocomplete() {
    
      var uluru = {
        lat: 36.8737979,
        lng: -111.510586
      };
      // The map, centered at Uluru
      var map = new google.maps.Map(
        document.getElementById('map'), {
          zoom: 6,
          center: uluru
        });
      // The marker, positioned at Uluru
      var marker = new google.maps.Marker({
        position: uluru,
        map: map,
        draggable: true,
        title: "Drag me!"
      });
    
      google.maps.event.addListener(marker, 'dragend', function(event) {
        document.getElementById("latbox").value = this.getPosition().lat();
        document.getElementById("lngbox").value = this.getPosition().lng();
      });
    
    
      // Create the search box and link it to the UI element.
      var input = document.getElementById("pac-input");
      var searchBox = new google.maps.places.SearchBox(input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    
    
      // Bias the SearchBox results towards current map's viewport.
      map.addListener("bounds_changed", function() {
        searchBox.setBounds(map.getBounds());
      });
    
      var newMarkers = [];
      // Listen for the event fired when the user selects a prediction and retrieve
      // more details for that place.
      searchBox.addListener("places_changed", function() {
        var places = searchBox.getPlaces();
    
        if (places.length == 0) {
          return;
        }
    
        // Clear out the old markers.
        newMarkers.forEach(function(marker) {
          marker.setMap(null);
        });
        newMarkers = [];
    
        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function(place) {
          if (!place.geometry) {
            console.log("Returned place contains no geometry");
            return;
          }
          var icon = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
          };
    
          // Create a marker for each place.
    
          var marker = new google.maps.Marker({
            map: map,
            icon: icon,
            draggable: true,
            title: "Drag Me!",
            position: place.geometry.location
          })
          google.maps.event.addListener(marker, 'dragend', function() {
            document.getElementById("latbox").value = this.getPosition().lat();
            document.getElementById("lngbox").value = this.getPosition().lng();
          });
          newMarkers.push(marker);
          if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
          } else {
            bounds.extend(place.geometry.location);
          }
        });
    
    
        map.fitBounds(bounds);
      });
    }
    /* Always set the map height explicitly to define the size of the div */
    
    #map {
      height: 400px;
    }
    
    #description {
      font-family: Roboto;
      font-size: 15px;
      font-weight: 300;
    }
    
    #infowindow-content .title {
      font-weight: bold;
    }
    
    
    /* width */
    
     ::-webkit-scrollbar {
      width: 10px;
    }
    
    
    /* Track */
    
     ::-webkit-scrollbar-track {
      background: #f1f1f1;
    }
    
    
    /* Handle */
    
     ::-webkit-scrollbar-thumb {
      background: #888;
    }
    
    
    /* Handle on hover */
    
     ::-webkit-scrollbar-thumb:hover {
      background: #555;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Places Search Box</title>
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initAutocomplete&libraries=places&v=weekly" defer></script>
      <!-- jsFiddle will insert css and js -->
    </head>
    
    <body>
    
    
      <input id="pac-input" class="controls" type="text" placeholder="¿A dónde lo llevamos?">
    
      <table width="95%" height=5 0% border="1" cellspacing="2" cellpadding="2">
        <tbody>
          <!-- Begin Second Class -->
          <tr>
            <td>
    
              <div id="map"></div>
            </td>
          </tr>
        </tbody>
      </table>
    
      <div id="latlong">
        <p>Latitude: <input size="20" type="text" id="latbox" name="lat"> &nbsp Longitude: <input size="20" type="text" id="lngbox" name="lng"></p>
      </div>
    
    
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 2018-03-03
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多