Google地图:在方向切换目的地

时间:2011-09-09 08:29:33

标签: javascript google-maps

我想借助Google地图中的多个标记来切换我的路线。它适用于单一目的地。获取到该单一目的地的路线后,如果我点击任何其他目的地标记,则不会使用新路线更新。我有以下代码:

<script type="text/javascript">
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    var home = new google.maps.LatLng(40.703188,-74.005029);

    function initialize() {
      directionsDisplay = new google.maps.DirectionsRenderer();
      var myOptions = {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: home
      }
      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
      directionsDisplay.setMap(map);
    }

    function calcRoute(location) {
      var request = {
          origin: home,
          destination: location.position,
          travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });
    }

    function getNearbyStores() {
        var searchQuery = $('#searchBox').val();
        var request =
        {
            location: home,
            radius: '10000',
            name: [''+searchQuery]
        };  

        var service = new google.maps.places.PlacesService(map);
        service.search( request, callback );

        var marker;
        function callback(results, status)
        {

            if (status == google.maps.places.PlacesServiceStatus.OK)
            {

                var infowindow = new google.maps.InfoWindow();
                var marker, i;

                for ( i = 0; i < results.length; i++ )
                {
                    var place = results[i];

                    var loc = place.geometry.location;
                    var marker = new google.maps.Marker
                    ({
                        position: new google.maps.LatLng(loc.Pa,loc.Qa)
                    });
                    marker.setMap(map);

                    google.maps.event.addListener(marker, 'click', function() {
                        calcRoute(this);
                    });
                }

            }
        }
    }
</script>

2 个答案:

答案 0 :(得分:2)

我正在使用正在运行的代码发布另一个答案。

问题不在您发布的代码中,或者至少无法从中推断出来。我不知道你的searchQuery是怎样的,但是你说你得到了目的地的标记,那么应该没问题。但你也可以看一下。我将request.name替换为request.types并添加了一个主页位置标记,以便更好地了解行为。请注意,你的家庭位置在水面,你想开车 - 但令人惊讶的是谷歌可以处理它!

您可以在Firefox或Chrome中测试jsFiddle代码(IE中存在jsFiddle问题)。

答案 1 :(得分:0)

我发现了两个潜在的问题:

(1)

position: new google.maps.LatLng(loc.Pa,loc.Qa)
// should preferably be:
position: new google.maps.LatLng(loc.latitude(), loc.longitude())

(2)

google.maps.event.addListener(marker, 'click', function() {                            
     calcRoute(this); 
     // here 'this' refers to the marker, but calcRoute() expects location
     // should probably be:
     calcRoute(this.position);
});