谷歌驾驶方向走向最近的道路

时间:2016-03-28 17:20:32

标签: javascript google-maps google-maps-api-3

我正在寻找两点之间的驾驶路线,其中一个或两个点没有直接通往它的道路,但靠近它。

例如,如果您使用DirectionsService尝试在Moab,UT和Zion National Park,UT之间创建一条驱动线,那么您将获得Zero_Results,因为没有通往ZION的中心(纬度,由谷歌返回的lng)的道路国家公园。如果您在google.com/maps上执行相同操作,则会看到从摩押到锡安国家公园东入口的驱动线,然后步行到公园中心(放置销钉的位置)。他们是如何决定前往锡安国家公园的?

1 个答案:

答案 0 :(得分:1)

如果你reverse geocode地理编码器为锡安国家公园返回的坐标(37.2982022,-113.0263005),第一个结果将是最近的路上位置。

proof of concept fiddle

代码段



var geocoder;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var start = "Moab, UT";
  directionsDisplay.setMap(map);
  geocodeAddress("Zion National Park", start);
}

function geocodeAddress(address, start) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      geocoder.geocode({
        'location': results[0].geometry.location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          calculateAndDisplayRoute(start, results[0].geometry.location)
        } else {
          window.alert('Reverse Geocode failed due to: ' + status);
        }
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function calculateAndDisplayRoute(start, end) {
  directionsService.route({
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);

html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
&#13;
&#13;
&#13;