如何从initautocomplete形式获取值到initmap

时间:2019-07-11 21:15:16

标签: javascript java google-maps google-maps-api-3 autocomplete

我编写了以下代码:

function initialize() {
  initMap();
  initAutocomplete();
}
var map, marker;

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 = {
  locality: '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());
    });
  }
}
<div id="locationField">
  <input id="autocomplete" placeholder="Γράψτε τη διεύθυνσή σας" onFocus="geolocate()" type="text" />
</div>

<div id="address">
  <div id="row">
    <div class="slimField-left-3">
    <label class="label">Οδός</label>
      <input class="field" id="route" required="required" placeholder="Οδός"/>
    </div>
    <div class="slimField-right-1">
    <label class="label">Αριθμός</label>
      <input class="field" id="street_number" required="required" placeholder="Αριθμός"/>
    </div>
  </div>
  <div id="row">
    <div class="slimField-left">
    <label class="label">Περιοχή</label>
      <input method="get" list="locality-browsers" class="field" id="locality" required="required" placeholder="Περιοχή"/>
      <datalist id="locality-browsers">
      </datalist>
    </div>
    <div class="slimField-left">
    <label class="label">T.K.</label>
      <input method="get" list="postalcode-browsers" class="field" id="postal_code" maxlength="5" required="required" placeholder="Τ.Κ."/>
      <datalist id="postalcode-browsers">
      </datalist>
    </div>
  </div>
</div>
<div id="map"></div>
<input id="address-confirmation-btn" type="submit" class="btn" value="Η ΔΙΕΥΘΥΝΣΗ ΕΙΝΑΙ ΣΩΣΤΗ">

<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&libraries=places&callback=initialize&language=el&region=GR" defer></script>

我设法在地图上同时获取字段和标记,以从自动完成功能中获取值,但是如果我更改表单内的值,则无法推动市场发展,有人可以帮我吗这个吗?

有些值用希腊语表示,但是一旦输入自动完成地址,您便可以看到它们的含义。

例如,您可以在顶部表格(自动完成)中输入地址,并在该字段获取值后输入,如果您更改了地址编号,我也需要在地图中进行更改。

演示:fiddle

1 个答案:

答案 0 :(得分:0)

您链接的网站使用Geocoding service来实现。

尝试将以下代码添加到您的应用中,作为一个简单的示例,您可以将其用作指导。它只是将更改事件侦听器添加到您的文本字段中,从而对这些字段中的值进行地理编码,并相应地更新地图和标记。

请注意,我对这种真正的代码进行了快速编码,因此需要清理,但我希望它可以帮助您指出正确的方向。

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("locality").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('locality').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] === "locality"){
        document.getElementById('locality').value = results[0].address_components[i].long_name;
      }
  }