具有地图重定位的自动完成地址字段值

时间:2019-07-16 19:35:48

标签: google-maps google-apps-script autocomplete

我从Google获得了自动填充地址字段,并通过更改其在地图上重新定位标记的字段来使它们在地图上定位标记。

1)是否可以通过更改地址字段中的值将全部信息也返回到自动完成栏?

2)是否可以在地图上移动标记以更改地址字段并使完整的信息栏自动完成?

var map, marker, geocoder;

function initialize() {
  initMap();
  initAutocomplete();
  initFieldListeners();
}

function initFieldListeners() {
  geocoder = new google.maps.Geocoder();
  document.getElementById("route").addEventListener("change", geocode);
  document.getElementById("street_number").addEventListener("change", geocode);
  document.getElementById("city").addEventListener("change", geocode);
  document.getElementById("postal_code").addEventListener("change", geocode);
}

function geocode() {
  var address = document.getElementById('route').value + " " + 
  document.getElementById('street_number').value + "," +
  document.getElementById('city').value + " " +
  document.getElementById('postal_code').value;

  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === 'OK') {
      map.setCenter(results[0].geometry.location);
      if (!marker) {
        marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
        });
      } else marker.setMap(null);
      marker.setOptions({
        position: results[0].geometry.location,
        map: map
      });
        for(let i = 0; i < results[0].address_components.length; i++){

      if(results[0].address_components[i].types[0] === "route"){
        document.getElementById('route').value = results[0].address_components[i].long_name;
      }
      if(results[0].address_components[i].types[0] === "city"){
        document.getElementById('city').value = results[0].address_components[i].long_name;
      }
  }
    }
  });
}

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 11.2,
      center: {lat: 40.64, lng: 22.945},
      zoomControl: true,
      mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false
    });
  }

var placeSearch, autocomplete;
var componentForm = {
  city: 'long_name',
  route: 'long_name',
  street_number: 'short_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();
  if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);
  } else {
    map.setCenter(place.geometry.location);
    map.setZoom(17);
  }
  if (!marker) {
    marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29)
    });
  } else marker.setMap(null);
  marker.setOptions({
    position: place.geometry.location,
    map: map
  });

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }


  for (var i = 0; i < place.address_components.length; i++) {


    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}



// START Force the dropdown to select!!!
// Find all inputs on the DOM which are bound to a datalist via their list attribute.
var inputs = document.querySelectorAll('input[list]');
for (var i = 0; i < inputs.length; i++) {
  // When the value of the input changes...
  inputs[i].addEventListener('change', function() {
    var optionFound = false,
      datalist = this.list;
    // Determine whether an option exists with the current value of the input.
    for (var j = 0; j < datalist.options.length; j++) {
        if (this.value == datalist.options[j].value) {
            optionFound = true;
            break;
        }
    }
  });
}
// END Force the dropdown to select!!!
autocomplete = new google.maps.places.Autocomplete(
                    /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
                    {types: ['(regions)'], componentRestrictions: {'country': "gr"}});

1 个答案:

答案 0 :(得分:0)

1)是的,有可能。只需将地址组件以正确的格式重新组装为字符串,然后替换pac_input DOM的值即可:

someElement.addEventListener('click', function() {
      document.getElementById("pac-input").value = reassembledAddress;
      document.getElementById("pac-input").focus();
      //autocomplete.setTypes(types);
});

2)您可以使用getPosition()类的google.maps.Marker方法来获取可拖动标记的LatLng,并将其输入到Reverse Geocoding Service请求中。