Reputation: 11
I'm looking to create driving directions between two points where one or both of the points does not have a road directly to it, but near it.
For example if you use the DirectionsService try to create a drive line between Moab, UT and Zion National Park, UT you will get back Zero_Results since there is no road to the CENTER (the lat, lng returned by google) of Zion Nation Park. If you do the same on google.com/maps you will see a drive line from Moab to the Zion National Park's East Entrance and a walk to the center of the park (where the pin is placed). How did they determine where to drive to for Zion National Park?
Upvotes: 0
Views: 449
Reputation: 161334
If you reverse geocode the coordinates returned by the geocoder for Zion National Park (37.2982022,-113.0263005), the first result will be the nearest location on the road.
code snippet:
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>
Upvotes: 2