我有一个应用程序显示数据库中的邮编,当点击一个按钮时邮政编码在弹出窗口中作为标记在Google地图上进行地理编码和显示。我试图在地图上显示两个标记之间的行车路线。我已将经地理编码的值保存到HTML span标记中,并试图将这些值用作路由的起点和终点。除了显示错误消息'由于NOT_FOUND引起的方向请求失败'的标记之间显示的路线之外,一切都有效。未找到Javascript/jQuery谷歌地图路线
任何想法如何让路线显示?
$(document).ready(function() {
$(".openMap").click(function() {
var directionsService = new google.maps.DirectionsService;
var mapLocation = $(this).prev().prev().prev().text();
var secondMarker = $(this).prev().prev().text();
window.markers = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: mapLocation }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Departure Location" });
markers.push(marker);
$('#route1').text(results[0].geometry.location);
}
});
var geocoder2 = new google.maps.Geocoder();
geocoder.geocode({ address: secondMarker }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Destination Location" });
markers.push(marker2);
$('#route2').text(results[0].geometry.location);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
});
directionsService.route({
origin: $('#route1').text(),
destination: $('#route2').text(),
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);
}
});
$("#map").dialog({ title: "Lift Location ", height: 500, width: 500, modal: true });
});
});
我得到你的代码中的错误:'未捕获的ReferenceError:directionsDisplay不defined' – geocodezip
什么是你的CSS/HTML看起来像?请提供证明您的问题的[最小,完整,测试和可读示例](http://stackoverflow.com/help/mcve)。 – geocodezip
https://jsfiddle.net/szw6yg6g/ – perfectDisguise