谷歌地图(v3)获取地理定位地址到方向 - 给出状态确定,但没有方向(目标未找到)

时间:2013-04-02 21:14:09

标签: javascript google-maps-api-3

所以我正试着这个:

  • 输入地址
  • 获取地址
  • 的纬度/经度
  • 将其放入最终目的地的“路线”(纬度/经度)
  • 在我的两个div中获取路线

听起来很容易。该脚本返回状态“OK”。所以你应该认为它会起作用,但不会。

<div id="map_canvas" class="pic50"></div>
<div id="map_directions" class="text50"></div>

bring_me_back('map_canvas','map_directions','some address');
<script>
// bring me back
var directionDisplay;
var directionsService = new google.maps.DirectionsService();

function bring_me_back(call_back_map,call_back_directions,address) {
    var latlng = new google.maps.LatLng(51.764696,5.526042); // where you're at
  directionsDisplay = new google.maps.DirectionsRenderer();
  var myOptions = {
    zoom: 14,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false
  };

  var map = new google.maps.Map(document.getElementById(call_back_map),myOptions);
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById(call_back_directions));
  var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title:"My location"
  });

  // find the address
    geocoder = new google.maps.Geocoder (map);
    geocoder.geocode ( { 'address': address }, function(results, status)  {
    if (status == google.maps.GeocoderStatus.OK)  {
        var end = results [0].geometry.location; // where you need to go
      map.setCenter(results [0].geometry.location);
      marker.setPosition(results [0].geometry.location);
          var start = "51.764696,5.526042"; // where you're at (random place)
          var request = {
            origin:start,
            destination:end,
            travelMode: google.maps.DirectionsTravelMode.WALKING
          };
          directionsService.route(request, function(response, status) {
             alert("Directions was not successful for the following reason: " + status);
          });
    } 
    else {
      $('#'+call_back).html("Geocode was not successful for the following reason: " + status);
    }
  });
}
</script>

我知道我做了一些愚蠢的事情,因为我的错误控制台说:目标:[我的网站]#找不到

有趣的是,地图确实以带有标记的地理定位器的正确位置为中心。因此,除了推回方向之外,它做得很好(我认为)

1 个答案:

答案 0 :(得分:0)

您不会在DirectionsService回调例程中执行任何操作,除了输出消息“由于以下原因导致路线不成功:”+状态:

      directionsService.route(request, function(response, status) {
         alert("Directions was not successful for the following reason: " + status);
      });

如果要显示路线,则需要拨打DirectionsRenderer

尝试这样的事情:

directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
  } else  alert("Directions was not successful for the following reason: " + status);
});