将警报消息更改为显示在 Google 地图地理编码服务搜索中的 div 中



我想更改警报消息(alert('地理编码不成功,原因如下:' + 状态);)显示在谷歌地图地理编码服务搜索的div 中。最好的方法是什么?

https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
      // Remove Div if Error message exist on the page
      var elem = document.getElementById("lsError");
      if (elem) {
          elem.parentNode.removeChild(elem);
      }
    } else {
      //alert('Geocode was not successful for the following reason: ' + status);
      // Add error message in the div id=lsError
      if (!document.getElementById("lsError")) {
          var node = document.createElement("div");
          node.id = "lsError";              
          var textnode = document.createTextNode("Please Enter Zipcode or City");        
          node.appendChild(textnode);
          document.getElementById("searchLocation").appendChild(node); 
      }

    }
  });
}
google.maps.event.addDomListener(window, 'load', initialize);

使用 CSS 表示错误消息。

<style>
  #searchLocation{
    position: relative;
  }
  #lsError{
    position: absolute;
    bottom: -20px;
    background: red;
    color: #fff;
    padding: 10px; 
  }
</style>

所以我最终使用 Javascript 在div 中创建错误消息。

最新更新