如何将反向地址解析值输入到输入字段中?

时间:2018-09-12 22:48:35

标签: javascript jquery google-maps

由Google为reverse geocoding coordinates into full address提供的示例代码很好,使用this stack question上的回复时,同样的结果也很好

根据示例,我不希望它们出现在信息框中,但是我想更新我的输入字段,这是我现在使用的代码,删除了反向地理代码,因为我无法转换将其转换为输入值:

<p id="addressHelper" ></p>
<div id="map"></div>

var myMarker = new google.maps.Marker({
 position: new google.maps.LatLng(47.651968, 9.478485),
 draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
 document.getElementById('addressHelper').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
  document.getElementById('addressHelper').innerHTML = '<p>Currently dragging marker...</p>';
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

1 个答案:

答案 0 :(得分:0)

玩了一会儿并且阅读了其他教程之后,这是我的解决方法:

<input type="text" id="location-text-box" name="address" placeholder="Your location..." required="">
<div id="map"></div>


    window.onload = function () {
      var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
      var mapOptions = {
        center: myLatlng,
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true,
        zoomControl: true
      };

      var map = new google.maps.Map(document.getElementById("map"), mapOptions);

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

      google.maps.event.addListener(marker, 'dragend', function (e) {
        var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
        var geocoder = geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
              $("#location-text-box").attr("value", results[1].formatted_address);
            }
          }
        });
      });
    }