2012-03-30 10 views
0

:マップ上のマーカーとして問題私はGoogle MapsのAPIで、次を達成しようとしている

  • 表示to_address
  • ユーザーの場所を取得
  • 生成し、表示方向gps/user入力で指定された情報に基づいて

私はちょうどうまく動作するように最後の2つを得ています。私が現在している問題は、場所が提供されていない場合、to_addressを地図上のマーカーとして示しています。

これは私が使用しているコードです。最後の2つのステップが期待通りに機能することに注意してください。私はlatlngを使ってこれを達成できることを知っていますが、それは私の選択肢ではありません。私はそれにアドレスを提供する必要があります。

var geocoder; 
var directionDisplay; 
var directionsService = new google.maps.DirectionsService(); 
var to_pos; 
var to_address = '11161 84th ave delta bc'; 

function initialize() { 

    directionsDisplay = new google.maps.DirectionsRenderer(); 


    geocoder = new google.maps.Geocoder(); 

    geocoder.geocode({ 
     'address': to_address 
    }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      to_pos = results[0].geometry.location; 
     } 
    }); 

    var myOptions = { 
     zoom: 7, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     center: to_pos 
    }; 
    var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); 

    directionsDisplay.setMap(map); 
    directionsDisplay.setPanel(document.getElementById('directions')); 

    var control = document.getElementById('d_options'); 

    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function (position) { 
      var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 

      var infowindow = new google.maps.Marker({ 
       position: pos, 
       map: map, 
       title: "You" 
      }); 

      map.setCenter(pos); 
      $('#from').val(pos); 
      $('#d_options').trigger('collapse'); 
      calcRoute(); 

     }, function() { 
      handleNoGeolocation(true); 
     }); 
    } 
} 

function calcRoute() { 
    var start = document.getElementById('from').value; 
    var end = to_address; 
    $('#results').show(); 
    var request = { 
     origin: start, 
     destination: end, 
     travelMode: google.maps.DirectionsTravelMode.DRIVING 
    }; 
    directionsService.route(request, function (response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
      directionsDisplay.setDirections(response); 
     } 
    }); 
} 


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

答えて

0

ジオコーディングでは非同期要求が使用されます。 geocode()のコールバック内にマーカーを作成する必要があります

geocoder.geocode({ 
     'address': to_address 
    }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var to_pos = results[0].geometry.location; 

      new google.maps.Marker({ 
       position: new google.maps.LatLng(to_pos.lat(),to_pos.lng()), 
       map: map, 
       title: "Destination" 
      }); 
     } 
    }); 
関連する問題