0

私のjavascriptスキルは最高ではないので、私はただ愚かなことをしていると思います。次のコードは、空白の灰色のマップを生成します。

function initialize() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        geocoder = new google.maps.Geocoder();
        var address = "Minneapolis, MN";
        geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK)
           {
               lat = results[0].geometry.location.lat();
               lng = results[0].geometry.location.lng();
               addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());  
           }
           else
           {
                   alert(status);
           }
        });
        var mapOptions = {
          zoom: 7,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: addresslatlng
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('directions-panel'));
      }

ただし、単に「center:addresslatlng」を次のように変更した場合:

center: new google.maps.LatLng(-34.397, 150.644)

正常に動作します。

latlngを使用してみましたが、どちらも機能しません。

center: new google.maps.LatLng(lat, lng)

何か案は?

4

2 に答える 2

1

ジオコーディングは非同期です。コールバック関数内で結果を使用する必要があります。

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var address = "Minneapolis, MN";
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK)
       {
           lat = results[0].geometry.location.lat();
           lng = results[0].geometry.location.lng();
           addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());  
    var mapOptions = {
      zoom: 7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: addresslatlng
    };
    var map = new google.maps.Map(document.getElementById('map_canvas'),
        mapOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));
       }
       else
       {
               alert(status);
       }
    });
  }

実例

于 2013-03-25T02:39:41.967 に答える
0

これだと思います

lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();

本当にこのようになるはずです

lat = results[0].geometry.location.lat;
lng = results[0].geometry.location.lng;

また、作成latlonてから次の行で使用しないでください。これを変える

addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());

これに

addresslatlng = new google.maps.LatLng(lat, lng);
于 2013-03-25T02:32:17.310 に答える