【问题标题】:Google Maps Geocoding not working谷歌地图地理编码不起作用
【发布时间】:2015-12-19 10:13:03
【问题描述】:

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

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:变量地址没问题,我用控制台查过了。

【问题讨论】:

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


    【解决方案1】:

    地理编码器是异步的,您必须在可用时/在哪里使用回调函数中的结果。

    代码 sn-p:

    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);
    html,
    body,
    #googleMap {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <div id="googleMap"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 2017-11-01
      • 1970-01-01
      相关资源
      最近更新 更多