Google maps API - 不接受来自地理编码的值

问题描述 投票:-1回答:2

我正在尝试在我的javascript中实现Google API地图。根据地址,我想获得相应的纬度/经度并在此位置显示地图。当我对该位置进行硬编码时,它可以工作。当我使用地理编码器中的值时,地图为空。这是代码:

<script>
     function initMap() {
         var loc = [];
         var geocoder = new google.maps.Geocoder();
         var address = "New York"; 

         geocoder.geocode({ 'address': address }, function (results, status) {
             if (status == google.maps.GeocoderStatus.OK) {
                 loc[0] = results[0].geometry.location.lat();
                 loc[1] = results[0].geometry.location.lng();
                 alert(loc); 

             } else {
                 alert("Geocode was not successful for the following reason: " + status);
             }
         });


         // Create a map object and specify the DOM element for display.
    var map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: loc[0], lng: loc[1] },
        scrollwheel: false,
        zoom: 8
    });
}

              </script>

警报(loc)功能显示正确的纬度和经度值,但地图似乎仍为空。知道为什么吗?

javascript google-maps-api-3 google-api google-geocoder
2个回答
0
投票

geocoder.geocode()异步工作。这意味着你应该将地图初始化放在回调函数中。目前,在触发地理编码器回调之前初始化地图。

function initMap() {
     var map;
     var loc = [];
     var geocoder = new google.maps.Geocoder();
     var address = "New York"; 

     geocoder.geocode({ 'address': address }, function (results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
             loc[0] = results[0].geometry.location.lat();
             loc[1] = results[0].geometry.location.lng();
             //alert(loc); 

             // Create a map object and specify the DOM element for display.
             map = new google.maps.Map(document.getElementById('map'), 
               {
                   center: { lat: loc[0], lng: loc[1] },
                   scrollwheel: false,
                   zoom: 8
               });

         } else {
             alert("Geocode was not successful for the following reason: " + status);
         }
     });

希望这可以帮助!


0
投票

Geocode API最近改变了一些东西。他们不接受#在地址

© www.soinside.com 2019 - 2024. All rights reserved.