谷歌地图API V3:如何显示从点A到点B(蓝线)的方向?

74

我有两个点在数据库中的纬度和经度,我希望在谷歌地图上显示从A点到B点的路线...

就像我们在这里看到的(谷歌地图方向)

链接中的图片

如何在地图上绘制该方向线?

6个回答

57

使用Google Maps API v3的路线服务(directions service)。它基本上与路线API相同,但是很好地打包在Google Maps API中,还提供了方便的方式来轻松地在地图上渲染路线。

有关在地图上呈现方向路线的信息和示例可以在Google Maps API v3文档的呈现方向部分找到。


2
@Tomik,在画完线条后,代码是否可以拍摄图像快照? - CodeGuru
请看第二个例子:有代码 :) - Nathan majicvr.com

43

使用 Javascript

我创建了一个工作演示,展示了如何通过JavaScript使用Google Maps API Directions Service:

  • DirectionsService对象用于发送和接收方向请求
  • DirectionsRenderer对象用于在地图上渲染返回的路线

function initMap() {
  var pointA = new google.maps.LatLng(51.7519, -1.2578),
    pointB = new google.maps.LatLng(50.8429, -0.1313),
    myOptions = {
      zoom: 7,
      center: pointA
    },
    map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
    // Instantiate a directions service.
    directionsService = new google.maps.DirectionsService,
    directionsDisplay = new google.maps.DirectionsRenderer({
      map: map
    }),
    markerA = new google.maps.Marker({
      position: pointA,
      title: "point A",
      label: "A",
      map: map
    }),
    markerB = new google.maps.Marker({
      position: pointB,
      title: "point B",
      label: "B",
      map: map
    });

  // get route from A to B
  calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);

}



function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
  directionsService.route({
    origin: pointA,
    destination: pointB,
    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);
    }
  });
}

initMap();
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    #map-canvas {
      height: 100%;
      width: 100%;
    }
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

<div id="map-canvas"></div>

在Jsfiddle上也可以找到示例代码: http://jsfiddle.net/user2314737/u9no8te4/

使用Google Maps Web Services

您可以使用API_KEY发出以下请求来使用Web服务:

https://maps.googleapis.com/maps/api/directions/json?origin=多伦多&destination=蒙特利尔&key=API_KEY

可以在Google开发者控制台中获取API_KEY,每天可免费请求2,500次。

请求的结果可以返回JSON或XML格式,用于在地图上绘制路径。

有关使用Google Maps Directions API的Web服务的官方文档在这里


嘿,我正在使用这段代码,它运行良好,但我想添加另一个标记A到C,并且方向不同,我尝试了很多方法,但都没有成功。 - Aniruddha Mishra
我对Google Maps API还比较陌生,虽然它能用,但是我该如何在路线上获取距离呢? - Sarz
2
@Sarz 看看我做的另一个演示 http://jsfiddle.net/user2314737/fLogwsff/ - user2314737

20
在您的情况下,这里使用directions service进行实现。
function displayRoute() {

    var start = new google.maps.LatLng(28.694004, 77.110291);
    var end = new google.maps.LatLng(28.72082, 77.107241);

    var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object
    directionsDisplay.setMap(map); // map should be already initialized.

    var request = {
        origin : start,
        destination : end,
        travelMode : google.maps.TravelMode.DRIVING
    };
    var directionsService = new google.maps.DirectionsService(); 
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

1
为了完整性,请将以下代码添加到您的程序中:var directionsService = new google.maps.DirectionsService(); - Dabbler
1
谢谢@Dabbler,我已经编辑了,如果你在答案中发现错误,请随意编辑。 - Vahe Harutyunyan
代码可以在画完线后拍摄图像快照吗? - CodeGuru
我不确定“方向服务”是否提供那种功能。 - Vahe Harutyunyan
好的回答!虽然,每次点击产品B的方向指示会增加点数 - 你如何重置路线/标记? :) - treyBake

6
  // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
  var map = new google.maps.Map(
    document.getElementById('MyMapID'),
    {
      center: {
        lat: Some.latitude,
        lng: Some.longitude
      }
    }
  );
  // Create a new directionsService object.
  var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: origin.latitude +','+ origin.longitude,
      destination: destination.latitude +','+ destination.longitude,
      travelMode: 'DRIVING',
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer({
          suppressMarkers: true,
          map: map,
          directions: response,
          draggable: false,
          suppressPolylines: true, 
          // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
          // AUTOMATICALLY DRAWN FOR YOU.
        });

        // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
        // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
        // LIST
        pathPoints = response.routes[0].overview_path.map(function (location) {
          return {lat: location.lat(), lng: location.lng()};
        });

        var assumedPath = new google.maps.Polyline({
         path: pathPoints, //APPLY LIST TO PATH
         geodesic: true,
         strokeColor: '#708090',
         strokeOpacity: 0.7,
         strokeWeight: 2.5
       });

       assumedPath.setMap(map); // Set the path object to the map

5
使用directions API来获取方向信息。
进行ajax调用,例如:
https://maps.googleapis.com/maps/api/directions/json?parameters

然后解析响应


代码在画完线之后是否可以拍摄图像快照? - CodeGuru

1

我正在使用弹出窗口在新窗口中显示地图。我正在使用以下URL:

https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE

HTML片段

<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接