Google地图(v3)将地理位置地址转换为方向-给出状态OK,但没有方向(未找到目标)

Google maps (v3) get geolocate address into directions - gives status OK, but no directions (target not found)

本文关键字:方向 OK 目标 状态 地理位置 v3 地图 地址 转换 Google      更新时间:2023-09-26

所以我试着去做这个:

  • 输入地址
  • 获取地址的晚/长
  • 把它放在"方向"和最终目的地(迟/长)
  • 在我的两个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>

我知道我正在做一些愚蠢的事情,因为我的错误控制台显示:目标:[我的网站]#未找到

有趣的是,地图确实以地理定位器的正确位置为中心,并有标记。所以除了把方向往后推我觉得还行

你不需要在DirectionsService回调例程中做任何事情,除了输出消息"由于以下原因,Directions没有成功:" + status:

      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);
});