更改警报消息以显示在Google Map Geocoding服务搜索中的div中

时间:2015-03-10 19:41:34

标签: javascript jquery google-maps google-maps-api-3

我想更改提醒消息(提示('地理编码未成功,原因如下:' +状态);)将显示在Google地图地理编码服务搜索的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);

1 个答案:

答案 0 :(得分:1)

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中创建错误消息。好像它有效。