Google地图地理编码无法正常工作

时间:2015-12-19 01:33:58

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

我正在尝试对以下地址进行地理编码 - > Noguera 429 San Antonio de Padua使用Google Maps API。地址来自数据库,它存储在变量地址中。这是我的代码:

var address = '<?php echo $cerrajero["direccion"]?>'+' '+'<?php echo $cerrajero["ciudad"]?>';
var myCenter;

function initialize(){

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({
        "address": address
    },function(results){
         myCenter = results[0].geometry.location;
    });

    var mapProp = {
        center:myCenter,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

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

    var marker=new google.maps.Marker({
        position:myCenter,
        icon:'css/images/pin.png'
    });

    marker.setMap(map);
}

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

然后:

<div id="googleMap" class="map" style="height:250px;"></div>

最后:

.map{
    margin: 0 0 18px 0;
    width: 100%;
}

但是我的地图没有显示出来。它只显示一个灰色块,javascript有什么问题吗?

PS:变量地址没问题,我用控制台检查了它。

1 个答案:

答案 0 :(得分:0)

地理编码器是异步的,你必须在回调函数中使用它们可用时的结果。

代码段

&#13;
&#13;
var address = 'Noguera 429 San Antonio de Padua';
var myCenter;

function initialize() {

  var geocoder = new google.maps.Geocoder();

  geocoder.geocode({
    "address": address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      myCenter = results[0].geometry.location;
      var mapProp = {
        center: myCenter,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

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

      var marker = new google.maps.Marker({
        position: myCenter,
        // icon:'css/images/pin.png'
      });

      marker.setMap(map);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
&#13;
html,
body,
#googleMap {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap"></div>
&#13;
&#13;
&#13;