重新绘制地图以查找地址时使用 addListener(dragend) 检索 GPS 坐标

Retrieving GPS Coordinates with addListener(dragend) When Map is Redrawn to Find Address

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

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

我综合使用了 JavaScript API Docs and this Whosebug 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.

我想我遗漏了一些简单的东西。

我在 fiddle 的控制台中收到 javascript 错误:Uncaught ReferenceError: i is not defined 因为 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

代码片段:

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>