获取路线API v3

时间:2014-07-06 15:06:02

标签: javascript jquery html google-maps

我在谷歌地图上实现了一些选项,但我在GET DIRECTIONS部分遇到了麻烦。我已经阅读了许多答案,并且已经以多种方式实施,但仍然无法弄清楚出了什么问题。希望你能帮助我:

我试图获取路线:用户的位置(使用地理位置),到:一个点击的位置。

我已正确实施了上述所有内容,但我的路线代码出了点问题:

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

function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
//some styles
var mapProp = {
//disableDefaultUI:true,    
zoom:14,
mapTypeControlOptions: {
  mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
 },
scrollwheel: false,
zoomControl: true,
zoomControlOptions: {/*zoom on the left*/
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_CENTER
            }
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
 directionsDisplay.setMap(map);
var destinationmarker;

function placeMarker(destination) {
if ( destinationmarker ) {
destinationmarker.setPosition(destination);
} else {
destinationmarker = new google.maps.Marker({
  position: destination,
  map: map
});

}
$("#end").val(destination.lat()+","+destination.lng());

}

google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);

});
// some markers from db
//below is the location of the user with a marker
var marker=new google.maps.Marker({
position: pos,
animation:google.maps.Animation.BOUNCE,
icon:'ktuugeo.png',
});

marker.setMap(map); 

$("#start").val(pos.lat()+","+pos.lng());
google.maps.event.addListener(marker);

//supposedly the route function, set to execute on change
function calcRoute() {
var start = document.getElementById("start").value;
var final = document.getElementById("end").value;
var request = {
  origin: start,
  destination: final,
  travelMode: google.maps.TravelMode.WALKING
 };
 directionsService.route(request, function(response, status) {
 if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(response);
 }
 });
 }
 google.maps.event.addDomListener(window, 'load', initialize);

<body><div id="googleMap"></div>
<div id="dire" >
<textarea cols="20" rows="5" id="start" name="start"></textarea>
<textarea cols="20" rows="3" id="end" name="end" onchange="calcRoute();"></textarea>
</div>
</body>

这就是我猜的全部。我跳过了一些不影响的部分

1 个答案:

答案 0 :(得分:0)

嗯,我无法保证这是唯一要修复的细节,但至少我可以告诉你,calcRoute期望对象作为起点和终点。你给它喂了一根绳子。

如果您已经知道posdestination的值(您使用它们绘制两个标记),那么请再次使用它们,而不是将位置存储为DOM元素中的字符串。

function calcRoute(pos,destination) {
    var request = {
        origin: pos,
        destination: destination,
        travelMode: google.maps.TravelMode.WALKING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            directionsDisplay.setMap(map);
        }
    });
}

编辑:我错过了设置directionsDisplay地图属性。

在这里,我给你留下了一个工作范例:http://bl.ocks.org/amenadiel/acad781594f9976839c3