为Google行车路线创建折线

时间:2011-12-04 07:40:24

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

我正在阅读关于Google API的内容,并且我希望实现谷歌地图的常用Google驾驶路线,这些路线有两个不同点。到目前为止,这是我的代码

(function() {
  window.onload = function() {

// Creating a map
var options = {
  zoom: 5,
  center: new google.maps.LatLng(36.1834, -117.4960),
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);

// Creating an array that will contain the points for the polyline
var route = [
  new google.maps.LatLng(37.7671, -122.4206),
  new google.maps.LatLng(34.0485, -118.2568)
];

// Creating the polyline object
var polyline = new google.maps.Polyline({
  path: route,
  strokeColor: "#ff0000",
  strokeOpacity: 0.6,
  strokeWeight: 5
});

// Adding the polyline to the map
polyline.setMap(map);

  };
 })();

两个城市之间有一条直线......

2 个答案:

答案 0 :(得分:1)

以下是使用DirectionsService的示例:

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

function initialize() {
    homeLatlng = new google.maps.LatLng(37.7671, -122.4206);

    var myOptions = {
        zoom: 10,
        center: homeLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var infowindow = new google.maps.InfoWindow({
        content: ''
    });

    directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: false,
        map: map, 
        markerOptions: {
            draggable: false
        },
        panel: document.getElementById("directionsPanel"),
        infoWindow: infowindow
    });

    var request = {
        origin:homeLatlng,
        destination:new google.maps.LatLng(34.0485, -118.2568),
        travelMode: google.maps.DirectionsTravelMode[DRIVING],
        unitSystem: google.maps.UnitSystem[METRIC]
    };

    directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
        }
    });
}

答案 1 :(得分:0)

如果您想根据行车路线(或步行路线或公交路线或骑车路线)绘制路线,请使用the Google Directions API。我不相信API不会为您绘制路线,但它会为您提供在折线中连接以显示路线所需的所有纬度/经度点。